Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should you check before setting a Django model's field?
I have a background service that imports django, and uses my django project's ORM directly. It monitors something, in a loop, very often - every few seconds. It goes through every user in my database, checks a condition, and based on that, sets a flag to either be True or False. I might have thousands of users in the database, so the efficiency here can add up. while True: time.sleep(5) for user in User.objects.all(): if user.check(): user.flag = True else: user.flag = False user.save() I'm using MySQL as my database. What I'm curious about is this: if a particular user has .flag set to True, am I doing a disk write every time I run user.flag = True; user.save(), even though nothing changed? Or is Django or MySQL smart enough not to do a disk write if nothing changed? I assume a MySQL read operation is less expensive than a write operation. Would it make more sense to check the value of user.flag, and only try to set user.flag if the value actually changed? This would essentially be exchanging a database read for a database write, from what I understand (except in cases where something actually changed, in which case, … -
How to prevent multiple calls to get_queryset() in django?
In my views.py, I have a custom get_queryset() that filters records on the user. When I update or create a specific record, I need information from the queryset to set some fields, so I end up with multiple calls to get_queryset(). If get_queryset() becomes more complex, my performance may decrease a bit. def update(self, request, *args, **kwargs): # Gets the model instance (which calls get_queryset() by default) object = self.get_object() # Updates the object and passes the queryset to the update method. if object.update(json.loads(request.body), self.get_queryset()): return HttpResponse('Successfully updated object') else: return HttpResponse('Error updating Object') Is there anyway to store the queryset temporarily when I call self.get_object? -
Filtering items by their exact title
I am trying to filter my items by exact title by clicking on the link with the title. I managed to display the titles, but when I click on one of them I am getting an error: Reverse for 'category_search' with arguments '('',)' not found. 1 pattern(s) tried: ['search/(?P<category_id>[0-9]+)$'] , which is pointing to the TitleView function. views.py- Just to clear some things up category_view is used to filter items by their category, which is located on different page, but the results are displayed on search.html def category_view(request, category_id): item_list = Item.objects.filter(category__pk=category_id) category = Category.objects.get(pk=category_id) return render(request, "search.html", {'item_list': item_list, 'category': category}) def TitleView(request, title): item_list = Item.objects.filter(title__iexact=title) return render(request, "search.html", {'item_list': item_list}) def SearchView(request, category_id=None, title=None): if category_id: category = Category.objects.get(pk=category_id) item_list = Item.objects.filter(category__id=category_id) else: item_list = Item.objects.all() query = request.GET.get('q') if query: item_list = item_list.filter(title__icontains=query) price_from = request.GET.get('price_from') price_to = request.GET.get('price_to') item_list = item_list.annotate( current_price=Coalesce('discount_price', 'price')) if price_from: item_list = item_list.filter(current_price__gte=price_from) if price_to: item_list = item_list.filter(current_price__lte=price_to) context = { 'item_list': item_list, 'category': category, } return render(request, "search.html", context) html template: <div class="offset-md-1 col-md-2"> <h2>Content Filter</h2> <br> <form method="GET" action="{% url 'core:category_search' category.id %}"> <h5>Search</h5> <div class="form-row"> <div class="form-group col-8"> <div class="input-group"> <input class="form-control py-2 border-right-0 border" type="search" name="q" … -
Error when passing data from python to html
when I try to transfer data between my views.py file and my home.html file within templates nothing is happening, I view the source code of the HTML and there is not my inputed data. My django version is 3.0.3 and I am running python 3.8.1 My code for the views.py file: from django.shortcuts import render from django.http import HttpResponse posts = [ { 'author': 'LukeA', 'title': 'Blog post 1', 'content': 'First post content', 'date_posted': '19th February' }, { 'author': 'John', 'title': 'Blog post 2', 'content': 'Second post content', 'date_posted': '20th February' } ] def home(request): context = { 'posts': posts } return render(request, 'blog/home.html', context) HTML File being called: <!DOCTYPE html> <html> <head> <title></title> </head> <body> {% for posts in post %} <h1>{{post.title}}</h1> <p>By {{ post.author }} on {{ post.date_posted }}</p> <p>{{post.content}}</p> {% endfor %} </body> </html> = -
How to mock relations on Django
How are you doing? I'm currently running into a problem, I can't figure out how to mock a relation. Let's say I have some model called class MyModel(models.Model): name = models.CharField(max_length=10) class RelatedModel(models.Model): my_model = models.OneToOneField(MyModel, on_delete=models.CASCADE, related_name='related_model') name = models.CharField(max_length=10 And I have some repository class like this: class MyModelRepository: @staticmethod def get_related_model(my_model): try: return my_model.related_model except MyModel.related_model.RelatedObjectDoesNotExist: # do some other thing When writing unit-tests for this how can I mock the related_model to raise this exception or return some arbitrary instance? -
How do I modify my Django REST endpoint to automatically create a dependent model when creating the submitted model?
I'm using the djangorestframework module to set up an API to update/read my models. I have these models ... from django.db import models from address.models import AddressField from phonenumber_field.modelfields import PhoneNumberField from address.models import State from address.models import Country class CoopTypeManager(models.Manager): def get_by_natural_key(self, name): return self.get_or_create(name=name)[0] class CoopType(models.Model): name = models.CharField(max_length=200, null=False) objects = CoopTypeManager() class Meta: unique_together = ("name",) class Coop(models.Model): name = models.CharField(max_length=250, null=False) type = models.ForeignKey(CoopType, on_delete=None) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() and I have these view classes ... class CoopList(APIView): """ List all coops, or create a new coop. """ def get(self, request, format=None): coops = Coop.objects.all() serializer = CoopSerializer(coops, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = CoopSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class CoopDetail(APIView): """ Retrieve, update or delete a coop instance. """ def get_object(self, pk): try: return Coop.objects.get(pk=pk) raise Http404 def get(self, request, pk, format=None): coop = self.get_object(pk) serializer = CoopSerializer(coop) return Response(serializer.data) def put(self, request, pk, format=None): coop = self.get_object(pk) serializer = CoopSerializer(coop, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): coop = self.get_object(pk) coop.delete() return Response(status=status.HTTP_204_NO_CONTENT) Problem is, I … -
Python CSV: Unable to upload file. Index Error("String index out of range")
I am trying to import a file using Python: I understand why Ive got this error but dont manage to correct it. The code tries to access a blank line and return an out of range error message. How could I correct this? Many Thanks, file_data = csv_file.read().decode("utf-8") print("1") lines = file_data.split("\n") #loop over the lines and save them in db. If error , store as string and then display for line in lines: if not line: continue line = line.strip() print(line) # following line may not be used, as line is a String, just access as an array #b = line.split() print(line[0]) print("2") fields = line.split(",") data_dict = {} data_dict["project_name"] = fields[0] -
Django User has no profile?
I have create superuser using terminal, and when i tried to to login i see this error what should i do to correct this error? this is my models.py @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() -
has_changed() missing 2 required positional arguments: 'initial' and 'data'
I'm trying to prevent the user from meddling with a hidden form field by checking in the view like so: if form.fields["email"].has_changed(): form.add_error( "email", ValidationError( "Email does not correspond to user", code="invalid_email", ), ) but I get the following TypeError: has_changed() missing 2 required positional arguments: 'initial' and 'data' At this point, form is a "bound form" which has gone through the user and a POST request, by the way. Inspecting the function itself, it does seem to have two non-optional parameters, but the documentation does not mention these at all, and it's not too clear to me what I should pass anyway: if I have to provide the initial value and the new value myself, I could just compare those by myself with no need for this method. What am I missing? It also occurred to me that I just need to set the field as disabled and any changed value would be ignored, but I'm still curious nonetheless. -
Formatting a table in HTML from Django
I have a constantly updated csv table. The table is sent to the server and displayed in html. How can I make it display correctly? All my attempts end in failure. This is how the tables look now: enter image description here And this is what I'm trying to do: enter image description here views.py def csv_simple_read(request): path = os.path.dirname(__file__) file = os.path.join(path, 'name.csv') with open(file) as csv_file: csv_reader = csv.reader(csv_file, delimiter=';') line_count = 0 resultlist = [] for row in csv_reader: resultdict = {} resultdict['name'] = row[0] resultdict['date'] = row[1] resultdict['time'] = row[2] resultdict['status'] = row[3] resultlist.append(resultdict) line_count += 1 return render(request, "blog/index.html", {'results': resultlist}) index.html <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading">Checklist</div> <div class="panel-body"> <table> <thead> <tr> <th>Phone Number <h4>{% for result in results %} {{ result.name}} {% endfor %} </h4> </th> <th>Time <h4>{% for result in results %} {{ result.date }} {{ result.time }} {% endfor %} </h4> </th> <th>Status <h4>{% for result in results %} {{ result.status }} {% endfor %} </h4> </th> </tr> </thead> </table> </div> </div> </div> </div> name.csv test1;2020-02-16;05:22:49;OK test2;2020-02-16;05:22:25;OK test3;2020-02-16;05:22:10;BAD test4;2020-02-16;05:22:25;OK test5;2020-02-16;05:22:10;BAD I would be grateful for any help -
WKHTMLTOPDF producing unreadable pdf's
I am building a tool that converts a page, after a user takes an action, to pdf. Everything generates but when I try to open the pdf I get "ERROR Failed to load document" in Chrome and any other pdf viewer I use. When opening the file via text edit, this is what a portion looks like and its text like this throughout: lioÚUDb”„@£ˆ&†£√¿¢ıFóF∆RèÔ`ê¿P‡@`P‡@P @pP‡P @P–P@Ä Other than this, I am not receiving any errors so I don't know where to go next. Using: WKHTMLTOPDF - 0.12.5 Ubuntu - 18.4 -
Passing values from Django template to javascript-ajax function
Now my template displays a table having a link on each row to display more details. Each row passes unique column_name,db_name,schema_name,tablenm combination to get more details . Values The above code works , but open a new window for the result set. But , I would like to route it through a javascript(Jquery-django) and capture the result back in Java script and display the result as a javascript message without refreshing the complete page . How Can I pass there values (column_name,db_name,schema_name,tablenm) to the java script on the click event I Tried replacing href with button and set a value to it But seems not working. I welcome any help on this . Thanks In advance -
Is it possible to add a simple python application to a django project and use it?
I have a python project in which its output is a simple text. is it possible to add it to django project and use it? I am new to django web developing and I am trying to make an online interface for my python project. Is it possible to simply copy and paste this project's files and folders in django and use it? -
AWS Cognito for Django3 + DRF Authentication
I'm trying to set up an AWS Cognito backend I have a React frontend already working with it, now I need my DRF API to authenticate using the Cognito as backend. I have found a few Python packages for that, none of them seem to be actively maintained django-warrant doesn't work with Django3 and is pretty much dead Django Cognito JWT seems to be my best bet, but also not actively maintained, the documentation is very poor, and there is a medium post on how to use, not very detailed, but better than nothing. So, I tried to follow the documentation Added the env vars on my settings COGNITO_AWS_REGION = 'us-east-1' COGNITO_USER_POOL = 'us-east-1_xxxxxxx' # same user pool id I'm using on the React app COGNITO_AUDIENCE = 'XXXXXXXXXXXXXXXXXXXXXX' # the same client id I'm using on the React app Then on my DRF authentication classes: 'DEFAULT_AUTHENTICATION_CLASSES': [ 'django_cognito_jwt.JSONWebTokenAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ], And finally the user model: AUTH_USER_MODEL = 'accounts.MyUser' COGNITO_USER_MODEL = "accounts.MyUser" My custom User Model: class MyUser(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() I'm also using DRF JWT package, and if I try to login … -
Not able to retrieve or create database objects inside django view function inside aws amazon linux v2
I am using amazon linux v2 with python 3.6 and django 2.2.0: I have set up database using RDS MYSQL DB instance. I am able to retrieve and/or create objects in python shell but not able to retrieve and/or create when using inside view function. pqs=ExpertQa.objects.filter(category="public") return render(request,'ebdjango/expert-qa.html',{'pqs':pqs}) the above code isn't fetching objects. I have tried passing list, string everything works fine.Just not able to get database objects. Please can anyone provide the solution? Is there any other syntax for linux? -
exercise 18-8 python crash course Cant loop Django
Using Django Hi im trying to loop through the toppings but the code doesn't work, i have been trying things since 2 days ago... so im freaking out its the only problem that's left to continue. Here is the hole project: https://github.com/Taiel-Kadar/Pizzas models: from django.db import models class Pizza(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Toppings(models.Model): pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE) name = models.CharField(max_length=200) class Meta: verbose_name_plural = 'toppings' def __str__(self): return self.name urls.py: from django.urls import path from . import views app_name = 'pizzas' urlpatterns = [ path('', views.index, name='index'), path('pizzas/', views.pizzas, name='pizzas'), path('pizzas/<int:toppings_id>/', views.toppings, name='toppings') ] views: from django.shortcuts import render from .models import Pizza from .models import Toppings def index(request): return render(request, 'pizzas/index.html') def pizzas(request): pizzas = Pizza.objects.all() context = {'pizzas': pizzas} return render(request, 'pizzas/pizzas.html', context) def toppings(request, toppings_id): toppings = Toppings.objects.get(id=toppings_id) context = {'toppings': toppings} return render(request, 'pizzas/toppings.html', context) toppings.html: {% extends 'pizzas/base.html' %} {% block content %} <p>Pizzas: {{ pizza }}</p> <p>Toppings:</p> <ul> {% for topping in toppings %} <li> <p>{{ topping }}</p> </li> {% empty %} <li>There are no toppings</li> {% endfor %} </ul> {% endblock content %} pizzas.html: {% extends 'pizzas/base.html' %} {% block content %} <p>Pizzas</p> <ul> {% for pizza in … -
URLField appending to 'http://127.0.0.1:8000/'
I have a ULRField that I'm trying to link using href but when I click it I am takn to something like http://127.0.0.1:8000/www.example.com rather than www.example.com models.py class Website(models.Model): website = models.URLField(max_length=100) template.html <a href="{{ dealer.website }}">{{ dealer.website }}</p> -
cannot load library libcairo
I have problem when trying to run a website in Django: OSError: no library called "libcairo-2" was found cannot load library 'libcairo.so.2': /lib/x86_64-linux-gnu/libfontconfig.so.1: undefined symbol: FT_Done_MM_Var cannot load library 'libcairo.so': /lib/x86_64-linux-gnu/libfontconfig.so.1: undefined symbol: FT_Done_MM_Var cannot load library 'libcairo.2.dylib': libcairo.2.dylib: cannot open shared object file: No such file or directory cannot load library 'libcairo-2.dll': libcairo-2.dll: cannot open shared object file: No such file or directory Althought the package is installed. I have installed weasyprint pip3 install weasyprint python -m pip install WeasyPrint sudo apt-get install build-essential python3-dev python3-pip python3-setuptools python3-wheel python3-cffi libcairo2 libpango-1.0-0 libpangocairo-1.0-0 libgdk-pixbuf2.0-0 libffi-dev shared-mime-info I also tried sudo apt install libcairo2-dev sudo apt install libgirepository1.0-dev I have Lubuntu system. Any ideas how can I fix it? Thanks in advance -
Generic Class: UpdateView and DeleteView not saving data back to model
The UpdateView and DeleteView not saving data back to model views.py class ProjectList(ListView): model = Project template_name = 'mainapp/browse_app.html' context_object_name = 'projs' class ProjectUpdate(UpdateView,request): model = Project fields = ['pname','desc','emailID'] template_name = 'mainapp/project_form_edit.html' form_obj = ProjectForm(request.POST) form_obj.save() class ProjectDelete(DeleteView): model = Project fields = ['id','pname','desc','emailID','updated_on'] template_name = 'mainapp/index.html' print('Deleted!') success_url = reverse_lazy('mainapp/projs') def form_display(request): data = Project.objects.all() return render(request,'mainapp/browse_page.html',{'data':data}) ... browse_page.html: has an edit link and a delete button and it displays the project details of the project which is clicked {% for i in data %} <center> <a href="#costumModal13{{ forloop.counter }}" role="button" class="btn btn-default" data-toggle="modal">{{ i }}</a> </center> <!-- Modal --> <div id="costumModal13{{ forloop.counter }}" class="modal" data-easein="bounceLeftIn" tabindex="-1" role="dialog" aria-labelledby="costumModalLabel" aria-hidden="true"> <a class="btn btn-info btn-lg fa fa-pencil-square-o" href="{% url 'project_edit' pk=i.id %}" aria-hidden="true">Edit</a> <form method="POST" action="{% url 'project_del' pk=i.id %}"> {% csrf_token %}<input type="submit" value="Delete"> </form> {{ i.pname }} {{ i.id }} {{ i.updated_on }} </div> {% endfor %} urls.py from django.contrib import admin from django.urls import path, include, re_path from mainapp import views from mainapp.views import ProjectUpdate, ProjectDelete app_name = 'mainapp' urlpatterns = [ path('browse/',views.form_display,name="browse_page"), re_path(r'^browse/(?P<pk>\d+)/$', ProjectUpdate.as_view(), name='project_edit'), re_path(r'^browse/delete/(?P<pk>\d+)/$', ProjectDelete.as_view(), name='project_del'), ] On submitting the edited form: On clicking on delete button: Can you help me resolve these … -
somthing's wrong with django messages
I have a view function like this: @login_required def delete_deal(request): title = "Delete deal" user = get_object_or_404(User, id=request.user.id) user_deals = Deal.objects.filter(user=user) if not user_deals.exists(): messages.add_message(request, messages.INFO, 'You have no deal.') return redirect('index') return render(request, 'booking/confirmation_delete.html', {'title': title}) If I test with a user who does not have a deal the message is not displayed the first time but if I redo the message is displayed 2 times, what is wrong ? I have another view function which returns a message and it displays it normally !! If you need more info tell me -
Is the server running on host "localhost" (127.0.0.1) and accepting
I am using nginx ubuntu 18.04 I install already the redis-server and i receive this error when i go to the admin site CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, # "symmetric_encryption_keys": [SECRET_KEY], }, } -
Timber.io + Django + Heroku | How to only display application logs
I have a Django application running on Heroku with a drain sending logs to my Timber.io source. Currently, my Timber.io logs display: The logs that I wrote in my app to display (All I want) app logs heroku logs Here is a link to what a section of my Timber.io logs look like. Notice how there are app web.1 and heroku router logs. I don't want any other logs other than the ones I write in my Django application. Django code: logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) timber_handler = timber.TimberHandler( source_id=config('TIMBER_SOURCE_ID'), api_key=config('TIMBER_API_KEY'), level=logging.DEBUG ) logger.addHandler(timber_handler) ... logger.warning('A user has navigated to the homepage') # To reiterate, logs like this are all I want to display in my Timber.io logs. I have sent a few emails posing this question to Timber.io's support email. But, after a week, I haven't received a response. This is my first question so I apologize if I did something incorrectly. Thanks in advance for responses. -
Once I create a web app using Django + Python can I alter models?
If I am creating my first python web app using Django, am I able to at a later date, edit/change up models/views and have the program do so accordingly? Do I have to run a specific command to update my web app? Or Do I need to create the web application the way I want too right away? I have been trying to google this, but am unable to come to a concrete answer. I am just using tutorials, but will want to add my own features at a later date, and want to make sure I do not need to create another app for example. Please remember, I am still fairly new. -
Dynamic nested serializer field Django REST Framework
I am trying to have a serializer of a Parent model, with a nested serializer as a field, being different regarding another string field. For example, if the registry_type field is equal to intra I want to use _IntraRegistrySerializer to serialize/deserialize the registry_data field, but if registry_type is equal to slack, I want to use _SlackRegistrySerializer for the same field. I managed to have the serialization working doing this: class RegistrySerializer(serializers.ModelSerializer): def to_representation(self, instance): data = super().to_representation(instance) if isinstance(instance, IntraRegistry): data["registry_type"] = "intra" data["registry_data"] = _IntraRegistrySerializer(instance=instance).data if isinstance(instance, SlackRegistry): data["registry_type"] = "slack" data["registry_data"] = _SlackRegistrySerializer(instance=instance).data return data class Meta: # `Registry` being the parent model of both `IntraRegistry` and `SlackRegistry` model = Registry fields = ["id", "description"] But it only does half of what I would like to do. I tried overloading methods, using SerializerMethodField, and even though I keep on searching and reading the doc I can't manage to find a solution. -
django urls all routed to the same view
This is my current urls.py from django.contrib import admin from django.urls import path from appA import views as pviews from appB import views as dviews urlpatterns = [ path('page1', dviews.index), path('page2', pviews.socks5), path('page3', pviews.socks4), ] For some reason every single time I go to mysite.com/page2 or any of the urls I get a 404 error and nothing else. This issue doesn't occur when I run it on my local environment, for some reason it only happens when I deploy so I think it might be an issue with uWSGI. The command I use to start uWSGI is uwsgi --chdir=/path/to/django --wsgi-file=/path/to/django/django_test/wsgi.py -module=django_test.wsgi:application --env DJANGO_SETTINGS_MODULE=django_test.settings --master --pidfile=/tmp/project-master.pid --socket=127.0.0.1:3031 --processes=5 --harakiri=20 --max-requests=5000 --vacuum My wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_test.settings') application = get_wsgi_application()