Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I customize django allauth sign up forms to look the way I want?
How do I make a registration form without using this code <form class="signup" id="signup_form" method="post" action="{% url 'account_signup'}"> {% csrf_token %} {{ form.as_p }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit">{% trans "Sign Up" %} »</button> </form> Here is a small snippet of the custom sign up html <div class="group-35"> <form class="signup" id="signup_form" method="post" action="{% url 'account_signup'}"> {% csrf_token %} <div class="overlap-group-container-1"> <input class="overlap-group1 border-1px-dove-gray -applesystemuifont-regular-normal-black-20px" type="text" id="first_name" name="first_name" placeholder="First Name"/> <input class="overlap-group2 border-1px-dove-gray -applesystemuifont-regular-normal-black-20px" type="text" id="last_name" name="last_name" placeholder="Last Name"/> </div> <div class="overlap-group"> <input class="rectangle border-1px-dove-gray -applesystemuifont-regular-normal-black-20px" type="email" id="email" name="email" placeholder="Email"/> </div> This code was generated using anima and I want to use input fields to sign up the user. So from this snippet I'd want to sign the user up with the first name, last name and email they entered in the input fields. -
How do I call custom Django Model Manager from Class Based View?
I would like to use a customer model manager that manipulates a field but does not save to the database. How do I call the model manager function named "with_counts()" in the sample code below. Is it possible to call it from my view or my templates? LEVEL = [ ('Pro', 'Professional'), ('Int', 'Intermediate'), ('OK', 'Competent') ] Languages = models.CharField(max_length=25) Years = models.IntegerField(default=1) Proficiency = models.CharField(max_length=15, choices=LEVEL, default="Competent") def __str__(self): return f'{self.Languages} Level: {self.Proficiency}' #Do not save to data base. def with_counts(self): return self.years * 10; -
NextJS/Django Manually Typing in URLs
I'm trying to set up an application that uses Django on the backend and NextJS on the front end. I've set this up by statically exporting the NextJS app then Django app handles routing and uses index.html as a catch all for any routes it does not know. This is working relatively well however I am running into a routing issue with NextJS and I'm not sure where exactly it's coming from. While my client side routing works fine (i.e,. Link components work as expected) it does nothing if I do this by typing in the URL. My directory structure is like this: ... - pages - _app.tsx - index.tsx - login.tsx ... Therefore I should expect /login to route to the login page and again this works as expected in the Link tag however when I manually type in localhost:8000/login/ it just redirects to index.tsx. Some other potentially relevant files: tsconfig.json { "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "baseUrl": ".", "paths": { "@/styles/*": ["styles/*"], "@/components/*": ["components/*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "exclude": … -
How can I disable the static cache in django?
Currently I have developed applications with django for a few months, I have noticed that once you finish developing the application interfaces and want to integrate them into the backend everything works correctly, time later it becomes a mess having to modify the static files, since django caches these files perhaps to render the templates more efficiently, however when I want to make changes I have to rename the file and reinsert it in my index.html so that django detects it "as a new file". As you can see, it is very annoying to work like this. Does anyone have an idea how to fix this problem? -
How can I pass a dict to urlpatterns in Django
I am trying to send data from my web page to urlpattern in Django and then to the view. I know that I can include a dict in my urlpattern path that will be sent to my view: path("edit_page", views.edit_article, {'article':'fake_text'}, name="edit_page") I want to send the dict directly from my webpage. I have been trying: urls.py path("edit_page", views.edit_article, name="edit_page") html <a href='{% url 'edit_page' {'article': 'article_test'} %}'>Edit</a> Where am I going wrong? -
Django REST: adding source argument to serializer field results in "this field is required" error
I'm trying to create a generalized serializer for graphs. So far I have class NewVariableTypeValuePairSerializer(serializers.Serializer): def __init__(self, *args, **kwargs): x_source = kwargs.pop('x_source') y_source = kwargs.pop('y_source') x_serializertype = kwargs.pop('x_serializertype', None) y_serializertype = kwargs.pop('y_serializertype', None) super().__init__(*args, **kwargs) x_serializer = serializers.FloatField() if x_serializertype is None else x_serializertype() y_serializer = serializers.FloatField() if y_serializertype is None else y_serializertype() self.fields[x_source] = x_serializer self.fields[y_source] = y_serializer This works as intended, for example value_pair = { 'x_value': 13.7, 'y_value': 5 } res = NewVariableTypeValuePairSerializer(data=value_pair, x_source="x_value", y_source="y_value", y_serializertype=serializers.IntegerField) gives me the JSON { "x_value": 13.7, "y_value": 5 } Now I wanted to standardize this some more, so that in the above example I would get the JSON { "x": 13.7, "y": 5 } I've tried class NewVariableTypeValuePairSerializer(serializers.Serializer): def __init__(self, *args, **kwargs): x_source = kwargs.pop('x_source') y_source = kwargs.pop('y_source') x_serializertype = kwargs.pop('x_serializertype', None) y_serializertype = kwargs.pop('y_serializertype', None) super().__init__(*args, **kwargs) x_serializer = serializers.FloatField(source=x_source) if x_serializertype is None else x_serializertype( source=x_source) y_serializer = serializers.FloatField(source=y_source) if y_serializertype is None else y_serializertype( source=y_source) self.fields['x'] = x_serializer self.fields['y'] = y_serializer But when when trying to serialize the above dict I get the error {'x': [ErrorDetail(string='This field is required', code='required')], 'y': [ErrorDetail(string='This field is required', code='required')]} What's wrong here? Thanks in advance. -
Search by name and surname
I have a search bar in template <input type="text" name="search" placeholder="Search..."> In Model I have two seperate properties name and surname class Person(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=50) In views.py I have logic like this search = self.request.GET.get("search", None) if search: Person.objects.filter(Q(name=search) | Q(surname=search)) I want to filter with name surname or both of them -
Does django perform an implicit update of related models?
I am trying to understand how the following code works under the hood: # models.py class M1(models.Model): m2 = models.ForeignKey('M2', related_name='m1s', null=True, blank=True) class M2(models.Model): m1 = models.ForeignKey('M1', related_name='m2_set', null=True, blank=True) # elsewhere m2 = M2() m1 = M1() m1.m2 = m2 m1.save() # no error! according to the docs, this shouldn't be allowed m1_persisted = M1.objects.get(id=m1.id) print(m1_persisted.m2 == None) # True, as expected since m2 was never saved m2.m1 = m1 m2.save() # this is fine, m1 was previously saved m1_persisted = M1.objects.get(id=m1.id) print(m1_persisted.m2.id) # prints m2's id! why does calling m2.save() update m1? According to the django docs it looks like I should get an error of the form ValueError: save() prohibited to prevent data loss due to unsaved related object when first calling m1.save(), but I don't. Is this expected behavior or is there something else going on here (potentially in an overridden save method) I tried digging around in the django source for .save() here but was unable to figure out what its doing. -
Redeclared 'LOGIN_REDIRECT_URL' defined above without usage
from django.urls import reverse LOGIN_REDIRECT_URL = reverse('dashboard') LOGIN_URL = reverse('login') LOGOUT_URL = reverse('logout') -
Getting ModuleNotFoundError: No module named 'taggit' in Django 3
I am getting ModuleNotFoundError: No module named 'taggit' when trying to load my app. However, I have installed 'taggit' -
A row is missing from one of my tables in my Django site. Where did it go?
A row is missing from one of my tables in my Django site. There is absolutely nothing in django_admin_log table mentioning that it was deleted. There were other deletions performed on that day and they were saved. Also, I checked Django's admin code and it looks like it tries logging the deletion first, so even if the deletion was made in a non-transaction manner, in the worst case I'd have log entry and a non-deleted record. There are no logs in the web log, neither nginx nor my web app log, that suggest that it was removed by Django-admin. There are logs of another deletion made on that day, so I guess deletions were logged. The database in question is PostgreSQL. I've just read about pg_dirtyread, unfortunately, I've just vacuumed the database a moment ago. My takes: Delete query typed from command-line utility - nope, nobody was logged-in on that day. Hacker? Come on, why would a hacker delete a single record from a table of a custom CMS-like software? Hardware fault? Memory problems would manifest in other, random ways. Disk problems - probably too. I have found an anecdotal mention of a record missing from an index in PostgreSQL … -
How to build entire dataset prior to sending AJAX -Jquery
I have a system that allows an admin to add managers to a campaign from a table. The table looks something along the lines of <tr> <td>Checkbox</td> <td>Last name, First name</td> <td>Employee Id #</td> </tr> Currently, when the "Add Manager" button is hit, I pass the manager's id and a "checked" value using this function <script> function addMgrs(){ dict = {} $('#potentialReviewers tr').each(function() { var userPid = $(this).find('td').eq(2).text() var addMgrBox = $(this).find('.addMgrBox').attr('value') if (addMgrBox == 'checked') { dict[userPid] = addMgrBox } // Create the Post request, pass the csrf_token in the header of the request $.ajax({ url: '/campaign-view/' + '{{ campaign.id }}' + "/", type: 'POST', headers: {'X-CSRFtoken': '{{ csrf_token }}'}, data: dict, dataType: 'json' }) }) } </script> What this does is iterate through the table, build the JSON response and pass it back to the Django view to do the backend processing. My problem is this, for each row it sends a POST request and that drastically increases the time it takes for the process to complete. I'd like it to build the entire dictionary prior to sending the response, but just can't wrap my head around how to do that. Any help would be appreciated. -
Allow only certain devices to access the website?
I am building a website with django/python (backend) and HTML/CSS/JS (frontend), and I am wondering how to allow my website to be accessed only by certain devices. -
403 permission error with apache2 and django
I thought I fixed the permission error but I'm still getting the permission error. Here are a few screenshots of my code. https://imgur.com/a/lZXr7lZ -
Is my django post method even being called?
I am trying to make a trading log app in Django but I have run into a few snags. It feels like my post method might night be being called when the submit button is clicked. I have tried printing and logging and neither ever fire in the post() method. The logging works fine in the get() method. Additionally I keep being routed back to my base index page even though I am rendering trading_log/add-order.html. I have also tried using a HTTPResponseRedirect. Both to no avail. I am really not sure what I am doing wrong at this point. Since I am unsure which files would need to be looked at I made the repo public for now to try and get some help. If that is not OK or not allowed I can delete the link and paste all the files in here that should be relevant, just let me know. Figured the repo would be easier. https://github.com/xcasper/caspers_trading_tools -
Django Runtime error model explicit app_name
I am using Python3 and django with django rest framework. Actually I am new to django and I am having error while creating models. Here is the error: Traceback (most recent call last): File "E:\Python\Website\deployment\portfolio\manage.py", line 22, in <module> main() File "E:\Python\Website\deployment\portfolio\manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\Python\Website\deployment\venv\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line utility.execute() File "E:\Python\Website\deployment\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\Python\Website\deployment\venv\lib\site-packages\django\core\management\base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "E:\Python\Website\deployment\venv\lib\site-packages\django\core\management\base.py", line 412, in execute self.check() File "E:\Python\Website\deployment\venv\lib\site-packages\django\core\management\base.py", line 438, in check all_issues = checks.run_checks( File "E:\Python\Website\deployment\venv\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "E:\Python\Website\deployment\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "E:\Python\Website\deployment\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "E:\Python\Website\deployment\venv\lib\site-packages\django\urls\resolvers.py", line 446, in check for pattern in self.url_patterns: File "E:\Python\Website\deployment\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "E:\Python\Website\deployment\venv\lib\site-packages\django\urls\resolvers.py", line 632, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "E:\Python\Website\deployment\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "E:\Python\Website\deployment\venv\lib\site-packages\django\urls\resolvers.py", line 625, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked … -
How to extract only numbers from a list of tuples
poi = booking_models.TestBooking.objects.filter(customer_visit=instance).values_list("package__package_name", "amount").order_by("package").distinct() [(None, 392.0), (None, 530.0), ('RahulNewPaackage', 3999.0), ('Suraj pkg today all', 699.0), ('suraj 44', 599.0)] I am learning python and django and trying to get only numbers from this output(poi). I want to get this in a list like this [392.0, 530.0, 3999.0, 699.0, 599.0]. As poi will iterate many times so every time till the last item there will be output of list of numbers. How to achieve this ? Any help will be really appreciated. Thank you !! -
Django Signal Receiver Function not accepting sender
I am trying to create notification whenever a user likes a post. For that I am using django signals. I have previously used the sender arguement in the receiver decorator but don't why its not working this time. Here are my files. #signals.py @receiver(m2m_changed, sender=Post) def likeNotification(sender,**kwargs): if kwargs['action'] == "post_add" and not kwargs['reverse']: post = kwargs['instance'] to_user = post.user liked_by_users = kwargs['pk_set'] like_notification = [Notification( post=post, user=to_user, sender=User.objects.get(id=user), text=f"{User.objects.get(id=user).profile.username} liked your post.", noti_type=3 ) for user in liked_by_users] Notification.objects.bulk_create(like_notification) #socialuser.models.py class Post(Authorable, Creatable, Model): caption = TextField(max_length=350, null=True, blank=True) liked_by = ManyToManyField( "core.User", related_name="like_post", blank=True) objects = PostManager() def no_of_likes(self): return len(self.liked_by.all()) The receiver doesn't catch the signal when sender=Post, when I remove the sender it works as intended. On print the positional arguement sender of likeNotification function. This is what I get <class 'socialuser.models.Post_liked_by'> What am I doing wrong? Do I need to reference to the intermediate class Post_liked_by, if so how do I do that? -
How to save billing and shipping address in Django Form
I have a form where the shipping address part will be visible when custom-checkbox input is checked. I am saving data to model when the checkbox is not checked. How should I deal with form to save shipping and billing address when checkbox is checked on following form: <form class="form checkout-form" method="POST" action=""> <div class="row mb-9"> <div class="col-lg-7 pr-lg-4 mb-4"> <h3 class="title billing-title text-uppercase ls-10 pt-1 pb-3 mb-0"> Billing Details </h3> <div class="row gutter-sm"> <div class="col-xs-6"> <div class="form-group"> <label>First name *</label> <input type="text" class="form-control form-control-md" id="firstname" name="firstname" required> </div> </div> <---- Other Required Billing Info Goes Here----> <div class="form-group mb-7"> <label>Email address *</label> <input type="email" class="form-control form-control-md" id="email" name="email" required> </div> <<=======Shipping form toggle section starts here =====> <div class="form-group checkbox-toggle pb-2"> <input type="checkbox" class="custom-checkbox" id="shipping-address" id="shipping-toggle" name="shipping-toggle"> <label for="shipping-toggle">Ship to a different address?</label> </div> <div class="checkbox-content"> <div class="row gutter-sm"> <div class="col-xs-6"> <div class="form-group"> <label>First name *</label> <input type="text" class="form-control form-control-md"id ="firstname" name="firstname" required> </div> </div> <div class="col-xs-6"> <div class="form-group"> <label>Last name *</label> <input type="text" class="form-control form-control-md" id="lastname" name="lastname" required> </div> </div> </div> <div class="form-group"> <label>Company name (optional)</label> <input type="text" class="form-control form-control-md" id ="companyname" name="company-name"> </div> <--- Other Shipping Infor goes here ---> <<=======form-group checkbox-toggle ends here =====> <div class="form-group … -
Where can I find and ID for Redis caching service running in a container?
im developing a rates service that retrieves rates from cache (Django, Redis), which has its own container. class CachedTraderRepository: def get_rate(self, pair): print("GET RATE START") print(pair) pair_rate = cache.get(pair) print(pair_rate) print("GET RATE END") return pair_rate def get_all_rates(self): print("GET ALL RATES START") all_rates = cache.get("all_pairs") print(all_rates) print("GET ALL RATES END") return all_rates I have a script that populates that cache with the data I need, and in the same script I made a method for retrieving same data and it works. Fills the cache, and when I do cache.get() I see the expected results. class CacheWorker: def fill_cache(self): print("START") pair_queryset = Pair.objects.all() pairs = [] print("retrieving pair queryset") for pair in pair_queryset: pairs.append(pair.name) print("pair list: ", pairs) all_rates = SandboxTraderSDK(account="martin").get_multiple_pair_response(pairs) print("rates: ", all_rates) cache.set("all_rates", all_rates) print("Cache filled") print("END") def get_cache(self): print("START") a = cache.get("all_rates") print(a) print("END") The problem is that I cannot see the same result when I execute it from the class: Shell: In [8]: CachedTraderRepository.get_all_rates() GET ALL RATES START None GET ALL RATES END So I think that django cache has 2 instances or sth like that, how can I print a Redis client ID or something like that to be sure if both codes are being executed on … -
'ascii' codec can't encode character '\u2013' when working with files in python (Django)
I have written a code that saves a certain image which was retrieved via an API with django etc... this module saves the retrieved image in some directory, and it works fine on some images but has an issue with others, also, this problem in happening in my actual live website and it does not occur in the localhost. the module is as follows: def save_poster(json_data): import os title = json_data['Title'] + ' ' + json_data['Year'] poster_url = json_data['Poster'] # Splits the poster url by '.' and picks up the last string as file extension poster_file_extension=poster_url.split('.')[-1] # Reads the image file from web poster_data = urllib.request.urlopen(poster_url).read() savelocation=os.getcwd()+'\\'+ 'Core' + '\\' + 'Posters'+'\\' # Creates new directory if the directory does not exist. Otherwise, just use the existing path. if not os.path.isdir(savelocation): os.mkdir(savelocation) filename=savelocation+str(title)+'.'+poster_file_extension f=open(filename,'wb') f.write(poster_data) f.close() return filename I get the following error when I try to use the API: UnicodeEncodeError at /api/film/film/create/ 'ascii' codec can't encode character '\u2013' in position 52: ordinal not in range(128) -
Django Conditional update based on Foreign key values / joined fields
I'm trying to do a conditional update based on the value of a field on a foreign key. Example: Model Kid: id, parent (a foreign key to Parent), has_rich_parent Model Parent: id, income So say I have a query set of A. I wanna update each item's has_guardian in A based on the value of age on the Kid's parent in one update. What I was trying to do is queryset_of_kids.update( has_rich_parent=Case( When(parent__income__gte=10, then=True) default=False ) ) But this is giving me an error Joined field references are not permitted in this query. Which I am understanding it as joined fields / pursuing the foreignkey relationships aren't allowed in updates. I'm wondering if there's any other way to accomplish the same thing, as in updating this queryset within one update call? My situation has a couple more fields that I'd like to verify instead of just income here so if I try to do filter then update, the number of calls will be linear to the number of arguments I'd like to filter/update. Thanks in advance! -
'name' in request.POST always returns False - django : python
I've a view, with two forms, i want to check which one will be submit, using 'bookingformbtn' in request.POST and 'visitorformbtn' in request.POST but both returns false ? here is my views def my_views_post(request): print('bookingformbtn' in request.POST)#returns False print('visitorformbtn' in request.POST)#returns False # non of these conditions works ! if request.method == 'POST' and request.is_ajax() and 'visitorformbtn' in request.POST: #do something elif request.is_ajax() and request.method == 'POST' and 'bookingformbtn' in request.POST: #do something else <form method="POST" class="mt-2" id="add_new_guestform">{% csrf_token %} <--! form inputs --> <input type="submit" name="visitorformbtn" value=" "save"> </form> <form method="POST" class="mt-2" id="post-form-add-booking">{% csrf_token %} <--! form inputs --> <input name="bookingformbtn" type="submit" value="save"> </form> is there something i did wrong please ?! thank you for your advice .. -
How to get sum of amount of distinct name
poi = booking_models.TestBooking.objects.filter(customer_visit=instance).values_list("package__package_name", "amount").order_by("package").distinct() Output of poi = [(None, 392.0), (None, 530.0), ('RahulNewPaackage', 3999.0), ('Suraj pkg today all', 699.0), ('suraj 44', 599.0)] So i want to get sum of these amounts. So sum will be 6219. I tried aggregate method but it does not work with order_by and without order_by distinct() does not work. So How to achieve this. Thank you !! -
How to list all items based on foreign key pk Django Rest Framework
i want to list all the instanced that are saved to a certain Animal. Let's say a dog has id 3 and i have got 2 instances of dog sexes but when i get the request from animal/3/sex i only get one instance not 2. I tried using many=True to serializers.PrimaryKeyRelatedField but it shows me that 'Animal is not iterable'. Do you have any idea how to do it? class AnimalSex(models.Model): name = models.CharField(max_length=256) slug = models.SlugField(max_length=128, unique=True, null=False, editable=False) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) animal = models.ForeignKey(Animal, on_delete=models.CASCADE, null=False) VIEWS class MyAnimalSex(generics.RetrieveAPIView): queryset = AnimalSex.objects.all() serializer_class = AnimalSexSerializer lookup_field = 'pk' SERIALIZER class AnimalSexSerializer(serializers.ModelSerializer): animal = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = AnimalSex fields = ('name', 'slug', 'animal',) URL path('animal/<int:pk>/sex', MyAnimalSex.as_view()),