Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Optimize IN CLAUSE in django
I want to optimize the following query with a Django==1.8.5 P.S I cannot upgrade the DJNAGO version at this point and use Exists clause This is taking almost 20 seconds to execute as the number of rows in this table is 41240271 query_action = Action.objects.filter(id=user_id, verb__in=list_of_verbs) query_action.order_by("-timestamp") last_activity = query_action[0] SELECT * FROM "action" WHERE ("action"."verb" IN (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) AND "action"."id" = %s) ORDER BY "action"."timestamp" DESC LIMIT ? -
'CustomUserCreationForm' object has no attribute 'cleaned_data'
The 'cleaned_data' attribute is not working on my custom form. The same issues I am facing while I try to use 'cleaned_data' directly through views.py file. Even after searching everywhere on internet, the issue is not resolved. Please help. The error displayed once I Submit the form: 'CustomUserCreationForm' object has no attribute 'cleaned_data' forms.py shows class CustomUserCreationForm(forms.Form): username = forms.CharField(label='Enter Application number', min_length=4, max_length=150) email = forms.EmailField(label='Enter email') password1 = forms.CharField(label='Enter password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) def clean_username(self): username = self.cleaned_data['username'].lower() r = User.objects.filter(username=username) if r.count(): raise ValidationError("Username already exists") return username def clean_email(self): email = self.cleaned_data['email'].lower() r = User.objects.filter(email=email) if r.count(): raise ValidationError("Email already exists") return email def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise ValidationError("Password don't match") return password2 def save(self, commit=True): user = User.objects.create_user( self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password1'] ) return user and in views.py def register_view(request): form =CustomUserCreationForm() if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid: roll_no = form.clean_username() email = form.clean_email() print(roll_no) print(email) context = { 'form':form } return render(request,'accounts/register_page.html',context) and in the template: <form action="" method="post"> {% csrf_token %} {{form.username}} {{form.email}} {{form.password1}} {{form.password2}} <button type="submit">Submit</button> </form> -
How to override Django Admin AutoComplete widget wrapper
I'm trying to override the AutoComplete widget in the admin and it's been a nightmare because I don't think many people have tried to customize it much. It's also wrapped in another widget RelatedFieldWrapper which I need to pass a dynamic variable to after a file has been uploaded. For context: what I do is I fetch some values from that file, and use them as initial data to create a bunch of inline formsets. This fine, but one of the columns is an Autocomplete. I can't pass data to that field since it needs a foreign key I won't know in advance, so I'm sending the data to that field as extra text in the Autocomplete's wrapper. So far this is what I have: class ChartItemForm(forms.ModelForm): hint = forms.CharField(widget=forms.HiddenInput) title = forms.ModelChoiceField(queryset=Title.objects.all()) def __init__(self, *args, **kwargs): super(ChartItemForm, self).__init__(*args, **kwargs) if 'hint' in self.initial: hint = self.initial['hint'] self.fields['title'].widget = MyRelatedFieldWidgetWrapper( AutocompleteSelect(self.instance._meta.get_field('title').remote_field, site._registry.get(Title).admin_site,), self.instance._meta.get_field('title').remote_field, site._registry.get(Chart).admin_site, hint=hint) It's ugly but it works kinda, but I'm getting this error: 'tuple' object has no attribute 'field' After much digging I saw it's because the Autocomplete widget's choices attribute don't have the field attribute. I guess in my overwrite the field is not being properly … -
Django Table Join ORM query
I have Three tables which i need to join using the django orm query if anyone could help please. These are the example models: Table1 - Debtors name = model.CharField(max_length=50) Table2 - CreditSales date = models.DateField() debtor = models.ForeignKey(Debtors, on_delete=models.CASCADE) amount = models.PositiveIntegerField() Table3 - DebtorPayment date = models.DateField() debtor = models.ForeignKey(Debtors, on_delete=models.CASCADE) amount = models.PositiveIntegerField() I tried this query in my views, but its giving duplicate results when trying to fetch a single debtor results from the three joined tables: def get_debtor_details(request, pk): results = Debtors.objects.filter(pk=pk).values('creditsales__date', 'creditsales__amount', debtorpayment__amount').distinct().order_by('creditsales__date') this query gives duplicate results. Please Help. Expected output date credit amount payment 1/1/20 50,000 50,000 2/1/20 70,000 60,000 and so on -
React-admin. Populate SelectField choices with ENUM from IntrospectionQuery (GraphQL simple data provider)?
My GraphQL backend is django-graphene, which creates ENUM kind in schema for every enumeration field (field with defined choices in django models). React-admin data provider is ra-data-graphql-simple. django model Choices are defined in Django model and this is set in stone: class Dataset(models.Model): class State(models.IntegerChoices): INIT = 0, _('Initializing') STARTED = 1, _('Started') READY = 2, _('Ready') state = models.IntegerField(choices=State.choices, default=State.INIT) django-graphene class DatasetQL(DjangoObjectType): class Meta: model = Dataset IntrospectionQuery { "data": { "__schema": { ... "types": [ ... { "kind": "OBJECT", "name": "Dataset", "description": null, "fields": [ ... { "name": "state", "description": "", "args": [], "type": { "kind": "NON_NULL", "name": null, "ofType": { "kind": "ENUM", "name": "DatasetState", "ofType": null, "__typename": "__Type" }, "__typename": "__Type" }, "isDeprecated": false, "deprecationReason": null, "__typename": "__Field" }, ... ], "inputFields": null, "interfaces": [], "enumValues": null, "possibleTypes": null, "__typename": "__Type" }, ... { "kind": "ENUM", "name": "DatasetState", "description": "An enumeration.", "fields": null, "inputFields": null, "interfaces": null, "enumValues": [ { "name": "A_0", "description": "Initializing", "isDeprecated": false, "deprecationReason": null, "__typename": "__EnumValue" }, { "name": "A_1", "description": "Started", "isDeprecated": false, "deprecationReason": null, "__typename": "__EnumValue" }, { "name": "A_2", "description": "Ready", "isDeprecated": false, "deprecationReason": null, "__typename": "__EnumValue" } ], "possibleTypes": null, "__typename": "__Type" }, ... ], "__typename": "__Schema" } … -
Django object saved while debugging but won't save when code is run with debugging
I am using nested serializers and I have overridden the update method of ModelSerializer. A Strange thing is happening when I run the code. If I debug the code line by line, the nested object is updated but if I run the code without debugging, the object is not updated. Here is my update method of serializer - try: nested_object_data = validated_data.pop('nested_data')[0] nested_object = instance.nested_object.all() for (key, value) in nested_object_data.items(): setattr(nested_object[0], key, value) nested_object[0].save() except KeyError: pass for (key, value) in validated_data.items(): setattr(instance, key, value) instance.save() return instance Thanks a lot for your time and help. -
Filter by Users Group
I only want to show buttons based on a user group. In this example I have a list of buttons then an IF Statement that checks if the user is in the group 'Recruiter', if they are then it displays some additional buttons: Is there an easier way to do this in the html, like {% if request.user.groups == 'recruiter' %} Views.py fields = request.user.groups if fields == 'Recruiter': fields1 = 'True' else: fields1 = '' context['fields1'] = fields1 html {% if fields1 %} a bunch of buttons {% endif %} -
How to use custom YAML file as API documentation in Django REST Framework?
I need to add API documentation to my project. I wrote my custom schema using swagger editor and now I have a YAML file as follows: swagger: "2.0" info: description: "This is the documentation of Orion Protocol API" version: "1.0.0" title: "Orion Protocol API" host: "127.0.0.1:8000" basePath: "/api/" paths: /api/decode: post: tags: - "pet" summary: "Decode the payload" consumes: - "application/json" produces: - "application/json" parameters: - in: "body" name: "body" description: "Packet data" required: true schema: $ref: "#/definitions/PacketData" responses: "405": description: "Invalid input" /api/encode: post: description: "Encoding configuration parameters for the devices" produces: - "string" parameters: - in: "body" name: "body" description: "Addresses and values of configuration parameters" required: true schema: $ref: "#/definitions/ConfigPayload" responses: "405": description: "Invalid input" definitions: PacketData: type: "object" required: - "payload" properties: payload: type: "string" description: "Packet string starting with 78" example: "78010013518BB325140400000500000AAA0000002A6E0000004AC05D00006A00000000" ConfigPayload: type: "object" properties: Addresses of the configuration parameter: type: "string" description: "According to the documentation of configuration protocol" example: "542" Now how can I add this to the project? Where it should locate in the project? May the views render this file? I need to have the following path: urlpatterns = [ path('documentation/', some-view-that-will-render-yaml) ] -
How to Use Q to filter using String
Suppose I can have these lists of strings(I already know how to get these list of strings from the user): {"title, "year", "stars"} and {"title"}. If I get the 1st one from the user, I want to filter the Movie objects such that it works like: Movie.objects.filter(Q(title__icontains=query) | Q(year__icontains=query) |Q(stars__icontains=query)). If i get the 2nd one from the user, it is like Movie.objects.filter(Q(title__icontains=query) We have assured that the string in the list is a field of model. -
who to pass the id from template to view
this is my view : def delete_chat(request, id): chat=get_object_or_404(Chat,id=id) chat.delete() return redirect('msgs:inbox') and this is my template: <a href="{% url 'msgs:delete_chat' id=Chat.id %}" class="parag delete-btn">Delete chat</a>'+ and this is the error : NoReverseMatch at /messages/inbox/ Reverse for 'delete_chat' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['messages\\/inbox\\/delete\\/$'] can someone plz help me to figure out who to pass the id? -
Django Formset Delete Field Not Showing
I need to manually render my formset in my template and I cannot get the delete checkbox field into the template when I render manually. However, it does show when I render {{form.as_table}}. views.py QuoteManifestForm= modelformset_factory(QuoteManifest, QManifestForm, can_delete = True) template - this does not display the {{form.DELETE}} but every other field shows fine, including id which I can see in the DOM. {{ manifest.management_form }} <--!I passed QuoteManifestForm to template as 'manifest'--> {% for form in manifest.forms %} <div id="form_set"> <table id = 'manifest-table25' class="manifest-table2" width=100%> {% csrf_token %} <tbody width=100%> <tr class="manifest-row"> <td width = 17.5% class="productCode" onchange="populateProduct(this)">{{form.ProductCode}}</td> <td width = 32.5% class="description">{{form.DescriptionOfGoods}}</td> <td width = 12.5% class="quantity" oninput="calculateUnit(this)">{{form.UnitQty}}</td> <td width = 12.5% class="unitType">{{form.Type}}</td> <td width = 12.5% class="price" oninput="calculate(this)">{{form.Price}}</td> <td width = 12.5% class="amount2">{{form.Amount}}</td> <td>{{form.DELETE}}</td> {{form.id}} </tr> </tbody> </table> </div> {% endfor %} Any idea why that is not working? -
Django user specific transfer of files/images/pdf
Consider there are two types of users 1. Creator. 2. Approver. The creator will upload a file and process it by clicking a button (by the way the file should not be in his queue) now, the file needs to move the approver and he will approve it and then the file needs to go back to the original creator. Any material links or suggestions about the same? -
Seeking advice what to continue learning [closed]
I am a young programmer(<15 years old) who has knowledge of Python, Java and C++. By basic, I mean enough to solve the first fifteen problems of Project Euler.https://projecteuler.net/archives To give an even better understanding, I was able to complete the Google's Code Jam - Qualification Round: Question A in a few hours. https://codingcompetitions.withgoogle.com/codejam/round/000000000019fd27/000000000020993c Most of programming knowledge rests in Python, since it is just so much easier. For a few days now I have been wondering whether to learn JavaScript, HTML and CSS to try and get started with Web Development, or to hook to a Python framework, specifically Django, or to give Data Science or Machine Learning a go and see if i can get the hang of the basics. I have almost no knowledge of algorithms. I one's I do know are bubble sort, and binary search. Which path should I take?? ( I am good at Math and have been trying to teach myself calculus. ) -
Flask is not dedicting a backslash in th URLS
So I have used this to create a route@app.route('/hi) Def hello(): return "Hello World But now if I go to mydomain.com/hi is works good but if I go to mydomain.com/hi/ it throws a 404 error any idea Thanks -
How to Upload my Django Project to bigrock.in Server
How can i upload my Django website on bigrock.in? I'm only getting solutions to deploy Django Project to Heroku but is there a way to deploy the Project to any other Hosting websites ? -
404 Error After Adding Argument To URL Path
Ive got a users profile page and an update_profile page. My projects urls.py: re_path(r'^profile/(?P<username>[\w-]+)/$', include('users.urls')), My users.urls: path('update_profile', views.update_profile, name='update_profile'), Prior to adding the username argument to the url both of these links were working. Since adding the username argument, I can access the profile page but the update_profile page throws a 404 error. My understanding is that if the address bar reads www.site/profile/testuser/update_profile the projects urls.py will strip the www.site/profile/testuser/ and pass just update_profile to the profile apps urls.py, which then should match the path ive given. Why isnt this working? On my profile page I have a check that ensures the username passed in matches the logged in user (so users can only access their own profiles). I will need a similar check on the update_profile page, but currently arent passing username to the update profile page. How could I perform this check without passing it in a second time like /profile/testuser/update_profile/testuser? Thank you. -
On migration in Django, I get error Integrity Error 1364, "Field 'id' doesn't have a default value"
This is something that appeared after a few iterations of saving and restoring the MariaDB database. It doesn't matter how simple the change is, or what I'm changing, it will perform the migration, then throw this error. File "/home/.virtualenvs/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/.virtualenvs/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/home/.virtualenvs/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/home/.virtualenvs/venv/lib/python3.7/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/home/.virtualenvs/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/home/.virtualenvs/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 412, in _query rowcount = self._do_query(q) File "/home/.virtualenvs/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 375, in _do_query db.query(q) File "/home/.virtualenvs/venv/lib/python3.7/site-packages/MySQLdb/connections.py", line 276, in query _mysql.connection.query(self, query) _mysql_exceptions.IntegrityError: (1364, "Field 'id' doesn't have a default value") This is something I can work around just by ignoring it, but it's quite annoying and distracting. How do I fix it? -
get_field is not returning value in advanced-custom-fields-pro
I using advanced-custom-fields-pro in wordpress to allow wordpress user to type page id they wish to display in web, is there any way to get the data from wordpress user and in backend using wp_query and display the page with the data user entered in advanced-custom-fields-pro? Please take note, i named the field as “feature” in plugin. For my case, ‘feature’ can be contain multiple value like 1,2,3,4 so i would like to get my ‘feature’ value in array, what can i do for this? Currently, get_field didnt get value sucessfully. $feature = get_field(‘feature’); $the_query_featured = new WP_Query( array( ‘posts_per_page’ => 2, ‘posts_per_page’ => 2, ‘nopaging’ => false, ‘order’ => ‘DESC’, //’order’ => ‘ASC’, ‘orderby’ => ‘date’, ‘meta-key’ => $feature, ‘page_id’ => $feature, ‘post_type’ => ‘any’ )); <?php while ( $the_query_featured->have_posts() ) : $the_query_featured->the_post(); ?> -
How to add styling in django templates inside for loop using css?
I am making a simple blog project in which I am trying to inject each post's data using for loop template tagging. But in doing so, the grid becomes distorted when css is applied on blog list template. However this css works perfectly fine when tested on manually added posts inside a separate Html page. How to fix this because most of the css that works fine on normal Html pages doesn't work properly when combined with django templates. Here is my Basic Blog Posts template: {% extends 'basic_app/base.html' %} {% block content %} <div class="centerstage"> {% for post in post_list %} <div class="cards"> <div class="card"> <img class="card__image" src="{{ post.blog_pic.url }}" alt=""> <div class="card__content"> <p> <a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a> </p> <p> {{ post.text|safe|linebreaksbr }} </p> </div> <div class="card__info"> <div> <i class="material-icons">{{ post.published_date|date:"D M Y"}}</i>310 </div> <div> <a href="{% url 'post_detail' pk=post.pk %}" class="card__link">Comments: {{ post.approve_comments.count }}</a> </div> </div> </div> </div> {% endfor %} </div> {% endblock %} Html Code that works fine on manually adding posts: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="cards_style.css"> <title>Blog</title> </head> <body> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <div class="cards"> <div class="card"> <img class="card__image" src="https://fakeimg.pl/400x300/009578/fff/" alt=""> <div … -
Django: OperationalError at /admin/User/profile/, no such column: User_profile.user_id
I will cut straight to the chase. Basically, I am recreating the django.contrib.auth.forms UserCreationForm from scratch using the forms.py, views.py, and templates. Everything seemed to be working fine, until I tried to access the database where my Users are listed. That is when this error pops up. I've been delayed by this for a week or so now, and I am genuinely frustrated. I will greatly take utilize any help and support. This is my second time encountering the no such column error, so if anyone could explain what this is being caused by, please inform me. forms.py. from django import forms from django.contrib.auth.models import User class UserRegisterForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'password1', 'password2'] def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords do not match") return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') form.save() messages.success(request, f'Your account has been created! You are now able to ' f'log in') return redirect('login') else: form = UserRegisterForm() … -
Using Django localsettings.py with Elastic Beanstalk
I am using a combination of settings.py (saved in git) and localsettings.py (not saved in git) to configure my app and keep sensitive info out of git. I'm deploying the Elastic Beanstalk for the first time and can't figure out how to upload or create the localsettings.py in the correct place. If I scp it it appears as the ec-user and I can't create the file with the right ownership directly in the deployment directory. The ultimate setup for me would be to have a "master" file that lives just above the /var/app/current directory that I can copy into the correct place whenever I deploy. Any help would be appreciated. -
Django login authentication form
views from django.shortcuts import render, redirect from django.http import HttpResponse from .models import User, Order, Date from django.contrib import messages from django.contrib.auth import authenticate, login, logout from .forms import OrderForm def login_page(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('order-list') else: messages.info(request, 'Username or password is incorrect') context = {} return render(request, "login.html", context) urls from django.urls import path,include from .views import order_list,date_list,create_order,update_order,delete_order,login_page app_name = 'accounts' urlpatterns = [ path('', login_page, name='login-page'), path('orderlist/', order_list, name='order-list'), path('datelist/', date_list, name='date-list'), path('create_order/', create_order, name='create-order'), path('update_order/<str:pk>/', update_order, name='update-order'), path('delete_order/<str:pk>/', delete_order, name='delete-order'), login.html <form method="POST" action=""> {% csrf_token %} <div class="container"> <input type="text" placeholder="Enter Username" name="username" > <input type="password" placeholder="Enter Password" name="password" > <button type="submit">Login</button> </div> {% for message in messages %} <p id="messages">{{message}}</p> {% endfor %} </form> I'm trying to create a login form, where a user can log in if his credentials exist in admin users. But seems like the form is just not working. nfondjfnjodnfndjfnjdnfjdnfjdnjfnjnfjnjsdfjdjbfhbfnfdjnfdkfbkdbfdfndfbnfnjkbfvbnfkgbfkbghfbhgbfbgbfhbghkfbgbfkgbfbg kjnjndfnjfnbjrnjgntrjnt rjrntjrjnyt yjtnynt yjtnynt yjnntnj jfojgiodrng nogdjtgnd gojtih t hojnt -
Autocomplete jquery sending wrong link in
I have a autocomplete in my form and the autocomplete sending in wrong link. here is my URL Path here my template where i implement the autocomplete and the template loaded in browse Now this is my issue, when i type anything ccNumber textbox I expect to send request in /scrapdisposal/ccautocomplete but when i check in my cmd, it send in /scrapdisposal us you can see below screenshot in my browser in my CMD what wrong im done here? -
The most correct way to create REST API with already existed project
There is a one already working project on Django Framework also there is a need to create some paid REST API which will use the same database as that project. So which way will be the most correct? Create new project for API. Create API on already existed project. -
Is it worth learning ASP .NET Core - haven't learned C# / Django vs NodeJS [closed]
I started programming at Feb 2020 with python. I can only use javascript and python. I was looking for a web-framework because recently I felt like studying backend. I was thinking of Django or Node.js since they are like the superstars. But I watched a youtube video about this ASP .NET Core and it looked pretty awesome. So I'm kinda confused if I should just go with my original plan or study C#. And how do you guys think of Django vs Nodejs? Since I'm a newbie it takes me a while to learn any kind of thing.