Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue: Datatable Server Side Processing in Django
I am totally new in Django. I am trying to implement datatable server side processing.I have written some codes in my models.py , views.py and urls.py and followed Datatables official documentation also. But unfortunately I am getting error in my terminal and cant able to figure it out how can I fix it. Here is , models.py from django.db import models class Products(models.Model): title = models.CharField(max_length=100, blank=True) description = models.TextField(blank=True) price = models.IntegerField(blank=True, null=True) def __str__(self): return self.title views.py from django.shortcuts import render from ajax_crud.models import Products from django.http import JsonResponse def product_json(request): products_json = Products.objects.all().values('title', 'description', 'price') data = list(products_json) value = JsonResponse(data, safe=False) print(value) return value urls.py from django.urls import path from ajax_crud.views import product_json urlpatterns = [ path('json/',product_json,name='json'), ] demo-datatbles.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"> </head> <body> <h1>List of Products</h1> <hr> <table id="demo-table"> <thead> <tr> <th>title</th> <th>description</th> <th>price</th> </tr> </thead> <tbody></tbody> </table> <script src="//code.jquery.com/jquery-3.3.1.min.js"></script> <script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <script> $(document).ready(function() { $('#demo-table').DataTable( { "processing":true, "serverSide": true, "ajax": { "type" : "GET", "url": "{% url 'json' %}", "dataSrc": "objects" }, "columns": [ { "data": "title" }, { "data": "description" }, { "data": "price" }, ] } ); } ); </script> </body> </html> My error in terminal. … -
How to login to django application for unit test, I am getting response code as 301 for every view
I am trying to login first then test other methods in view. We have keycloak integrated with django application. c = Client() login = c.login(username='admin', password='12345') self.assertTrue(login) //this succeed response = self.client.get('other view') self.assertEqual(response.status_code, 200) // getting 301!=200 error Could you please help with the login, so that it will not redirect! thanks. -
Form data display on terminal & doesn't save in postgres database django
In my cause of learning django, I decided to start with small projects, I'm working on a simple registration page. I have my form on the home page (index.html). And I have a view.py page I pass all the data from the form to my postgres db. I realise data does not save in db, instead all the registration data display in terminal and the url bar. Here's my code; Form (index.html) <form action="/index/" method="POST"> {% csrf_token %} <div><p><label for="fName">First Name</label></div> <div><input type="text" name="fName"></input></div> </p> <p> <label for="lName">Last Name</label> <input type="text" name="lName"></input> </p> <p> <label for="email">Email</label> <input type="text" name="email"></input> </p> <div><p><label for="uName">Username</label></div> <div><input type="text" name="uName"></input></div> </p> <p> <label for="password1">Password</label> <input type="password" name="Password1"></input> </p> <p> <label for="password2">Confirm Password</label> <input type="password" name="Password2"></input> </p> <div> <p><input type="submit"></input></p> </div> </form> views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth def index(request): if request.method == 'POST': first_name = request.POST['fName'] last_name = request.POST['lName'] username = request.POST['uName'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] user = User.objects.create_user(username=username, password=password1, email=email, first_name=first_name, last_name=last_name) user.save() print('user created') return redirect('/') else: return render(request, 'index.html') I suspect the data is collected and them skip to executed this return render(request, 'index.html') because after I enter submit, the home page(index.html) … -
Django Mock an imported function used in a class function as part of a unit test
So I'm writing tests for my django application and I have successfully mocked quite a few external api calls that aren't needed for tests however one is tripping me up which is send_sms. To start here is the code: a/models.py: from utils.sms import send_sms ... class TPManager(models.Manager): def notification_for_job(self, job): ... send_sms() ... class TP(models.Model): objects = TPManager() ... p/test_models.py: @patch('a.models.send_sms') @patch('p.signals.send_mail') def test_tradepro_review_job_deleted(self, send_mail, send_sms): job = Job.objects.create( tradeuser=self.tradeuser, location=location, category=category, details="sample details for job" ) The Job object creation triggers TP.objects.notification_for_job via its perform_create method here: p/views.py: def perform_create(self, serializer): job = serializer.save(tradeuser=self.request.user.tradeuser) if settings.DEV_MODE: from a.models import TP job.approved = True job.save() TP.objects.notification_for_job(job) I have tried mocking a.models.TP.objects.notification_for_job, utils.sms.send_sms, a.models.TPManger.notification_for_job all to no avail. This is a pretty complex flow but I believe I have tried the main mock candidates here and was wondering if anybody knows how to either mock the notification_for_job function or send_sms function properly mostly just to prevent these api call that inevitably fail due to my test environment. Any ideas are greatly appreciated! -
How to implement a join query in django on a model with foreign keys
everyone. I want to implement a "following" function on my Profile model in django. i have a relationship model and i want to join both fields so that i can select the user that maches the query. I know peewee and i'll do something like the following: def following(self): return ( User.select().join(Relationship, on=Relationship.to_user).where(Relationship.from_user == self)) but i haven't been able to find how to make join queries in django. This are the models i have on models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) joined_at = models.DateTimeField() class Meta: ordering = ['-joined_at'] def __str__(self): return f'{self.user.username} profile' def following(self): """ I want to implement the query here. """ class Relationship(models.Model): from_user = ForeignKey(User, related_name='relationships') to_user = ForeignKey(User, related_name='related_to') -
Integrating Graphs with Django
I'm building my portfolio-site and I wanted to show my skills with the Graph. That will be a more creative way to represent skills I guess. I don't want to use complex libraries like D3.js and Django-graphos I want to keep it simple. any Suggestions? -
Adding items in a model
I'm working on a project where I've to add the first and second semester scores together. I summed up the first semester results in my models and also for the second semester also. But I've difficult summing the two models i.e the first and second. Here's my code for better understanding. Class First (models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) midscore = models.FloatField() finalscore = models.FloatField() def__str__(self): return self.user def get_total_first_score(self): return self.midscore + self.finalscore Class Second (models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) midscore = models.FloatField() finalscore = models.FloatField() def__str__(self): return self.user def get_total_second_score(self): return self.midscore + self.finalscore Now, how can I add the ger_total_score for the two semester. I tried something like this, but it's not giving me any results, since it's not under any model. def get_total_scores: get_total_first_score + get_total_second_score -
Django Inline formset validation with clean_<fieldname>() method
It's there anywhere validate the inline formset data with the clean_ "fieldname"() method instead of clean() method, the clean_"fieldname"() method is work in ModelForm but not in BaseInlineFormSet, I am tried browsing around, but no luck for me. class StockTransactionForm(forms.ModelForm): # clean() method def clean(self): to = self.cleaned_data.get('t') from = self.cleaned_data.get('from') # clean_<field>() method def clean_to(self): to = self.cleaned_data.get('t') return to class StockHistoryInlineFormSet(BaseInlineFormSet): class Meta: model = StockHistory fields = '__all__' # not working def clean_quantity(self): raise forms.ValidationError('tears') -
'str' object has no attribute 'as_view' in django
I am calling a class view inside class.Call_view value is "InsertionOrder" but it does not work instead directly writing 'InsertionOrder' works.Value is dynamic so i cant directly write 'InsertionOrder'.How to do this? Error shows: 'str' object has no attribute 'as_view' in django class GenericDetailView(APIView): def put(self, request,pk, format=None): url_name = request.resolver_match.url_name call_view = url_name.split("_")[0].title().replace('-', '') return call_view.as_view()(request._request, format) this does not # return InsertionOrder.as_view()(request._request, format) this works class InsertionOrder(APIView): #Code goes on -
How to configure both Memcache and database cache in the Django project
I am working with the Django project and get to know about the cache and its benefits. I had implement database cache and Memcache at the different project. Here is the config of the database cache. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'my_cache_table', } } python manage.py createcachetable Here is the config of Memcache. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } Note: Make sure you install this package. pip install pymemcache Problem: I wanted to use both caching in a single project. -
Django 3.1 | Django administration broken
I recently updated a Django project I had from 3.0 to 3.1 Everything seemed to work just fine, however, when rendering the page in Django administration (.../admin) everything was off-balance Here is what it looks like As you can see, if I zoom out the information is over there but, the scale is not correct. -
DJango>ConnectionRefusedError>App function that sends Password reset email
Good evening, I am having an issue in which I have built an app with a "Reset_Password_Email" function that sends an email to selected admin that allows them to reset their password. However when I submit my email I get a "ConnectionRefusedError at /accounts/password_reset/ [WinError 10061] No connection could be made because the target machine actively refused it" In the Tutorial it suggests that I add EMAIL_HOST = "localhost" and EMAIL_PORT = 1025 and that I run ''' python -m smtpd -n -c DebuggingServer localhost:1025 ''' in Powershell, but when I run it, I get no output, and when I attempt to send my email after leaving Powershell because of it's lack of an output and I run my server for my app, I am still faced with this crisis. Please help, and if there is any additional information that I can bring, feel free to let me know. Thank you! -
Having an error in creating contact us page in django?
models.py class Contact(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) message = models.TextField(max_length=400) def __str__(self): return f"{self.first_name} {self.last_name}" forms.py class ContactForm(ModelForm): class Meta: model = Contact fields = ["first_name", "last_name", "message"] widgets = { "message": Textarea( attrs={ "placeholder": "Xabaringizni kiriting!" } ) } project urls.py from django.contrib import admin from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$',views.HomePage.as_view(), name='home'), url(r'^admin/', admin.site.urls), url(r'^blog/', include('blog.urls',namespace='blog')), #url(r'^blog/',include('django.contrib.auth.models.urls')), url(r'^about/', views.AboutPage.as_view(),name='about'), #url(r'^contact/', views.ContactPage.as_view(),name='contact'), ] blog/urls.py from django.urls import path from . import views from . import models #Template tagging app_name = 'blog' urlpatterns = [ path('', views.PostList.as_view(template_name='index.html'), name='index'), path('<slug:slug>/', views.post_detail, name='post_detail'), path("contact/", views.ContactCreate.as_view(template_name='contact1.html'), name="contact"), path("thanks/", views.thanks, name="thanks"), ] blog/views.py from django.shortcuts import render, get_object_or_404 from django.views import generic from django.views.generic import ListView,DetailView,CreateView from .models import Post, Contact from django.urls import reverse_lazy from django.http import HttpResponse from .forms import CommentForm,ContactForm class ContactCreate(CreateView): model = Contact form_class = ContactForm success_url = reverse_lazy("thanks") def thanks(request): return HttpResponse("Rahmat Siz bilan tez orada bog`lanamiz!") contact_page/contact1.html all my pages are linked like this in navigation bar <nav class="navbar navbar-expand-sm navbar-dark bg-dark"> <div class="container"> <a href="{% url 'home' %}" class="navbar-brand"><i class="fas fa-balance-scale">iLawyer.uz</i></a> <button class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a … -
Django ORM using distinct disrupts other order_by parameters
Why does adding .distinct() to my query totally screw up the order_by() logic? I have the following query (Postgres backend): sort_order = '-car__cardate' statements = CarModel.objects.only( 'car__car_id', 'car__cardate', 'car__title', 'car__location', 'model__name' ).select_related( 'car', 'candidate', ).extra( select={ 'is_position_setting': 'type_id = 7', 'is_null_date': 'cardate IS NULL', 'shorttitle': extra, }, ).filter(**kwargs).order_by('is_position_setting', 'is_null_date', sort_order) If I only want a queryset that contains unique car__car_id items, I try updating the order_by to this: order_by('car__car_id', 'is_position_setting', 'is_null_date', sort_order) and adding distinct thusly: distinct('car__car_id', 'is_position_setting', 'is_null_date', sort_order) this results in a deduped queryset but all other ordering/sorting is ignored. What am I doing wrong here? All I can seem to get is either a non-dedupe ordered queryset to my specified ordering OR just a deduped no-ordered queryset. Tried to follow what's described here: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#distinct -
POST form data and wait the response or any other possible solution?
I made the research but couldn't found the answer I am looking for, most likely due to my failure to address the question properly. I hope I can do better here. So, I have a web form and I am sending this form's fields as JSON to the backend server via a POST request. The server should send back a JSON response to the client after a computation according to those fields. This computation could take up to 5 minutes or so on. My question is, does the server should send back the computed JSON as the response to this POST request? Or, is there any way to do something like set the job with a POST request, then GET the result somehow? Or, is there any other ways, like, what is the best practice? If the description is too vague, I can give more implementation detail. -
Create,Update in different view and get in different view in django class based view
My urls.py def generate_urls(): for service in SERVICES_MAPPING: service_name = service.split('_')[0] if 'list' in service: yield path( "v1/{}/".format(service_name), GenericListView.as_view(), name=service ) if 'detail' in service: yield path( "v1/{}/<int:pk>/".format(service_name), GenericDetailView.as_view(), name=service ) My view.py class GenericListView(APIView): def get(self, request, format=None): #for list view class GenericDetailView(APIView): def get(self, request, pk, format=None): #for detail view Urls.py is creating many urls and sending to same view for list and detail view.But for Create and Update i want to create seperate view with same url. In more detail: This are few urls created by urls.py.There are many. api/ v1/browser/ [name='browser_list'] api/ v1/browser/<int:pk>/ [name='browser_detail'] api/ v1/language/ [name='language_list'] api/ v1/language/<int:pk>/ [name='language_detail'] Now for 'v1/browser/' and 'v1/language/' calls GenericListView.'v1/browser/int:pk/' and 'v1/language/int:pk/' calls GenericDetailView.But when i create,update in 'v1/browser/' i need seperate view for this with same url. -
from_db_value error with cache in django3.0.10
I'm trying to update to Django3 and got an error in cache. Is it an existing bug because it's all an error in the Django package? It seems that this error occurs when the query is cached and the content of the query is empty. How can I handle this error? Traceback (most recent call last): File "project/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "project/lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "project/lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "project/lib/python3.8/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "project/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "project/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "project/lib/python3.8/site-packages/django/template/base.py", line 171, in render return self._render(context) File "project/lib/python3.8/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "project/lib/python3.8/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "project/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "project/lib/python3.8/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "project/lib/python3.8/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "project/lib/python3.8/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "project/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "project/lib/python3.8/site-packages/django/template/defaulttags.py", line 398, in render return strip_spaces_between_tags(self.nodelist.render(context).strip()) File "project/lib/python3.8/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "project/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated return … -
how to deploy django/react app to heroku with different directory structure
I have a django/react app I created using this tutorial here Although slightly different, I then tried to deploy my app to heroku using this tutorial here The directory structure following the tutorials are different though. My directory structure is as follows... django-todo-react/ backend/ backend/ todo/ manage.py ... frontend/ all my react stuff... in my django-todo-react folder (the project root directory) I have requirements.txt, Procfile, package.json, and '.gitignore` file. To my understanding the Procfile should contain something like web: gunicorn backend.wsgi but because my Procfile is in the root directory I do instead the following web: gunicorn backend/backend.wsgi that looks very weird but basically I go into my backend folder where I have my actual backend project I started with django-admin startproject backend and get wsgi. I added all the other stuff from the second tutorial I mentioned this one but still no such luck. I get a COLLECT_STATIC error and if I silence the error everything passes but I then get a application error when opening my heroku app. I have already tried deploying an app just using the 2nd tutorial and all worked fine but that had the directory structure of the second tutorial. I thought that changing … -
Clarification of Django and Celery workings
I implemented an installable app of Django which includes a Rate Limiter (a Python object), but I am afraid of going to production because I find no documentation or readings regarding how production server works compared to Django dev server. The Rate Limiter is a Python object, all the request should go through this limiter in order to be "safe" to make calls (to an API). So far in the Django dev server it is working as expected (everything shares the same rate limiter), but when I enable logs, I see that the app (and the limiter) was initialized twice, which wasn't clear of what is happening at all. While it does work on the dev server, I find no docs of production servers (the server I am using is Daphne or Apache depending if I add websockets support) if this still works as expected (they share the same object). Another question I have is regarding Celery, will Celery tasks also share the same app object (and rate limiter)? I have a task that runs periodically for a large amount of time. -
Django filter returns queryset with ID instead of username
Hi guys so I have a search function but when using the .objects.filter() method I get a queryset that shows an ID instead of the username. This is the view: def search_expense(request): if request.method == 'POST': search_str = json.loads(request.body).get('searchText') expenses = Expense.objects.filter( amount__istartswith=search_str) | Expense.objects.filter( date__icontains=search_str) | Expense.objects.filter( description__icontains=search_str) | Expense.objects.filter( category__icontains=search_str) data = expenses.values() return JsonResponse(list(data), safe=False) <QuerySet [{'id': 16, 'amount': 2.33, 'date': datetime.date(2020, 10, 2), 'description': 'Something', 'owner_id': 1, 'category': 'Food'}]> So instead of the 'owner_id': 1 I need it to be 'owner': username The model (the User model is Django's standard model): class Expense(models.Model): amount = models.FloatField() date = models.DateField(default=now) description = models.TextField() owner = models.ForeignKey(to=User, on_delete=models.CASCADE) category = models.CharField(max_length=255) def __str__(self): return self.category class Meta: ordering: ['-date'] -
Media Files not Loading on pythonanywhere.com (Django)
I deployed a personal portfolio project using pythonanywhere.com's server and my instructor sent me a video explaining why my media files weren't loading properly (https://d.pr/v/RARFcF) but I couldn't understand what he was telling me I should do about it. If you look at my urls.py file I believe my code is good. Can someone please examine this, thanks? Can someone please watch it and help me understand what he was trying to tell me to do!? Thanks. website: https://willpeoples1.pythonanywhere.com/ -
AttributeError: module 'django.db.models' has no attribute 'DataField'
i tried running my server then i got this updated_at=models.DataField(auto_now_add=True) AttributeError: module 'django.db.models' has no attribute 'DataField' Based on the line of the error, here is the code exactly where the error was detected. id=models.AutoField(primary_key=True) name=models.CharField(max_length=225) email=models.CharField(max_length=224) password=models.CharField(max_length=225) created_at=models.DateField(auto_now_add=True) updated_at=models.DataField(auto_now_add=True) objects=models.Manaager() Kindly help me as i am new to python -
Im not sure what im doing wrong here but im guessing i need to change the path
main urls.py: from django.contrib import admin from django.urls import path , include urlpatterns = [ path('admin/', admin.site.urls), path(r'' , include("learning_logs.urls", 'app_name')) ] second urls.py: from django.urls import path from . import views urlpatterns = [ #Home page path(r'^$', views.index, name='index'), ] app_name = 'learning_log' views.py: from django.shortcuts import render def index(request): return render(request , 'learning_logs/index.html') result: djangowebapp -
Django: Order object depending in two values
So I have this: class Thread(models.Model): first_thread_notification = models.IntegerField(default=0) second_thread_notification = models.IntegerField(default=0) I need to order the objects depending on the sum of the 2 objects: class Meta: ordering = ['-first_thread_notification' + '-second_thread_notification'] I know this is incorrect but how can I do it? -
Graphene-django - Mutating types with enums
So, I have the following model: class Semester(models.Model): course = models.ManyToManyField(Course, through='CourseSemester') class SemesterType(models.TextChoices): A = 'A', 'Winter' B = 'B', 'Spring' SUMMER = 'SU', 'Summer' name = models.CharField( max_length=200, choices=SemesterType.choices, default=SemesterType.A, ) year = models.IntegerField() I try to add a mutation to add a new semester. Graphene-django seems to automatically generate an Enum field for me, but how can I get it inside the arguments? According to the github issues, something like SemesterType._meta.fields['name'] should work, but I can't get it right, even with wrapping it inside graphene.Argument. It is possible to tell Graphene not to convert it to Enum, however I'd rather avoid that if possible. Any clue how to get that right?