Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: {% include %} tags: Readability vs Performance Trade-off
I found myself using a significant number of {% include %} tags in my Django templates. According to Django's documentation, "using {% extends %} is faster than using {% include %}" and "heavily-fragmented templates, assembled from many small pieces, can affect performance." With that being said, I found {% include %} vastly useful to improve the readability and maintainability of my code. With this CS trade-off at hand, what are some rules of thumb for when to use {% include %}? -
Django connect mysql problem, NameError: name '_mysql' is not defined
I found MySQL database cannot start properly, so I uninstall Mysql 5.7. I installed MySQL 8.0.21, I found that my Django project has a problem. I would like makemigrations on my Django project and then I got an error on my Django project. Please help, I don't know how to solve this error. Packet Django==2.1.5 mod-wsgi==4.7.1 mysql-connector-python==8.0.21 mysqlclient==2.0.1 Python 3.7.9 MySQL Ver 8.0.21 Setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'xxxxxx.compute.amazonaws.com', 'PORT': '3306', 'NAME': 'xxxxx', 'USER': 'xxxxx', 'PASSWORD': 'xxxxxx', 'init_command': "SET sql_modes = 'STRICT_TRANS_TABLES'", }, } python3 manage.py makemigrations Error message Traceback (most recent call last): File "/var/www/html/Django_website/django/lib64/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: libmysqlclient.so.18: cannot open shared object file: No such file or directory During handling of the above exception, another exception occurred: 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 "/var/www/html/Django_website/django/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/var/www/html/Django_website/django/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/var/www/html/Django_website/django/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/html/Django_website/django/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/var/www/html/Django_website/django/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, … -
Django-Rest nested serilizer issue
Currently I am trying to nest down seriliazers using DRF. class CustomerDetailsSeriliazer(serializers.ModelSerializer): class Meta: model = CustomerDetails fields = ['location',] class UserProfileSeriliazer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['name','type','phone_number'] class CustomerUserSerializer(serializers.ModelSerializer): username = serializers.CharField(validators=[UniqueValidator(queryset=User.objects.all())]) password = serializers.CharField(min_length=8) user_profile_details = UserProfileSeriliazer(source='user_profile') #**********Below field is in relationship with user profile and it is causing issue******** customer_user_details = CustomerDetailsSeriliazer(source='customer_details') def create(self, validated_data): user = User.objects.create_user(validated_data['username'],validated_data['password']) userprofile_data = validated_data.pop('user_profile') userprofile = UserProfile.objects.create(**userprofile_data,user=user) customer_details_data = validated_data.pop('customer_details') customer_details = CustomerDetails.objects.create(**customer_details_data,user_profile=userprofile) return user class Meta: model = User fields = ['id', 'username','password','user_profile_details','customer_user_details'] I have 3 models, User model(default django) UserProfile(foreign key to User->->OneToOne relation) CustomerDetails(foreign key to UserProfile->OneToOne relation) I am able to do nested serilization of UserProfile as given in docs but whenever I try to access CustomerDetails it throws error(User is not directly related with CustomerDetails). How to achieve this kind of serialization using ModelSeriliazer ? Or do I need to change something ?. Thanks for help. -
'ReverseManyToOneDescriptor' object has no attribute 'filter' Django
Hi there Im trying to retrieve a specific object from the related model so as to render data to my view specific to that particular object, in my case I have a custom user model and a related model called Seller. Models from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): is_customer = models.BooleanField(default=False) is_seller = models.BooleanField(default=False) class Seller(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True) store_name = models.CharField(max_length=120) address = models.CharField(max_length=180) phone = models.IntegerField(blank=True, null=True) email = models.CharField( max_length=180, blank=True, null=True ) def __str__(self): return self.store_name View @method_decorator( seller_required , name='dispatch') class SellerDashBoardView(ListView): model = Seller template_name = 'seller_dashboard.html' def get_context_data(self, *args, **kwargs): user = CustomUser.seller_set.filter(store_name=self.request.user.username) context = super(SellerDashBoardView, self).get_context_data( **kwargs) context['products'] = Product.objects.filter(seller=user)[:6] return context -
How do I delete model records that have no links?
I have a little experience, but I would like to know your professional advice. I developed my Django application, and I decided not to physically delete the database records, but only to mark the records with a marker (isDeleted) so that no confusion would be created between related records in the database. But over time, there are a lot of such records, and I decided to create a "Database Maintenance" button, which would perform real (physical deletion) of records with checking all the dependencies of this record. For example, I want to delete an item, but it is associated with an order. But it can be deleted if it has no connections. Is it possible in Django to somehow perform a check, such as this: for model in allModels: if (records of model has no links with other model records): delete records of model else: do nothing -
How to create union with two or more django-models to ManyToMany field?
I have 3 models in 3 different apps. APP 1: class ModelA(models.Model) title = models.CharField(max_length=200) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) ... APP 2: class ModelB(models.Model) title = models.CharField(max_length=200) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) ... APP 3: class ModelC(models.Model) name = models.CharField(max_length=200) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) ... Then I have 4th model in own app. APP 4: class ModelD(models.Model) title = models.CharField(max_length=200) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) ... union = models.ManyToManyField(ModelA, blank=True) Like in ModelD I can build ManyToMany relationship (field name "union") with one model (e.g. ModelA). I am looking for solution where I can combine all three models to one ManyToMany field. Like in next SQL query which is doing exact what I need. select id, "modelA" as "model" from app1.modelA union select id, "modelB" from app2.modelB union select id, "modelC" from app3.modelC ManyToMany field creates cross reference table with columns ModelD_id and ModelA_id. I assume that I need also cross reference table where I can store at least modelD_id and id from other model objects and I also need information from models to own column. Like column name "model" in SQL query. I am building checkbox list for users to select correct items. What could be the best way to built … -
Django UpdateCacheMiddleware at the beginning and FetchFromCacheMiddleware at the end
According to Django recommendation UpdateCacheMiddleware should be at the beginning of the middlewares list while FetchFromCacheMiddleware should be at the end. I was wondering, doesn't that mean that when I save a response to the cache, it will be AFTER is passed through all of the middlewares (in the request phase and then again in the response phase), but when I fetch a response from the cache, it will be already AFTER it passed through all of the middlewares, and then it will go back AGAIN through all of the middlewares in the response phase? Does it mean that all middlewares should be able to receive a response that they already processed? -
call django function with parameter from angular
I have a function in Django which takes the image path as parameter and return string. How I can call it from Angular with image path and get the function ran which return string which I can display on screen. Is there any way to solve it, any link, example would be appreciated... -
Django insert data to ManyToManyfield AssertionError error
model class Enrollee(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, verbose_name=_('id')) first_name = models.CharField(max_length=60, verbose_name=_('first name')) dependents = models.ManyToManyField(to=Dependant, blank=True, verbose_name=_('dependents')) class Dependant(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, verbose_name=_('id')) first_name = models.CharField(max_length=60, verbose_name=_('first name')) view class EnrolleeViewSet(viewsets.ModelViewSet): queryset = models.Enrollee.objects.all() serializer_class = serializers.EnrolleeSerializer filter_class = filters.EnrolleeFilter serializers class EnrolleeSerializer(DynamicFieldsMixin, DynamicFieldsModelSerializer): dependents = DependantSerializer(many=True, required=False) class Meta: model = models.Enrollee fields = '__all__' error: _nested_writes assert not any( AssertionError: The `.create()` method does not support writable nested fields by default. Write an explicit `.create()` method for serializer `api.serializers.EnrolleeSerializer`, or set `read_only=True` on nested serializer fields. Here I am trying to send nested data for my dependents(ManyToManyField) But, Getting above error while inserting data. Is there any way we can achive this ? { "first_name":"soubhagya", "dependents" : [ { "first_name":"soubhagya" } ] } Above is the data i am sending using post method. please have a look -
Display pop up with dynamic data on click from button Django template
I have a project where i am passing doctionary data from view to template and creating buttons inside the html page from template. now if user clicks on button it should show a pop up window ( bootstap implemented modal ) and show some more info regarding clicked items. i already have object containing more information corresponding to button. how can i acheive this ? -
Django - Accessing page url/slug primary key when uploading an image from the page
I have a website where users can submit mock design briefs and other users can submit their designs for them. When uploading the image from the design brief detail page, I need to set it so that the design gets associated with the brief that the user is on. So for example if the user is on brief with primary key 24, it gets added as a foreign key on the image model. How would I go about doing this and is it possible. The brief model has a primary id key. The design model has two fields, the author who uploaded the image and the brief its associated with as a foreign key. How would I accomplish this, thanks -
How to populate model from other model's field?
We had a model to save some text in a model like this: class Model1(models.Model): text = models.CharField(max_length=255) # other fields Now we are adding support for multiple languages, so created a new model and want to save the text with its corresponding language in it, and change Model1 text field to many-to-many, as this text can be used in many models. class Model1(models.Model): texts = models.ManyToManyField(Model2) # other fields class Model2(models.Model): text = models.CharField(max_length=255) language = models.CharField(max_length=100) I am thinking of this process: Create Model2 and its migrations populate Model2 from Model1 data, and change text field in Model1 to many-to-many Update Model1 text field to many-to-many But, I am unsure how to perform step 2. I am new in Django, so am I missing something? -
develop web application on the basis of desktop application
I have a desktop application ready which is developed using wxpython, matplotlib, numpy etc. Now I want to convert this same application in web. So is it possible to open desktop application using browser which means we will install desktop application on server and using browser, we can view it in different machine. Already developed desktop application is little bit complex and it will take a lot of time to develop again in web. As I already have the desktop app ready, I was looking for some shortcut where I can use my existing desktop app instead of doing all the coding from the scratch. -
request.user in decorators.py returns different results to self.request.user in views.py
I have created a decorator 'unauthenticated_user(view_func)' in my 'decorators.py' file which restricts a user from accessing a view if the current user is not authenticated. In the 'unauthenticated_user()' function, there is a conditional 'request.user.is_authenticated' which should return true if a user attached to the token is authenticated. However, upon testing this function, I have noticed that 'request.user' in 'decorators.py' is not always equal to the correct value returned by 'self.request.user' in 'views.py'. Instead, it often returns previously logged in users, or 'AnonymousUser' which ruins functionality. decorators.py: def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return view_func(request, *args, **kwargs) else: return HttpResponse('No user logged in') return wrapper_func views.py: @method_decorator(unauthenticated_user, name = 'dispatch') class UserLogout(APIView): ... This is the views.py function I have been using to test that there is in fact an authenticated user when the decorators.py function returns 'AnonymousUser': class Current(APIView): def get(self, request, format = None): try: return Response(self.request.user.is_authenticated) except: return Response("no user currently logged in") How to I ensure that 'decorators.py' 'unauthenticated_user' function has access to the user in the current request like the 'Current' view does in 'views.py'? Any help would be much appreciated. To my knowledge there is no way to call 'self' in the 'decorators.py' … -
Django change email/username already exists and email isn't valid error messages
I'm trying to change these error messages to custom, here's code: >>>forms.py class UserRegistrationForm(forms.ModelForm): ... ... ... def clean_email(self): username = self.cleaned_data['username'] email = self.cleaned_data['email'] users = User.objects.filter(email__iexact=email).exclude(username__iexact=username) if users: raise forms.ValidationError("Email's already taken.") return email.lower() def clean_username(self): username = self.cleaned_data['username'] try: user = User.objects.exclude(pk=self.instance.pk).get(username=username) except User.DoesNotExist: return username raise forms.ValidationError("Username's already taken.") When I type username that is already taken I get an error screen: KeyError at /account/register/ 'username' Request Method: POST Request URL: http://127.0.0.1:8000/account/register/ Django Version: 3.1.1 Exception Type: KeyError Exception Value: 'username' Exception Location: C:\Users\user\Desktop\esh\myshop\account\forms.py, line 58, in clean_email And also I can't figure out how to override invalid email error message. -
Django ModelForm Form not Posting
I have a form that is based on a ModelForm in my forms.py. I initially get the blank form as expected, however when filling out the form and hitting submit nothing happens. I am not sure where I am going wrong. views.py def add_customer(request): # print(customer_form) # print(customer_form.errors) print(request.method) print(request.POST) customer_form = CustomerForm(request.POST or None) if customer_form.is_valid() and request.method == 'POST': form = CustomerForm(request.POST) form.save() return redirect('AdminPortal:customers') print('posted') else: print('failing') context = {'customer_form': customer_form,} return render(request, 'add_customer.html', context=context) urls.py path("customers/", views.customers, name="customers"), path("customers/customer/<int:id>/", views.customer, name="customer"), path("add_customer/", views.add_customer, name="add_customer"), forms.py class CustomerForm(forms.ModelForm): class Meta: model = AppCustomerCst fields = ('is_active_cst', 'name_cst', 'address_1_cst', 'address_2_cst', 'address_3_cst', 'city_cst', 'state_cst', 'zip_cst', 'country_cst', 'salesrep_cst', 'type_cst', 'is_allowed_flat_cst', 'iddef_cst', 'balance_notify_cst', 'receive_emails_cst', 'contact_domain_cst' ) add_customer.py [form portion] <form method="post" action='AdminPortal:add_customer'> {% csrf_token %} {{ customer_form }} <button type="button" value="submit">Submit</button> <button type="button" value="cancel">Cancel</button> </form> -
3 using css on django
I'm using django 3 and the css doesn't work -
(Django REST Framework) Difference between objects.create directly and .save()? [duplicate]
I have 2 ways to create Parameter object: location = Location.objects.create(name=loc['name'], description=loc['description'], longitude=float(location['lng']), latitude=float(location['lat'] ) and location = Location(name=loc['name'], description=obj['description'], longitude=float(loc['lng']), latitude=float(loc['lat']) ) location.save() I want to ask what is the difference between the two? -
Python Django: Merge Dataframe performing Sum on overlapping columns
I want to merge two DataFrames with exact the same column names. The overlapping columns can be added togheter. I'm having a bit of troubles because the grouping should be happening on the "index" called "Date" but I can't this index through using the 'Date' name. Actually, I just need the index (Date) and the sum of all the stocks their 'Adj Close'. I tried: data.join(temp, how='outer') Returns: "ValueError: columns overlap but no suffix specified: Index(['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume'], dtype='object')" data = pd.concat([data, temp]).groupby([data.index, temp.index], as_index=True).sum(axis=1) Returns: "Grouper and axis must be same length data = pd.merge(data, temp, left_index=True, right_index=True)['Adj Close'].sum(axis=1, skipna=True).astype(np.int64) Returns: "KeyError: 'Adj Close'" Code def overview(request): stocks = Stock.objects.all() data = None for stock in stocks: if data is None: data = yf.download(stock.ticker, start=stock.trade_date, period="ytd") else: temp = yf.download(stock.ticker, start=stock.trade_date, period="ytd") data.join(temp, how='outer') DataFrame Output 1 [*********************100%***********************] 1 of 1 completed Open High ... Adj Close Volume Date ... 2019-09-19 55.502499 55.939999 ... 54.697304 88242400 2019-09-20 55.345001 55.639999 ... 53.897728 221652400 2019-09-23 54.737499 54.959999 ... 54.142803 76662000 2019-09-24 55.257500 55.622501 ... 53.885353 124763200 2019-09-25 54.637501 55.375000 ... 54.714626 87613600 ... ... ... ... ... ... 2020-09-10 120.360001 120.500000 ... 113.489998 182274400 2020-09-11 114.570000 115.230003 … -
How to filter with choices | Django
I want to filter this item with category but in this way it doesn't show the correct result in filtering. Example: when I searched by Outwear it didn't show any item(though I have this type of items). As well as when I use Q(category=query) and searched by S/SW/OW it shows the correct result. models.py CATEGORY_CHOICES = ( ('S', 'Shirt'), ('SW', 'Sport wear'), ('OW', 'Outwear') ) class Item(models.Model): title = models.CharField(max_length=100) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) views.py class HomeView(ListView): model = Item paginate_by = 5 template_name = "home.html" def get_queryset(self, *args, **kwargs): qs = super().get_queryset(*args, **kwargs) query = self.request.GET.get('q') if query: return qs.filter(Q(category__in=query)) return qs -
How to update django database models in MySQL?
How to update database table in MySQL ? For example, in my Django app, I have a database table named 'Category1' , and I want to rename it into "Category" only. After I run python manage.py makemigrations and python manage.py migrate , it doesn't show any errors but I can't see any changes in my MySQL Workbench. How to do this ? -
django urls pattern syntax {0,1}
I'm migrating a django app (python2.7, django 1.11) developed by someone else to a new server and see urlpatterns like the following. The new server has python3.6 and django 2.2.2 and seem the pattern syntaxes are different and I had to drop the {0,1} part. I'm just curious what {0,1} means and searched around but couldn't find any document about it. I saw something like \W{4}, \d{2}, but never saw {0,1}. urlpatterns = patterns( '', url(r'^news/{0,1}$', 'views.news', name='news'), url(r'^toggle/{0,1}$', 'views.masquerade', name='toggle_url'), url(r'^dashboard/{0,1}$', 'views.dashboard', name='dashboard'), url(r'^/{0,1}$', 'views.dashboard', name='dashboard'), ... ) -
Django: Translating URLs: How to separate translatable URL patterns in app/urls.py?
This is how Django recommends going about translating URL patterns: Translating URL patterns. Why are URL patterns described in project/settings.py and not in app/urls.py? The example provided above works but when you have many apps installed on your project project/settings.py starts to get really messy. How can I translate my URLs and keep them separate in their app folder at the same time? Thank you. -
apache2 wont start (Process: 16815, Process: 17391)
I am new to Apache and Hosting in general. Today I wanted to deploy my first Django app on a Linux Server. I followed this Tutorial https://www.youtube.com/watch?v=Sa_kQheCnds. Everything worked fine except the installation of sudo apt-get install libapache2-mod-wsgi-py3.if got an error, tried again and got this being read ... Done Dependency tree is built. Status information is read in .... Done libapache2-mod-wsgi-py3 is already the newest version (4.5.17-1ubuntu1). 0 updated, 0 reinstalled, 0 removed, and 0 not updated so i keept going but now at the end when i enter sudo service apache2 restart i get: Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details. systemctl status apache2.service gives me the following output: Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled) Drop-In: /lib/systemd/system/apache2.service.d └─apache2-systemd.conf Active: failed (Result: exit-code) since Thu 2020-09-17 14:45:14 CEST; 1min 33s ago Process: 16815 ExecStop=/usr/sbin/apachectl stop (code=exited, status=0/SUCCESS) Process: 17391 ExecStart=/usr/sbin/apachectl start (code=exited, status=1/FAILURE) Main PID: 524 (code=exited, status=0/SUCCESS) The Server came preinstalled with Plask. -
I am not able to install django_heroku in my virtual environment for my django project
I tried updating pip, wheel, and psycopg but I keep receiving the error: ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /Users/serena/Projects/VidLibrary-Backend/env/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/zd/04_z6x812bsg7gsgrv5wr4800000gq/T/pip-install-1i40ukbk/psycopg2/setup.py'"'"'; file='"'"'/private/var/folders/zd/04_z6x812bsg7gsgrv5wr4800000gq/T/pip-install-1i40ukbk/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/zd/04_z6x812bsg7gsgrv5wr4800000gq/T/pip-record-8emxpni2/install-record.txt --single-version-externally-managed --compile --install-headers /Users/serena/Projects/VidLibrary-Backend/env/include/site/python3.8/psycopg2 Check the logs for full command output.