0

so the idea is thrt you can make a user able to create new services after activating is_staff in django admin panel for it's user acccount then he will become a distributor this is the linked models for the service and the distributor:

models.py

class Distributor(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,null=True, blank=True)
service_ch =[('credit','credit'),('games','games')]
name = models.CharField(max_length=200,null=True,blank=False)
phone = PhoneNumberField(null=True,blank=False)
address = models.CharField(max_length=200,null=True,blank=False)
facebook = models.CharField(max_length=200,null=True,blank=False)
ccp = models.BigIntegerField(null=True,blank=False)
key = models.IntegerField(null=True,blank=False)
def __str__(self):
    return self.name


class Service(models.Model):
type_ch = [('credit','credit'),('game','game')]
currency_ch = [('€','€'),('$','$'),('DZD','DZD'),('Unit','Unit')]
distributor = models.ForeignKey(Distributor,on_delete=models.SET_NULL,null=True,blank=False)
model = models.CharField(choices=type_ch,max_length=20,null=True,blank=False)
name = models.CharField(max_length=200,null=True,blank=False)
price = models.FloatField(default=0.00)
currency = models.CharField(choices=currency_ch,max_length=20,null=True,blank=False)
available = models.FloatField(null=True,blank=False)
image = models.ImageField(default='defser.png')
def __str__(self):
    return self.name

the ServiceForm for creating a new service works fine if i choose the distributor manually

forms.py

class ServiceForm(forms.ModelForm):
class Meta():
    model = Service
    fields = ['distributor','model','name','price','currency','available','image']

def __init__(self, *args, **kwargs):
    super(ServiceForm, self).__init__(*args, **kwargs)
    self.fields['model'].widget.attrs['class'] = 'form-control-account'
    self.fields['name'].widget.attrs['class'] = 'form-control-account'
    self.fields['distributor'].widget.attrs['class'] = 'form-control-account'
    self.fields['price'].widget.attrs['class'] = 'form-control-account'
    self.fields['currency'].widget.attrs['class'] = 'form-control-account'
    self.fields['available'].widget.attrs['class'] = 'form-control-account'

views.py

def service_create(request):
user = request.user
if user.is_staff:
    if request.method == "POST":
        form = ServiceForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            messages.success(request,'Service has been added successfully.')

        return HttpResponseRedirect(reverse('saller'))
else:
    raise PermissionDenied()
form = ServiceForm()
return render(request, 'app/service_form.html', {'form': form})

the problem is the user with the distributor privilege should not be able to choose the distributor, because now he is able to create services by the name of other distributors,all he has to do is to choose the name of a different distributor which comes as a choice list exposing all the distributors names in the database!! how do i prevent this and make the form choose the current login distributor as the distributor for that newly created service by default???? is there such a thing or a way around this?

YahyaST18
  • 101
  • 1
  • 10
  • Hi, I think this post should help you: https://stackoverflow.com/questions/3419997/creating-a-dynamic-choice-field You can pass the user to your form `__init__` method and filter the choices available, thus the other possibilities won't be shown and the validation will verified that this constraint is respected – vctrd Jun 06 '20 at 21:30

1 Answers1

-1

If the user must login:

from django.contrib.auth.decorators import login_required

@login_required
def service_create(request):
user = request.user
if request.method == "POST": 
    if user.is_staff:
        form = ServiceForm(request.POST, request.FILES)
        if form.is_valid():
           db = form.save(commit=False)
           db.name = request.user
           db.save()
           messages.success(request,'Service has been added successfully.')
           return HttpResponseRedirect(reverse('saller'))
        else:
           error = form.errors.as_data()
           return render(request, 'app/service_form.html', {'form': form, 'error':error,})
     else:
        raise PermissionDenied()
else:
     form = ServiceForm()
     return render(request, 'app/service_form.html', {'form': form})

Form.py: you can remove 'name' from fields

Houda
  • 671
  • 6
  • 16
  • the user must log in to see the view page. In this case you will have the username: request.user. And the Form you should not display the name field, you will fill it out with the user name – Houda Jun 06 '20 at 22:38