Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Why is full URL being returned for some FileFields, but not others?
So I have this view that returns a list of posts that are like a facebook wall post. As you can see in the above image this encompasses: images, videos maybe, avatar, text, and metadata about the post and metadata about the user. I get all the relevant data for the post via table joins. For some reason Video and Photo are returning the full URL with the domain of MEDIA_URL prepended, but creator_avatar_url is only returning the tail end of the url (i.e something like /media/user/avatar.jpeg). Why is my code not returning the full URL for creator_avatar_url? model.py class User(AbstractDatesModel): uuid = models.UUIDField(primary_key=True) username = models.CharField(max_length=USERNAME_MAX_LEN, unique=True, validators=[ MinLengthValidator(USERNAME_MIN_LEN)]) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) avatar = models.ImageField(upload_to=avatar_directory_path, blank=True, null=True) @property def avatar_url(self): return self.avatar.url class Post(models.Model): uuid = models.UUIDField(primary_key=True) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN, validators=[MinLengthValidator(POST_MIN_LEN)]) class Photo(AbstractBaseModel): post = models.OneToOneField(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to=images_directory_path) @property def image_url(self): return self.image.url class Video(AbstractBaseModel): post = models.OneToOneField(Post, on_delete=models.CASCADE) video = models.FileField(upload_to=videos_directory_path) @property def video_url(self): return self.video.url helper.py def query_to_full_post_data_serializer(request, post_query_set: QuerySet): query_set_annotated = post_query_set.annotate( creator_username=F('creator__username'), creator_avatar_url=F('creator__avatar'), ).prefetch_related( … -
Django view with slug and id
I have this URL path('kategorie/<slug:slug>-<int:pk>', views.category_view, name="category_view"), And this view def category_view(request,slug,pk): categories = EcommerceProductCategory.objects.all().filter(slug=slug, pk=pk).order_by('-created_at') product = Product.objects.filter(slug=slug).order_by('-created_at') context = { 'categories': categories, 'product': product, } return render(request, 'ecommerce/category_view.html', context=context) Now i wanna show on that page category_view.html only the products that have particular slug and pk. Lets say kategorie/cat-4. Cat is the category.slug and the category.pk is 4 and i only wanna show the products that have this category and this pk. (Btw yes product is connected with Ecommerce via M2M) -
Multiple Widgets in Form Field - Django Forms
I'm working on a form in Django and it has a select element with a unique ID. This is what I'm currently doing: instance_type = forms.CharField(label='Instance Type', widget=forms.Select(choices=INSTANCE_TYPES), widget=forms.TextInput(attrs={'id':'instance_type'})) The problem is that Django is giving me a syntax error that says: SyntaxError: keyword argument repeated: widget I need to combine these two widgets into one, but haven't found a solution to it. Any help is appreciated. Thank you all! -
pipenv.exceptions.ResolutionFailure; ERROR: Disabling PEP 517 processing is invalid
I ran into what seems to be a dependency conflict when trying to run pipenv lock but can't seem to figure out what is causing this: [pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. You can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation. Hint: try $ pipenv lock --pre if it is a pre-release dependency. ERROR: Disabling PEP 517 processing is invalid: project specifies a build backend of setuptools.build_meta:__legacy__ in pyproject.toml I tried to debug using the suggested pipenv install --skip-lock and pipenv graph and wasn't able to spot any conflicts in the output below: bleach==4.1.0 - packaging [required: Any, installed: 21.3] - pyparsing [required: >=2.0.2,!=3.0.5, installed: 3.0.6] - six [required: >=1.9.0, installed: 1.16.0] - webencodings [required: Any, installed: 0.5.1] bpython==0.21 - curtsies [required: >=0.3.5, installed: 0.3.5] - blessings [required: >=1.5, installed: 1.7] - six [required: Any, installed: 1.16.0] - cwcwidth [required: Any, installed: 0.1.4] - cwcwidth [required: Any, installed: 0.1.4] - greenlet [required: Any, installed: 1.1.1] - pygments [required: Any, installed: 2.10.0] - pyxdg [required: Any, installed: 0.27] - requests [required: Any, installed: 2.26.0] - certifi [required: >=2017.4.17, installed: 2021.5.30] … -
Django: Script that executes many queries runs massively slower when executed from Admin view than when executed from shell
I have a script that loops through the rows of an external csv file (about 12,000 rows) and executes a single Model.objects.get() query to retrieve each item from the database (final product will be much more complicated but right now it's stripped down to the barest functionality possible to try to figure this out). For right now the path to the local csv file is hardcoded into the script. When I run the script through the shell using py manage.py runscript update_products_from_csv it runs in about 6 seconds. The ultimate goal is to be able to upload the csv through the admin and then have the script run from there. I've already been able to accomplish that, but the runtime when I do it that way takes more like 160 seconds. The view for that in the admin looks like... from .scripts import update_products_from_csv class CsvUploadForm(forms.Form): csv_file = forms.FileField(label='Upload CSV') @admin.register(Product) class ProductAdmin(admin.ModelAdmin): # list_display, list_filter, fieldsets, etc def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} extra_context['csv_upload_form'] = CsvUploadForm() return super().changelist_view(request, extra_context=extra_context) def get_urls(self): urls = super().get_urls() new_urls = [path('upload-csv/', self.upload_csv),] return new_urls + urls def upload_csv(self, request): if request.method == 'POST': # csv_file = request.FILES['csv_file'].file # result_string = … -
Import "rest_framework" could not be resolved
I was installing a django Rest Framework for my project. I installed this with pip install djangorestframework it worked perfectly fine, then i add a rest_framework line into INSTALLED_APPS in settings.py. And now at this point I want to import Response from rest_framework in views.py but it shows: ImportError: cannot import name 'Response' from 'rest_framework' It looks like it's not installed I guess, but it is ... I checked even a version of rest_framework from the console and it shows everything. Do you have any idea what is going on ? -
why I am having TypeError: expected string or bytes-like object - django
hello I am doing an app with django and I was using sqlite I want to migrate to postgres now but I am having this error I think something related to time but I really don't know how to solve it. Applying users.0018_auto_20210911_1322...Traceback (most recent call last): File "C:\Users\lenovo ideapad\Desktop\callservices\manage.py", line 22, in <module> main() File "C:\Users\lenovo ideapad\Desktop\callservices\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\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 "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\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 "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\db\migrations\migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\db\backends\base\schema.py", line 490, in add_field definition, params = self.column_sql(model, field, include_default=True) File "C:\Users\lenovo ideapad\Desktop\callservices\env\lib\site-packages\django\db\backends\base\schema.py", line 237, in column_sql default_value = self.effective_default(field) … -
Ajax POST fails to due missing CSRF token
I've got a rather odd problem. I've got probably 100s of ajax calls back to my backend. They all work except for one. For some reason, on one page that doesn't require that the user be logged in to access (but can be logged in when they access the page), the ajax query fails due to missing CSRF token. When I clear history/cookies in Chrome, the ajax call is successful. Any thoughts on what could be causing this? Thanks! -
How to run a script or command every time a terminal (zsh) opens in a VSCode workspace?
I am working on a Django project on macOS. My terminal runs zsh. I want to create helpful aliases, like run instead of python manage.py runserver, but, I don't want to run these commands every single time I open a new terminal. So here's what's going on: I don't want to create these aliases or run any command in my home directory's .zshrc or .zprofile because I don't want them to be system-wide. I want to run them on local project directories exclusively. Every time we open a new terminal on VSCode, when working with a selected Python virtual environment, a command to activate it gets run first thing. It will look like this: source /Users/.../venv/bin/activate This (should be) carried out by Microsoft's Python extension. I cloned its repo but had no luck finding where they place this in VSCode's configurations. Where do they? Some posts on StackOverflow told me to take a look on the terminal.integrated.profiles.osx setting. I did, and the closest thing I came to was creating this profile: "zsh (Django)": { "path": "zsh", "args": [ "-c", "source setup.sh" ] } setup.sh is a file on my working directory. Its only command, for now, is echo "Hello World". … -
pytest-django and conservative db access
I know that pytest-django takes a ‘conservative’ approach to database access: https://pytest-django.readthedocs.io/en/latest/database.html And I don’t have a problem with that, but as that same page makes clear, the db being accessed is still a test db that is being setup and then torn down, so why the ‘need’ to be ‘conservative’? The real database isn’t being touched at all, so there’s no risk, or am I missing something? Thanks. -
Handling many text input fields in Django?
I'm using Django 3 (still) on my resume website. I'm working on a Sudoku Solver as an example personal project, so I have 81 text input fields in a grid. I'm trying to find the least painful way to handle up to 81 inputs in Django, so I can pass the inputs to my Python function(s) that handle the sudoku logic. How would I go about getting the user input into my views.py and handling all of them? I'm wanting to take whichever cells in which the user inputs numbers, process them through my Python function(s), and then send the full puzzle back into the cells once processed. I'm not super experienced with forms and form data in HTML just yet. For reference, here is my HTML that handles the grid. I know I'll need to add in maximum text length for the input fields, to ensure the user can only enter 1 digit per cell. <section class="resume-section"> <div class="d-lg-grid" id="grid"> <div id="grid-1"> <input type="text" size="3" id="cell1"> <input type="text" size="3" id="cell10"> <input type="text" size="3" id="cell19"> <input type="text" size="3" id="cell28"> <input type="text" size="3" id="cell37"> <input type="text" size="3" id="cell46"> <input type="text" size="3" id="cell55"> <input type="text" size="3" id="cell64"> <input type="text" size="3" id="cell73"> </div> … -
Django How to bulk update all child object?
I am building help desk system on django. Where anyone can open ticket for customer support. Assume I have an parent object #001 and every child object of this parent have same ticket id. See the screenshot for better understand: child1 and child2 have same ticket id like their parent object. How to apply bulk update on all objects if they have same ticket id?. Assume if I change ticket status of child2 then I want it will also apply bulk update of child1 and parent object. any idea how to do that on django? here is my code: models.py class Contact(models.Model): choice = (("pending","pending"),("solved","solved"),("closed","closed")) ticket_status = models.CharField(choices=choice,max_length=100,default="pending") parent =models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='contact_parent') sno = models.AutoField(primary_key=True,) def save(self,*args,**kwargs): if not self.parent and not self.support_ticket: self.support_ticket= str(rand_support_ticket()) if not self.support_ticket: self.support_ticket = self.parent.support_ticket super(Contact,self).save(*args,**kwargs) forms.py class SupportAgentFrom(forms.ModelForm): class Meta: model = Contact fields = ['support_message','ticket_status'] views.py def AddReplySupport(request,slug): # fetch the object related to passed id obj = get_object_or_404(Contact, slug = slug) # pass the object as instance in form form = SupportAgentFrom(request.POST or None, instance = obj) if form.is_valid(): form.instance.support_agent = request.user form.save() now I can update only single object once at a time. I want to apply bulk … -
Heroku being extremely slow when there's a lot of requests
I have a Django app deployed to Heroku. A few days ago it was totally fine, when my traffic was low. I had 5 requests per second, and the response time was not more than 2 seconds. However, I have recently started getting a lot of traffic. My requests per second have gone up to 50, and now my response time is 30 seconds. I'm trying to figure out whats going on. Naturally I scaled up my dynos. I went from a Standard tier dyno to a professional dyno with 2 workers. I also updated my Procfile to have Gunicorn use 12 workers: web: gunicorn wsgi -w 12 --timeout 30 I also updated my database to a standard tier so I'd have more connections. I realized I wasn't using Gzip compression with Django, so I added the Gzip middleware as well 'django.middleware.gzip.GZipMiddleware'. However, surprisingly, the request time is still 30 seconds or more. None of these new changes have made a difference. I also optimized some of my database queries, and that had a very minor impact. All this is leading me to think there's something wrong with either how my Django app is set up or Heroku itself, but … -
running subprocess to capture output for node js
I have a file add.js and it's content is- var add = (a, b) => a + b; const args = process.argv; console.log(add(args[2], args[3])); and when I run it from django using - def cmdline(command): process = Popen( args=command, stdout=PIPE, shell=True, universal_newlines=False ) return process.communicate()[0] print(cmdline("node folder/add.js 10 10")) it is giving - b'1010\n' and when I pass - print(cmdline("node folder/add.js 10")) it's giving - b'10undefined\n' I do not have much experience with js so how do I add them as integers. Thanks -
How to create Article tags from splitting the Title in Django
I want to create articles tags from the title of a RSS feed post. Then save the tags into a DB with a post_id of the title i got the tags from at the same time. Something like this: Title = "Voyant raises $15M to scale production of its tiny, inexpensive lidar tech" Tags = ['Voyant', 'Raises', '$15M', 'To', 'Scale', 'Production', 'Of', 'Its', 'Tiny', 'Inexpensive', 'Lidar', 'Tech'] Assuming the post_id is 1, the Tags table should look like: id | tag | post_id -------------------------------- 1 | Voyant | 1 2 | Raises | 1 I have 3 models in my table(Source, Posts & Tags). class Source(models.Model): name = models.CharField(max_length=500, verbose_name='Website Name') class Posts(models.Model): title = models.CharField(max_length=500, verbose_name='Post Title') source = models.ForeignKey(Source, on_delete=models.CASCADE, verbose_name='Source') class Tags(models.Model): name = models.CharField(max_length=500) post = models.ForeignKey(Posts, on_delete=models.CASCADE, verbose_name='Posts') So so far i was able to split the title above. title = item.title strip_away = title.replace(",", "").replace(":", "").replace("(", "").replace(")", "").replace("'", "").replace("[", "").replace("]", "").replace("!", "").replace("?", "").replace("-", " ") capital = strip_away.title() article_tags = capital.split() But now my problem comes during the saving part. def fetch_articles(): feed = feedparser.parse("my_site_of_preference") source = Source.objects.get(pk=1) source_id = int(source.pk) source_name = source save_new_articles(source_id, source_name, feed) def save_new_articles(source_id, source_name, feed): selected_source_id = source_id … -
Build invite-code user registration Django 4.0
I want build a invite-code registration user system in Django. For registration a new user need to fill two fields of form 'INVITE' (UUID getted from already exists user) and 'PASSWORD'. After send data (requests.POST) Django check invite-code (finds it in the database and correlates it with the user id) and if result is success Django generate 8-symbols username and add new user record in db with fill ID, USERNAME, PASSWORD, INVITER, UUID. For example, the invitation code is the UUID of an existing user. myapp/model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser class Users(AbstractBaseUser): def login_gen(): import uuid uuid = uuid.uuid4() return str(uuid)[:8], uuid id = models.BigAutoField(primary_key=True) username = models.CharField("Username", max_length=8, null=False, blank=False, db_index=True, unique=True, default=login_gen()[0]) password = models.CharField("Password", max_length=255, null=False, blank=False) role = models.BooleanField("Right or Left", null=False, blank=False) inviter = models.ForeignKey('Whos invite', self.id, null=False, blank=False) #... other fields UUID = models.UUIDField("UUID", null=False, blank=False, default=login_gen()[1]) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['username', 'password', 'role'] def __str__(self): return self.username I would like to implement the task with authentication tools built into Django, but I can't cope with the user model (model.py), form (forms.py) and manager (managers.py) in any way. -
Django one to many models - How to create the "many" when the "one" is created?
There are a lot of questions along these lines, but so far as I can tell, but many are quite old and I haven't found one that helped me understand my use case. I think I want to be looking at signals, but I'm not clear on exactly what I should be doing in terms of Django patterns and best practices. Here's my Model code: from django.db import models from django.db.models.fields import SlugField, TextField from django.utils import timezone # Hexes have Terrains, which impart intrinsic properties, like base speed and .png image # They're NOT 1:1 with Hexes IE) You might want Slow and Normal Grasslands with the same image class Terrain(models.Model): FAST = 'F' NORMAL = 'N' SLOW = 'S' SPEED_CHOICES = [ (FAST, 'Fast'), (NORMAL, 'Normal'), (SLOW, 'Slow'), ] name = models.CharField(max_length=64) speed = models.CharField(max_length=6, choices=SPEED_CHOICES, default=NORMAL) image = models.ImageField(upload_to='images/', blank=True) def __str__(self): return self.name # Grids establish the dimensions of a HexMap. Grids may be used in many HexMaps class Grid(models.Model): name = models.CharField(max_length=64) size = models.IntegerField(default=72) num_rows = models.IntegerField(default=10) num_cols= models.IntegerField(default=10) def __str__(self): return self.name # Hexes represent the "tiles" on a Grid. A single Hex may appear in many Grids class Hex(models.Model): name = models.CharField(max_length=64, … -
Implement REST API with Django
This is my Django model: class M(models.Model): a = models.IntegerField() b = models.IntegerField() This is the serializer: class MSerializer(ModelSerializer): class Meta: model = M fields = ['a', 'b'] I would like to be able to implement these REST APIs: 127.0.0.1:8000/m/ (GET list of all elements, POST new element) 127.0.0.1:8000/m/:id/ (GET details of element with id id) 127.0.0.1:8000/n/:a/m/ (GET all elements with a specific a field) So far this is the view and urls that I implemented: class MViewSet(ModelViewSet): queryset = M.objects.all() serializer_class = MSerializer router = DefaultRouter() router.register(r'm', MViewSet) urlpatterns = [ path('', include(router.urls)), ] However, in this way the third use case is not working. How can I modify my code to make the third case work? I'd prefer to use as few lines of code as possible (i.e., I would like to use some Django built-in functionalities). -
Form.as_p works fine but individual form fields is not submitting correctly
I have set up my template by import my form with form.as_p before, and it works fine. However, I need to specify each field, as I have a field that I don't want the user to see (and I need to have it in my django admin so I can't exclude it from the form). However, when I set-up the form with it's individual fields, and submit it, I don't get redirected, I just get back to the filled out form. I have set-up a number of print fields, and have also tried to print in form_invalid but nothing shows up, I have no idea what the issue is. Can someone suggest how to fix this or maybe solve it another way? The form in the template <form method="post" enctype="multipart/form-data" id="adForm" data-municipalities-url="{% url 'ajax_load_municipalities' %}" data-areas-url="{% url 'ajax_load_areas' %}" novalidate> {% csrf_token %} <!-- {{ form.as_p }} --> {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.province.errors }} {{ form.province.label_tag }} {{ form.province }} </div> <div class="fieldWrapper"> {{ form.municipality.errors }} {{ form.municipality.label_tag }} {{ form.municipality }} </div> <div class="fieldWrapper"> {{ form.area.errors }} {{ form.area.label_tag }} {{ form.area }} </div> <div class="fieldWrapper"> {{ form.name.errors }} {{ form.name.label_tag }} {{ form.name }} </div> <div … -
Ajax json doesnt show any instances
that even if i connected json data to ajax, it doesnt show me any results. def get_json_categories(request): query_get = request.GET if query_get: query_get = query_get['q'] categories = EcommerceProductCategory.objects.filter(name__contains=query_get).order_by('name') else: categories = EcommerceProductCategory.objects.order_by('name') data = {} data['results'] = [] for category in categories: data_to_return = {} data_to_return['id'] = category.id data_to_return['name'] = category.name data['results'].append(data_to_return) return JsonResponse(data) And i urled that to ecommerce/get_json_categories and in the Django html <div class="mt-2"> <hr> <div class="form-group"> <select class="form-control w-30" name="category_select" id="category_select" aria-describedby="category_select" required></select> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <script> $('#category_select').select2({ placeholder: 'Wybierz kategorię', ajax: { url: 'http://127.0.0.1:8000/ecommerce/get_json_categories', dataType: 'json', data: function (params) { return { q: params.term, page: params.name }; }, } }); </script> But it shows me "No results could be found" but that site (/ecommerce/get_json_categories) is full of json data. -
how to show delete button for modelformset - django
I'm trying to implement an application, which is has two models : Booking and Visitor each booking needs to have several Visitors, so the Visitor should be a formset in order to add several Visitors, but sometimes we need remove unwanted form from the Visitor, {{form.DELETE}} shows a checkbox, but i dont want it be a button, and remove the form right after clicking the button, i need to change here is my models class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE,default=1) room_no = models.ForeignKey(Room,on_delete=models.CASCADE,blank=True,related_name='rooms') name = models.CharField(max_length=40,default='',blank=True,null=True) class BookingVisitor(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT,related_name='visitor_admin') booking = models.ForeignKey(Booking,on_delete=models.CASCADE,related_name='booking_bookingvisitors') visitor_name = models.CharField(max_length=50) my forms is simple modelform VisitorBookingFormset = modelformset_factory(model=BookingVisitor,form=BookingVisitorForm,can_delete=True) and here is my views def createBooking(request): main_form = BookingForm() visitor_forms = VisitorBookingFormset(queryset=BookingVisitor.objects.none(),prefix='formset') if request.method == 'POST': main_form = CustomerInvoiceForm(request.POST) visitor_forms = VisitorBookingFormset(request.POST,prefix='formset') if main_form.is_valid() and visitor_forms.is_valid(): main_obj = main_form.save(commit=False) main_obj.admin = request.user main_obj.save() for form in visitor_forms: if form.is_valid(): form_obj = imei.save(commit=False) form_obj.booking = main_obj form_obj.save() return JsonResponse({'success':True}) else: return JsonResponse({'success':False,'error_msg_mainform':main_form.errors,'error_msg_visitorform':imei_forms.errors}) context = { 'main_form':main_form, 'visitor_forms':visitor_forms } return render(request,'booking/booking.html',context) and here is my template form <form action="" method="POST" id="create-booking">{% csrf_token %} <div class="row"> <!-- /.col --> <div class="col-md-4 pull-right"> <div class="form-group"> <label>room no</label> {{main_form.room_no | add_class:'form-control text-center'}} </div> </div> <div class="col-md-4 pull-right"> <div class="form-group"> <label>name</label> … -
django how to create a serializer ListField that accepts DictField with images values
As the title describes I need to create a Custom serializer ListField that accepts dictionary of string keys and value of Image Example input: [ {'1':FirstImage} , {'3',ThirdImage} ] What I've tried: customSerializer = serializers.ListField( child=serializers.DictField( child=serializers.ImageField(allow_empty_file=True, use_url=False) ) ) Obviously my serializer doesnt work as it should, anyone have an idea how can I make this work? Thanks In Advance -
How to successfully INCLUDE extra fields & UPDATE/DELETE existing fields(at a go) using either modelformset_factory/inlineformset_factory
i have my models ready, adding new products, that i have figured out, but including extra fields and updating/deleting this newly added field on one html form has been such a pain, the following are my exact codes with slight changes #my models.py class Product(models.Model): title = models.CharField() class ProductSpecification(models.Model): name = models.CharField() class ProductSpecificationValue(models.Model): product = models.ForeignKey(Product) specification = models.ForeignKey(ProductSpecification) value = models.CharField() class ProductImages(models.Model): product = models.ForeignKey(Product) images = models.ImageField(upload_to="images/uploads/") So here i will show my working code for ADDING new Product objects(just incase am doing it wrong, and it has anything to do with why updating part isn't working) #MY Adding product forms.py class AddNewProductForm(forms.ModelForm): title = forms.CharField() class Meta: model = Product fields = ['title',] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['title'].widget.attrs.update{'class': 'form-control'}) class AddNewProductSpecForm(forms.ModelForm): class Meta: model = ProductSpecificationValue fields = ['specification', 'value'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['specification'].widget.attrs.update({'class': 'form-control'}) self.fields['value'].widget.attrs.update({'class': 'form-control'}) class AddNewProductImgForm(forms.ModelForm): #this is to upload multiple img in bulk at one go images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = ProductImages fields = ['images',] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['images'].widget.attrs.update({'class': 'form-control'}) #MY Adding product views.py @login_required def add_new_product(request): AddNewProductFormSet = modelformset_factory(ProductSpecificationValue, form=AddNewProductSpecForm, extra=3) if request.method == "POST": product_form = AddNewProductForm(request.POST, … -
Will ignoring this (ValueError: signal only works in main thread of the main interpreter) affect anything?
I have a Django server running, and when it receives the user's data, it runs a separate program in views.py After it has completed what I have wanted I receive this error both in the terminal and the host server: handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler)) ValueError: signal only works in main thread of the main interpreter So I decided to do: try: #code except ValueError: return redirect('home') Which works perfectly fine as it redirects to the homepage of my website. Will it affect my website in the future when multiple users use the website? -
Override Save Model Django
I would like to override the save model in Django, to ensure a check that my User doesn't follow himself/herself. I know I can do this using serializer and put a check in view but I want to learn how to override def save. class Followable(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) followers = models.ManyToManyField(User, related_name="users", null=True, blank=True) class Meta: abstract = True def save(self, *args, **kwargs): if self.user != self.followers: return ValidationError("User cannot follow oneself.") super(Followable, self).save(*args, **kwargs) I tried printing out *args and **kwargs but it is empty. Also, User is my custom User Model.