Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - using modern middlewares, should I ever use process_view?
I'm migrating a few middlewares to a new Django codebase, using Django 3.1. I'm obviously using MIDDLEWARE and not MIDDLEWARE_CLASSES. I see that process_view is still supported. But I don't understand why would I ever use that. Does it add anything over using a standard Middleware using get_response directly? When will this get_response even be called in this flow? -
Save manual data in log file django
hi I am creating a log file in django , and my settings.py file is like LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/home/User/Desktop/customapp/debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } I just want to save in log file like , at 12:00 user visted www.mywebsite.com I am trying to save data in it like logger.info('www.mywebsite.com') But nothing is happening -
Can I access context object in decorator over django view
I have multiple django views to which I want to add some context based on their response and status code. Right now I have a code that look something like this: def my_decor(func): def wrapper(*args, **kwargs): response = func(*args, **kwargs) if response.status_code == 200: # It will be changed to manipulate 2XX reponses only new_data = foo() response.context['some_new_data'] = new_data return response return wrapper @my_decor def view1(request): # some logic context = {'some_data': 'some_value'} return render(request, 'some_template.html', context) @my_decor def view2(request): # more logic return render(request, 'another_template.html') So, bassically, I want to create decorator, that can be used with views that attach context on return and with those that don't. Right now I get AttributeError: 'HttpResponse' object has no attribute 'context'. What am I doing wrong? Python 2.7.13 and Django 1.7.11 -
uuid OR slug for seo friendly url in django
I am new to django and making small book project locally. For detail view I am currently using uuid for unique url. But that id is some random number. The book I am currently following has this small article **Slugs vs. UUIDs** Using the pk field in the URL of our DetailView is quick and easy, but not ideal for a real-world project. The pk is currently the same as our auto-incrementing id. Among other concerns, it tells a potential hacker exactly how many records you have in your database; it tells them exactly what the id is which can be used in a potential attack; and there can be synchronization issues if you have multiple front-ends. There are two alternative approaches. The first is called a “slug,” a newspaper term for a short label for something that is often used in URLs. For example, in our example of “Django for Professionals” its slug could be django-for-professionals. There’s even a SlugField191 model field that can be used and either added when creating the title field by hand or auto-populated upon save. The main challenge with slugs is handling duplicates, though this can be solved by adding random strings or numbers … -
I am getting an error NoReverseMatch at sub_detail in Django
I know that my view is correct, however, when I put {% url 'sub_detail' subc.id %}in index.html it suddenly gives an error of no reverse match. Once I remove it index works fine. I tried changing id, but it did not change anything as it still gives the same error. Thanks in advance. views.py: from django.shortcuts import render, redirect, reverse, get_object_or_404 from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import Slides, MainContent, SubContent from .forms import TitleForm, SubContentForm, SlidesForm def index(request): slides = Slides.objects.all() maincontent = MainContent.objects.all() subcontent = SubContent.objects.all() context = { 'slides': slides, 'maincontent': maincontent, 'subcontent': subcontent, } return render(request, 'home/index.html', context) def sub_detail(request, subc_id): subcontent = get_object_or_404(SubContent, pk=subc_id) context = { 'subcontent': subcontent, } return render(request, 'home/sub_detail.html', context) urls.py: path('', views.index, name='home'), path('<int:subc_id>/', views.sub_detail, name='sub_detail'), path('manage/', views.manage, name='manage'), path('slides/', views.slides, name='slides'), path('title/', views.add_title, name='add_title'), path('sub/', views.add_sub_content, name='add_sub_content'), ] models.py: class SubContent(models.Model): class Meta: verbose_name_plural = 'Sub Content' title = models.CharField(max_length=28, null=False, blank=False) image = models.ImageField() description = models.TextField() def __str__(self): return self.title index.html: <a href="{% url 'sub_detail' subc.id %}"> <div class="col-md-6 section-index-img"> <img src="{{ sub.image.url }}" class="rounded img-fluid" alt=""/> </div> </a> error code: Environment: Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.1 Python Version: … -
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