Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to reset Django transaction after exception during multiprocessing?
How do you reset a Django transaction after a database exception (e.g. IntegrityError) occurs so you can continue to write to the database? I have several workers running in their own processes, all launched via the joblib package, that process database records. They all write their progress to a database via Django's ORM. Generally, they work fine, but occasionally, if one encounters an error, such as trying to write a record with a column that violates a unique constraint, then an IntegrityError is thrown. I have error handling logic to capture these, record the error, and allow it to skip to the next file to process. However, I'm finding that once one of these errors is encountered, that effectively prevents all further database access by that worker, as all further write attempts return the notorious error: django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. The weird thing is, I'm not directly using atomic(), so I'm assuming this is being implicitly run by Django somewhere. How do I work around this? I know the usual way to avoid this error is to explicitly wrap your writes inside atomic. So I … -
Django factory, problem with string primary key
My Django model has string as primary key class ActOfWithdrawal(models.Model): ext_act_id = models.CharField(max_length=256, primary_key=True) ready_to_print = models.BooleanField(default=False) class SapPosition(models.Model): act = models.ForeignKey(ActOfWithdrawal, on_delete=models.CASCADE) solution_for_position = models.CharField(max_length=1) Based on it I created two factories class ActOfWithdrawalFactory(factory.django.DjangoModelFactory): class Meta: model = 'apps.ActOfWithdrawal' django_get_or_create = ('ext_act_id',) ext_act_id = 'M' + str(factory.fuzzy.FuzzyInteger(1, 100000)) ready_to_print = False class SapPositionFactory(factory.django.DjangoModelFactory): class Meta: model = 'apps.SapPosition' act = factory.lazy_attribute(lambda a: ActOfWithdrawalFactory()) solution_for_position = factory.fuzzy.FuzzyText(length=1) But when I try to create SapPositionFactory I got such error self.withdraw_act = factories.ActOfWithdrawalFactory.create( ext_act_id='M3', ) self.sapposition = factories.SapPositionFactory.create( act=self.withdraw_act, solution_for_position='B' ) django.db.utils.DataError: invalid input syntax for type integer: "M3" Does factory boy supports Foreign key in string format? -
Django Time Zone issue
I'm having lot's of troubles with TimeZones in my Django application. For explanation purposes I'll jump right to the example : I have an object which has a TimeField(null=True, blank=True), and I basically want to show this time depending on the users timezone. I have a Middleware class which activates the timezone to the authenticated user : #'middleware.py' import pytz from django.utils import timezone class TimezoneMiddleware(object): """ Middleware to properly handle the users timezone """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: timezone.activate(pytz.timezone(request.user.timezone)) else: timezone.deactivate() response = self.get_response(request) return response Next to this, I'm pulling timezones from User model field timezone = models.CharField(max_length=128, choices=[(tz, tz) for tz in ['UTC'] + pytz.country_timezones('US')], default="UTC") which basically tells me the timezone user selected. And that's all good until I need to render the time adopted to the users timezone. So In my case user has the 'Pacific/Honolulu' timezone. Object time field was saved to 'American/New_York' timezone, and I'm still getting the same time no matter which timezone I select. What am I doing wrong? (I was fallowing the official docs for this) This is my template : {% load tz %} {% get_current_timezone as TIME_ZONE %} {% for object … -
Please if you know how to use django on pydroid, kindly read and answer this question
Please has anyone used django on pydroid? If you had, please can you describe, how you did it yourself, with examples. -
How to use memcache in Django?
I've seen all over problems using Memcached in Django projects which is considered to be The fastest, most efficient type of cache supported natively by Django For instances, Why doesn't memcache work in my Django? How to configure Memcache for Django on Google cloud AppEngine? Django doesn't use memcached framework memcache on django is not working How to use memcached in django project? How do you confirm django is using memcached? Configuring memcached with django What steps are needed to implement memcached in a Django application? How to use memcached in django project? So, how can we then use it? -
How can we remove null key : value pair from the Django response?
I'm getting the response as where I don't want to send the null key: value pair to the client How can we remove null key : value pair from the Django response? -
NameError: name 'DATABASES' is not defined Heroku
When I try to deploy a Django app at Heroku, I got this error. NameError: name 'DATABASES' is not defined. I have created Postgres from resources, but sill I don't know why I am getting this error -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.7.9 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> No change in requirements detected, installing from cache -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/build_a013ae50_/main_app/settings.py", … -
Bootstrap Card Shrinks after Search Button Clicked
I am pretty new to Boostrap, I've mainly been doing backend stuff, but am now doing front end work. I have a feature where the user searches a place and a list of nearby venues pops up. I'd like these to pop up in a card. I am using bootstrap cards. At the moment I have 2 problems: On load there is just this big card sitting there all clumsy: When I execute a search the card snaps down to a tiny scrollable version and all the content divs (map/card) seem to drop down a tad. I can probably figure out the javascript needed to make the card appear only when search occurs but I don't know how to set the card at a standard height after search (and prevent the divs from shifting slightly). What I'd like to achieve is a standard height for the card after search. Here is the for the initial card: <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Places Nearby</h5> <div id="cafes"> <div id="cafe_list"></div> </div> </div> </div> Here is the html for the function that generates the list: <div class="cafe-details d-flex"> <ul> {% for cafe in cafes %} <li> <address> <div> <h6 class="cafe-name" data-id="{{ cafe.id … -
Django Render HTML to PDF
I'm trying to render an html file to pdf however while the pdf functionality is working fine the rendering is working properly, no css. Also it renders the whole page, how can i render specific sections of the html page. I'm using xhtml2pdf. views.py file from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from django.views import View from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None data = { "company": "Name", } #Opens up page as PDF class ViewPDF(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('listings/listing.html', data) return HttpResponse(pdf, content_type='application/pdf') urls.py file path('pdf_view/', views.ViewPDF.as_view(), name="pdf_view"), html file <section class="p0"> <div class="container"> <div class="row listing_single_row"> <div class="col-sm-6 col-lg-7 col-xl-8"> <div class="single_property_title"> <a href="{{ listing.photo_1.url }}" class="upload_btn popup-img"><span class="flaticon-photo-camera"></span> View Photos</a> </div> </div> <div class="col-sm-6 col-lg-5 col-xl-4"> <div class="single_property_social_share"> <div class="spss style2 mt10 text-right tal-400"> <ul class="mb0"> <li class="list-inline-item"><a href="#"><span class="flaticon-transfer-1"></span></a></li> <li class="list-inline-item"><a href="#"><span class="flaticon-heart"></span></a></li> <li class="list-inline-item"><a href="#"><span class="flaticon-share"></span></a></li> <li class="list-inline-item"><a href="{% url 'pdf_view' %}"><span class="flaticon-printer"></span></a></li> </ul> </div> </div> </div> </div> </div> </section> Thank you! -
Why can't I access my template view when trying to register a user with Django?
I'm trying to implement a login functionality to a small Django project but when I go to the page with signup/signin form I get the 404 error. I am using Django default user model and auth forms. here are the views: def signup(request): if request.user.is_authenticated: return redirect('/') if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('/') else: return render(request, 'signup.html', {'form': form}) else: form = UserCreationForm() return render(request, 'signup.html', {'form': form}) def signin(request): if request.user.is_authenticated: return render(request, 'homepage.html') if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') else: form = AuthenticationForm(request.POST) return render(request, 'signin.html', {'form': form}) else: form = AuthenticationForm() return render(request, 'signin.html', {'form': form}) def log_out(request): logout(request) return redirect('/') here are the urls for my views: urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('signup/', views.signup, name='register'), path('signin/', views.signin, name='signup'), path('log_out/', views.log_out, name='log_out'), ] -
How to connect django model using foreignkey to a unique object in another model
Please how do I connect a model to a particular object in another model using either onetoonefield or foreignkey. Example class Post(models.Model): title = models.TextField(max_length=100, null=True) caption = models.CharField(max_length=1000) photo = models.ImageField(upload_to ='posts', null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes= models.IntegerField(default=0) dislikes= models.IntegerField(default=0) price = models.DecimalField(max_digits=10, decimal_places=2, null=True) digital = models.BooleanField(default=False, null=True, blank=False) location = models.PointField(srid=4326, null=True) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(unique=True, null=True) def __str__(self): return self.title @property def number_of_comments(self): return Comment.objects.filter(post_connected=self).count() class Comment(models.Model): **post_owner = models.OneToOneField( )** content = models.TextField(max_length=150) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post_connected = models.ForeignKey(Post, on_delete=models.CASCADE) I need to make post_owner in Comment Models, connected to author in Post models and not the entire Post models -
How to set default Field attributes i.e ( max_length) for the whole project - Django
What's the best way to set global default attributes for a model Field in Django ? Say i have many DecimalField() in various models in my app, and i want to set a default max_digits and decimal_places globally so it applies to all my DecimalFields ?? -
How to overwrite default django admin login view
I need to modify default django admin login functionality while keeping the rest untouched. I found the login.html template, but I need to work on some data I receive from modified login template. I see mentions of LoginView, and expected to see something like login method in which all the workflow is done, but see none. -
Django makemigrations return KeyError
So, when I tried makemigrations command I got this error *Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/migration.py", line 114, in apply operation.state_forwards(self.app_label, project_state) File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 165, in state_forwards for name, instance in state.models[app_label, self.model_name_lower].fields: KeyError: ('Conversation', 'user_pos')Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, *kwargs) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) … -
Name 'member_one' is not defined error in django
I want to get all Message_thread_private instances from database but I am getting error NameError: name 'member_one' is not defined Models.py: class Message_thread_private(models.Model): member_one = models.ForeignKey(User, related_name='member_one_messages', on_delete=models.CASCADE) member_two = models.ForeignKey(User, related_name='member_two_messages', on_delete=models.CASCADE) content = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.member_one.username def last_10_messages(): return Message.objects.order_by('-timestamp').all()[:10] views.py: @login_required def room(request, room_name): users = User.objects.filter(is_active=True).exclude(username=request.user.username) messages = Message_thread_private.objects.filter(member_one.username==request.user.username) return render(request, 'chat/room.html', { 'room_name_json': mark_safe(json.dumps(room_name)), 'username': mark_safe(json.dumps(request.user.username)), 'users': users, }) Why am i getting this error and how can I resolve this? -
What is the benefit of learning sql over sqlalchemy?
I was reading this: Using and connecting application through an ORM (Object Relational Mapper) like SQLAlchemy, Django ORM and so on is easier, faster, and more efficient than writing SQL - which means, more likely, it is preferred by the team. Good to have it in your skillset! So, I guess I would work with these platforms easier than the based ones? Can someone explain more smoothly? -
DEADLINE IS NEAR - NOTIFICATION
I'm doing a django-project that manages some projects. Each project has its deadline, and I'd like to implement the fact that when the deadline is in 3 days for example, the system sends a notification to the employee that is working on that project. I haven't decided if the notification should be sent as an email to the worker, or if it should be a notification sent to the worker's profile on my webapp. Could you give me some advice for which is the best way? And in either case how could i do it? Should I use celery or cron-job or something else? -
Celery identify list of worker running on multiple instance
I have celery set up on four different servers. Scheduling task Task #1, Task #2, Task #3 (Each task 10 worker) Task #1, Task #2, Task #3 (Each task 10 worker) Task #1, Task #2, Task #3 (Each task 10 worker) The first server is scheduling a task and the other three servers are executing a task. The setup is quite ok and working flowless. Now I came across one scenario that. Sometimes I need to stop any of the server 2 or 3 or 4. So I want to raise a shutdown broadcast signal for thee of the workers running on a particular server from the first scheduling server. How can I send a shutdown signal to a perticular server's worker? [Django celery, Redis queue] -
How can we use python for loop variable for the django class field?
I am sending ajax data to the below view I want to save it in the model I have created (mentioned below). Problem is, in that model I want 26 fields as the months so I created that by the add_to_class inside for loop. I don't know how much months user will input so I have to loop the list in views and save the data as: a = '100000' b = '120000' c = '15000' where a, b, c are the months and the rest values will be 0 default. Here is the model ''' class sold(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) Buyer = models.ForeignKey(buyer, on_delete=models.CASCADE) total = models.IntegerField() deposit = models.IntegerField() balance = models.IntegerField() months = models.IntegerField(default=12) tracker = models.IntegerField() insurance = models.IntegerField() def __str__(self): return f'{self.car} {self.Buyer} {self.total} {self.balance} for i in ascii_lowercase: sold.add_to_class('%s'%i, models.CharField(default=0, max_length=255,null=True, blank=True))''' NOTE: I have tried range(1, 27) with str and int but it didn't worked out. The views.py def sale_car_data(request): if request.method == 'POST': check = request.POST['car'] # if soldTo.objects.filter(car__chasis=check).exists(): # return HttpResponse('Already Exist') if 1==1: #Some condition here insurance = request.POST['insurance'] month = request.POST['month'] installment = request.POST.getlist('installment') installment = [json.loads(item) for item in installment] sale = sold(car=pro, Buyer=buyer, total=total, deposit=deposit, balance=balance, … -
registration and login form without use django authentications
I have a registration and login form but I dont want to use django authentications. I want to log in using the username and password that the user enters in the registrationform. How can I say that the content of the field inside the template is equal to the fields of my model.Im begginer in django and i hope help me. model.py class Customer (models.Model): CustomerUserName=models.CharField(unique=True,max_length=150) CustomerFirstName=models.CharField( max_length=150) CustomerLastName=models.CharField(max_length=150) CustomerPassWord=models.CharField(max_length=150) CustomerSerialNum=models.CharField(max_length=10) CustomerPhonNum=models.CharField(max_length=11) CustomerAddress=models.TextField(max_length=1000) CustomerEmail=models. EmailField(max_length=256) GENDER=( ('a','male'), ('b','female'), ) CustomerGender=models.CharField(max_length=1,choices=GENDER) CustomerBirthDate=models.DateField(null=True,blank=True) CustomerImage=models.ImageField(upload_to ='upload/userimage/' ) def __str__(self): return '%s %s' % (self.CustomerFirstName, self.CustomerLastName) return self.CustomerUserName.username form.py class SignUpForm(forms.ModelForm): CustomerFirstName = forms.CharField(max_length=150,label='firstname') CustomerLastName = forms.CharField(max_length=150,label=' lastname ') CustomerEmail = forms.EmailField(max_length=256,label=' Email',widget=forms.TextInput( attrs={ 'placeholder': 'example@gmail.com'} )) CustomerPhonNum = forms.CharField(max_length=150,label=' phone number',widget=forms.TextInput( attrs={'class':'phone' ,'placeholder': '09xxxxxxxxx'} )) CustomerPassWord = forms.CharField( label=' password ', widget=forms.PasswordInput( attrs={'class':'psw', 'pattern':'(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}' } )) class Meta: model = Customer fields = ['CustomerUserName','CustomerFirstName', 'CustomerLastName','CustomerEmail','CustomerPhonNum','CustomerPassWord'] class SignInForm(forms.ModelForm): CustomerPassWord = forms.CharField( label=' password', widget=forms.PasswordInput( attrs={'class':'psw', 'pattern':'(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}' } )) class Meta: model = Customer fields = ['CustomerUserName','CustomerPassWord'] view.py def signin(request): form=SignInForm() if request.method== 'POST': form=SignInForm(data=request.POST) if form.is_valid(): UserName = form.cleaned_data['CustomerUserName'] PassWord = form.cleaned_data['CustomerPassWord'] return render(request,'index.html',{'form': form}) else: return HttpResponse('this user is not exist') else: form=SignInForm() return render(request,'signin.html',{'form': form}) def signup(request): form = SignUpForm() if request.method=='POST': … -
Run a celery task every 90 mins from 1:30am-6am UTC
Can we make a celery task run at 1:30, 3:00, 4:30, 6 AM using single crontab function? i.e 'schedule': crontab(minute=30, hour='1, 3, 4, 6') will run it at 1:30, 3:30, 4:30, 6:30AM but I want it to run every 90 mins from 1:30 to 6AM -
How to define multiple serializers in a django mixin?
I'm currently writing views to display my objects. But in those views, I want to have some query parameters to filter my objects. I'm using drf-yasg to generate the schema and django-rest-framework for the views. So for example I have this serializer for the filter data: class IceCreamFilterSerializer(serializers.Serializer): start = serializers.DateField() and I have this view: @method_decorator(name='list', decorator=swagger_auto_schema( manual_parameters=[openapi.Parameter('start', openapi.IN_QUERY, type=openapi.TYPE_STRING)] )) class IceCream(ListModelMixin, GenericViewSet): serializer_class = IceCreamSerializer def get_queryset(self): filter_data = IceCreamFilterSerializer(data=self.request.query_params) start = filter_data['start'] qs = IceCream.objects.filter(created__gte=start) return qs This works okay, but then I want to implement this method to my other views. So I want to create a Mixin so that I can inherit the Mixin in the view classes. But the problem is, how do I define the input and output serializer in the Mixin? Do I have to override get_serializer_class there? Note: I know I can use FilterSet from DRF to filter, but I feel like this method is the better way for my case. Any help would be really appreciated. Thanks in advance! -
Altering the fields of User custom model in Django
I have already built in backend like this. Now I have to make api for user registration. For that I need to remove 'name' field from class User(AbstractBaseUser, PermissionsMixin): and add with first_name and last_name instead. Can I have the privilige of doing that directly?? Because when I try that, mySQL data base is showing error that cant drop the perivious field of 'name'. What is the issue?? class UserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): """Creating new user and saving the user.""" if not email: raise ValueError('Admin must have a valid email') user = self.model(email=self.normalize_email(email), **kwargs) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """Creates and saves a new super user""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """ Custom user model that supports using email instead of username """ email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) object = UserManager() USERNAME_FIELD = 'email' -
Adding a class attribute to a queryset field on ModelForm
So I'm trying to add a class attribute to this field on my ModelForm to allow for Bootstrap styling: category = forms.ModelChoiceField(queryset=Category.objects.all()) I tried this: category = forms.ModelChoiceField(queryset=Category.objects.all(), widget=forms.ModelChoiceField(attrs={'class':'form-control'})) and got this error: TypeError: __init__() missing 1 required positional argument: 'queryset' My complete ModelForm: class NewListingForm(forms.ModelForm): class Meta: model = Listing fields = ["title", "description", "start_price", "image", "category"] title = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off', 'class':'form-control'})) description = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off', 'class':'form-control'})) start_price = forms.DecimalField(label='Starting Bid Price (£)', widget=forms.NumberInput(attrs={'class':'form-control'})) image = forms.URLField(widget=forms.URLInput(attrs={'autocomplete':'off', 'class':'form-control'})) category = forms.ModelChoiceField(queryset=Category.objects.all(), widget=forms.ModelChoiceField(attrs={'class':'form-control'})) (I was going to do the fields = [] labels={} widgets={} format but I couldn't work out how to do that with a queryset field) -
How to add new values to Many2Many field Django
I'm currently working on a small Django project and I'm having an issue setting a many2many field's value. in my models I have something like : class Operation(models.Model): day = models.DateField() realized_by = models.ManyToManyField(User, related_name="consumer", blank = True) ... in my views.py I want to check: if there is an Operation instance that happened today, then add request.user to the relized_by users list else, create an Operation instance and make request.user the first element of realized_by users list Thank you for your answers in advance.