Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO Beginner to Intermediate
I'm new to the Django Project and Community Can someone recommend me any YT channels or Books for pursuing in Django? -
Unknown field(s) (username) specified for Account. Check fields/fieldsets/exclude attributes of class AccountAdmin
Ive been spending hours on figuring out how to fix this error however I can figure it out? I have specified the different fields. This occurs when im in the admin panel and i try to add a new account - SNI works fine. I dont understand. Am i missing something? I have set the user field too Model from asyncio import FastChildWatcher import email from pyexpat import model from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class userCouncil(BaseUserManager): def create_user(self, userID, password=None): if not email: raise ValueError("Email is required") user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, userID, password): user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.is_staff = True user.is_admin = True user.save(using=self._db) return user class sni(models.Model): SNI = models.CharField(max_length=10, primary_key=True) # USERNAME_FIELD = 'SNI' def __str__(self): return self.SNI class Account(AbstractBaseUser): userID = models.EmailField(max_length=80, unique=True) name = models.CharField(max_length=100) dateOfBirth = models.DateField(max_length=8, null=True) homeAddress = models.CharField(max_length=100, null=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) sni = models.OneToOneField(sni, on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'userID' objects = userCouncil() def __str__(self): return self.userID def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Admin from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Account, sni class AccountAdmin(UserAdmin): ordering … -
Django Assigning users to models
I'm trying to create an assigning feature to my blogapp in Django What I want to do is when a new user is created, that user automatically gets added to an Assign Model, which you would then be able to assign a person(s) from a dropdown menu to whatever blog a user chooses. Here's my code so far 'models.py' class Assign(models.Model): name = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) class Issue(models.Model): MARK_AS = ((True, 'Open'), (False, 'Closed')) title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) assignee = models.ForeignKey(Assign, on_delete=models.SET_NULL, null=True) mark_as = models.BooleanField(choices=MARK_AS, default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('issue-detail', kwargs={'pk': self.pk}) 'views.py' class IssueCreateView(LoginRequiredMixin, CreateView): model = Issue fields = ['title', 'content', 'mark_as', 'assignee'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class IssueUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Issue fields = ['title', 'content', 'mark_as', 'assignee'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): issue = self.get_object() if self.request.user == issue.author: return True return False -
How to stop Django from evaluating false template conditions?
I have a Django template that renders links defined by specific apps like: <div>{% url 'admin:myapp_myview' %}</div> However, I want to make this app optional in my code, so I created a simple tag, called is_installed, like: import logging from django.apps import apps logger = logging.getLogger(__name__) @register.simple_tag def is_installed(name): result = apps.is_installed(name) logger.info('App "%s" is installed? %s', name, result) return result and use that to wrap my link in an if statement like: {% load mytags %} {% is_installed "myapp" as is_myapp_installed %} {% if is_myapp_installed %} <div>{% url 'admin:myapp_myview' %}</div> {% endif %} Unfortunately, it looks like regardless of the value of is_myapp_installed, Django's template engine evaluates all parts of the template, even if those parts are wrapped in if statements with false conditions. This means that when I disable myapp from my INSTALLED_APPS list, I see my log output: App "myapp" is installed? False Yet Django gives me the template error: Reverse for 'myapp_myview' not found. 'myapp_myview' is not a valid view function or pattern name. implying it's ignoring the if statement. Is there any way to fix this and stop Django from evaluating code inside false if statements? Are there alternative solutions? -
Bootstrap Navbar Logo not found
Hello I am trying to get my NavBar on bootstrap to show a Logo, I have tried moving the png to different folders in the app but I get this error: System check identified no issues (0 silenced). January 21, 2022 - 18:18:54 Django version 4.0.1, using settings 'mapproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [21/Jan/2022 18:19:00] "GET / HTTP/1.1" 200 229230 Not Found: /logo.png [21/Jan/2022 18:19:00] "GET /logo.png HTTP/1.1" 404 2219 Here is the index.html: <!--Navbar--> <!-- Just an image --> <!-- Image and text --> <nav class="navbar navbar-dark bg-dark"> <a class="navbar-brand" href="#""> <img src="logo.png" width="30" height="30" class="d-inline-block align-top" alt=""/> EtherWAN Product Map </a> </nav> <!--End Navbar--> -
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 …