Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a celery task work in Django?
I am working on a project that requires to create a model entry every time the date has exceeded the booking date. I am using celery for it. Everything seems to run fine but my task does not work. I don't know what is wrong with it. I am attaching codes of my celery task and model. Please help. task.py @task(name="create_payment") def create_payment(): try: booked_client = Booking.objects.get(client__user__username=request.user) len = Payment.objects.filter(username__user_username=request.user) due = Payment.objects.filter(user__user_username=request.user).values_list('due_date')[len - 1] print(due) if datetime.date.now - due >= 0: form = PaymentsForm() form.username = request.user form.save() except: pass celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'qworky.settings') app = Celery('qworky') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.beat_schedule = { 'add-every-5-seconds': { 'task': 'create_payment', 'schedule': 10.0, 'args': (), }, } @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) models class Payment(models.Model): username = models.ForeignKey(UserProfile,on_delete = models.CASCADE, related_name='name') amount = models.IntegerField() date = models.DateField(blank=False, default = date.today) due_date = models.DateField() collected_by = models.ForeignKey(UserProfile,on_delete = None, related_name='collected_by', blank=True, null = True) is_due = models.BooleanField(default = True) def save(self, *args, **kwargs): self.due_date = self.date + monthdelta(1) amt = list(map(int,Booking.objects.filter(client__user__username=self.username).values_list('cabin__price', flat='True'))) self.amount = sum(amt) super(Payment, self).save(*args, **kwargs) celery worker in terminal INFO/ForkPoolWorker-3] Task create_payment[532389a2-31a1-43e8-8155-87c0a6cbc8e3] succeeded in 0.003159977000905201s: None celery beat in terminal Scheduler: Sending due task add-every-5-seconds (create_payment) -
How to mock celery send_task function in django Unit test
I want to write a unit test in Django, for a function which has celery send_task function. So how to write its UT in Django and how to mock celery. def push_to_queue(self, data): """ function to add task in the backend queue Args: Accept data dictionary returns: Nothing """ try: LOG.info( "Pushing %s to queue %s " % (data, settings.SCHEDULER_STATUS_QUEUE_NAME) ) # sqs handler handle = Celery("scheduler_service", broker="sqs://") handle.send_task( settings.BACKEND_TASK, queue=settings.SCHEDULER_STATUS_QUEUE_NAME, kwargs=data, ) LOG.info( "Pushed message successfully to %s queue." % settings.SCHEDULER_STATUS_QUEUE_NAME ) except Exception as err: LOG.error("Exception while pusing meesage to queue %s " % str(err)) -
Django admin css not being applied after loading
I am using nginx to serve my django static files. In the browser I can see that they are loaded, base.css, login.css, responsive.css all got status 200, I can click on them and see their content. The problem is that they don't seem to be applied in the html. The html still looks like it has no css formatting applied to it at all. There are no errors in the nginx logs and no errors in the network tab in chrome. I have tried chrome and firefox Using Django 2.2.4 -
How to save all user clicks and inputs in Django?
This is may be an obvious question to a Django expert, but is there a way that I can save all user input (clicks and text-based). If this is possible, then how do I access it later? Or must I create models for each entry and then save each click by hand in the view with something like to save user behavior, obviously it would be way bigger than this, in the application: #(within a view function) UserInputs.objects.get_or_create(user=request.user, selection1=request.POST.get('selection1'), id=request.POST.get('id')), thumbs_up=request.POST.get('thumbs_up'), thumbs_down=request.POST.get('thumbs_down'), comments=request.POST.get('comments') ) -
How can I set my very own JSON key label in Django REST API framework?
I'm trying to use REST API framework in Django and I noticed that the JSON format for it always takes the particular model's field name as the key. eg: A field called image in my model stores images in the database. When viewed in JSON format, it's seen as : {"image": "apple.png"} I want to change the image to my own personalized label. How can I do this? -
Invalid HTTP_HOST header even after adding it to the allowed host
I have a python/django website running on amazon lightsail instance. I have included my domain name in the allowed_hosts. But sometimes I am getting the error that i need to include my static IP to the allowed_hosts. This error is showing to only some users but I dont know where is the real problem. I don't want to include my static IP to the allowed_host as it is not a best practice. Does anyone know the problem here? -
Data output from Froala Editor is not in the format i wanted - Django
I integrated Froala editor in my django forms to save data into the database. I have noticed that Froala editor save the data with html tags.I have a table on my django web apps which retrieve data from the database and display. The data from the database is displayed with html tags. Is there a way to fix this? User can't be looking at the html tags with the data. Any help would be appreciated. -
How to fix: when I'm trying to follow the link with a name of another anchor the page crashes
I'm setting up a website based on Django. I want to link several pages using the positional link (..../#anchor_name), but when I follow the link the page crashes and I really confused. I have done some googling, but there was nothing that helped This is the anchor with a link that I followed. Normal links (without ../#anchor_name) work just fine. <a href="{% url 'home_page' %}#get_in_touch">CONTACT</a> This is the endpoint anchor. I've also tried to set an id, but unfortunately, it leads to the same consequences. <a name="get_in_touch"> <section class="section"> </section> </a> Eventually, it happens: https://i.ibb.co/ZLjMr07/Screenshot-6-LI.jpg I have also tried different browsers. Thanks in advance -
How to know which user added another user?
How do I know which user added another user? User A registers and is assigned admin status. User A adds User B within the application. How can I save User A in my extended user model so I know who has added who? This is a multi-tenant application. Django/Postgres -
How to return list of dicts in `SomeTable.objects.raw()` in Django?
I have code below: SomeTable.objects.raw(custom_query) And I need to get results as list of dicts. Something similar to when SomeTable.objects.filter(some_filter).values_list() which returns a ValuesQuerySet SomeTable.objects.raw returns a RawQuerySet and don't seem to have easy way to extract/convert it to list. Although using cursor is also doable: cursor.execute(custom_query) return [ dict(zip([col[0] for col in cursor.description], row)) for row in cursor.fetchall() ] -
Django's create method for models is not accepting my dictionary
I have been trying to simplify my testing file test_client_api.py for my django model Client in models.py. However, I am running into an error when I try to make a sample_client method that simplifies the creation of this Model for testing purposes. Here is my Repo's full code: https://github.com/StrawHatAaron/duplicagent-api when I change the code in app/clients/tests/test_client_api.py on line 50 to client1 = sample_client(user=self.user, fein="helloword") from client2 = Client.objects.create( user=self.user, fein = 'Yolo dude', business_name = 'Dont know why it wont work', first_name = "Test", last_name = "Name", emails = "test@sacappdev.com", phone = 69696969, address = 'none your damn biz', city = 'nonya', state = 'fu', zip_code = 12345, ) I get an unexpected error: ERROR: test_retrieve_clients (clients.tests.test_client_api.PrivateClientApiTests) Test retrieving a list of recipes ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.DataError: integer out of range The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/clients/tests/test_client_api.py", line 50, in test_retrieve_clients client1 = sample_client(user=self.user, fein="helloword") File "/app/clients/tests/test_client_api.py", line 35, in sample_client return Client.objects.create(user=user, **defaults) File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 413, in create obj.save(force_insert=True, using=self.db) File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 718, … -
Accesing to a print remotely from WEB API
I used Django to develop a WEB API which allows me to register food orders and I want them to be sent directly to my EPSON TM-m30 command printer. This command printer would be connected via ETHERNET to my modem. For printing I use python-escpos module, which works fine when I run my app locally as following: p = printer.Network("192.168...") p.text('Hello world') p.cut I'm hosting my app in Digital ocean with Ubuntu 18.04 VM. As expected, my printer is not discoverable when I run my code from the digital ocean server... so what I supposed to do in order to allow that? Any suggestions would be appreciated. -
How to limit django allowed_hosts to one docker container
In my production environment, I have two docker container one for the web and one for nginx. Is it possible to specify the allowed_hosts in django to only the nginx container? Thank you. I've tried the service name and container name, none worked. -
Unable to get send_mail to send an email message Django
I posted a question earlier where I asked how to get my email to send and was told that it's the provider, so I tried 3 providers and the send_mail and/or EmailMessage function doesn't work with any of them. So, I strongly think it's something related to my set-up. I get a message in the send_email folder, but no email ever sends and no error is logged. Here is my settings.py file: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemails@gmail.com' EMAIL_HOST_PASSWORD = 'pass' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = 'myemail@gmail.com' Might someone else have an idea? -
Change value for paginate_by on the fly
I would like to be able to allow users change the default page size (paginate_by). My current page size is set to 10; I'd like to have buttons for say 25, 50, and all. I am running Django 2.2 and Python 3.73 with postgresql 11.4. My views.py creates a queryset and sets up pagination. My prod_list.html template properly displays the data in pages with ten rows per page. Here is what I currently have in my views.py: class ProdViewSet(viewsets.ModelViewSet): queryset = Proddetails.objects.all() serializer_class = ProdSerializer class ProdListView(ListView): model = Proddetails template_name = 'prod_list.html' # added for pagination context_object_name = 'prods' #Default: object_list paginate_by = 10 I want to be able to let my users change the number of rows per page. I'm thinking I need to reset paginate_by based on which button the user clicks, but how can I do that? Thanks-- Al -
Django DetailView and get request
I have a detail view with a drop-down list. The user can choose an item in the drop-down list and the information about that item should appear below it. This requires that the DetailView includes something like this: def get_context_data(self, **kwargs): context = super(InvoiceDetail, self).dispatch(*args, **kwargs) request = self.request if request.GET: try: invoice_selector = request.GET.get('invoice_selector', None) invoice = Invoice.objects.get(id = int(invoice_selector) ) # either a string representing a number or 'add invoice' context_object_model = invoice except ValueError: return HttpResponseRedirect(reverse('accounting:add_invoice')) return context How do I over-write the context_object_model? The above code does not make the change. -
How to include quaggajs script tag in django
I have installed quagga using npm and moved quagga.min.js and quagga.js into the static directory of my app(recordmgnts), so i have recordmgnts/static/recordmgnts/quagga.min.js. I tried using src="{% static 'recordmgnts/quagga.min.js' %}" in my script tag but it is not working. How can i include it in my template? Thank you in advance. -
Django REST framework: Unable to use custom template for login view
Gist: I'm trying to use a custom template for Django REST framework's login view by following the instructions from official documentation, but the template that I have put at <PROJECT_ROOT>/templates/rest_framework/login.html is not used to render the login page. Detail: I'm trying to properly set up Django REST framework's browsable API. In particular, after a successful login, the login view redirects to LOGIN_REDIRECT_URL, which has a default value of '/accounts/profile/' and is not what I need. I figured there are two possible solutions: to assign a value to LOGIN_REDIRECT_URL, or use a custom template for Django REST framework's login page and modify the HTML form to pass 'next': <MY_REDIRECT_URL> as the form data (I've tested this manually and it works). I decided to go with solution #2 because solution #1 is not ideal because that would be setting a global default to change behavior of one specific part of a subsystem. Solution #2 requires using a custom template for the login view, but I'm unable to get it to work by following the official instructions (link above). Things I have tried: I have tried the solutions in the following Stack Overflow questions: Django REST Browsable API Template Change django drf login … -
The view Expéditions.views.changelisteexpédition didn't return an HttpResponse object. It returned None instead
I'm new in django developpemnt , in my view i have some elif conditions that mastring some functions, in execution on the last condition i have this issue : The view Expéditions.views.changelisteexpédition didn't return an HttpResponse object. It returned None instead. def changelisteexpédition(request,id=id): if "Editer" in request.POST: ....... elif "Bloquer" in request.POST : ....... elif "Supprimer" in request.POST: ....... elif "Annuler" in request.POST: ....... elif "Débloquer" in request.POST : ....... elif "Top Départ" in request.POST : trsp = transporteur.objects.all().order_by('id') obj = get_object_or_404(Expédition,id=request.POST.get("choix")) form = TopdépartForm(request.POST) if form.is_valid(): Topdépart.objects.create( Expédition = obj, transporteur = request.POST.get("transporteur"), chauffeur = request.POST.get("chauffeur"), bl = request.POST.get("bl"), plomb = request.POST.get("plomb"), commentaire = request.POST.get("commentaire"), date = request.POST.get("date"), immatriculation = request.POST.get("immatriculation") ) obj.statut = "Expédié" obj.transporteur = request.POST.get("transporteur") obj.chauffeur = request.POST.get("chauffeur") obj.immatriculation = request.POST.get("immatriculation") obj.save() a = Commande.objects.get(numcommande=obj.numcommande) a.quantitélivrée = obj.quantitélivrée a.statut = "Expédié" a.save() j = Ligneexpédition.objects.filter(numcommande=obj.numcommande) for i in j : c = Articles.objects.get(sku=i.sku) c.stockexpedié = c.stockexpedié + i.quantitélivrée c.save() return HttpResponseRedirect("asnintransit") else : form = TopdépartForm() context = { 'form':form,`enter code here` 'obj':obj, 'trsp':trsp } return render(request,'topdépart.html',context) I need some help. Thanks. -
How to Create and Save File in Django Model
I have a view which generates a .docx file for whichever 'reference #' the user selects - I would like for the file to save to my Orders model whenever the doc is generated. models.py #model where I'd like to save the doc each time it gets generated class Orders(models.Model): reference = models.CharField(max_length=50, unique=True, error_messages={'unique':"This reference id has already been used"}) ultimate_consignee = models.ForeignKey(Customers, blank=True) ship_to = models.CharField(max_length=500, blank=True) vessel = models.CharField(max_length=100, blank=True) ... order_file = #not sure what data type to use here views.py #view generating the .docx def docjawn(request): if request.method == 'POST': reference = request.POST.get('Reference_IDs') referenceid = reference manifest = Manifests.objects.all().filter(reference__reference=referenceid) order = Orders.objects.get(reference=reference) doc = DocxTemplate("template.docx") totalCNF = 0 totalFOB = 0 for item in manifest: totalCNF += item.cases * item.CNF totalFOB += item.cases * item.FOB context = { 'ultimate_consignee' : order.ultimate_consignee, 'reference' : order.reference, 'ship_to' : order.ship_to, 'terms' : order.terms, 'date' : "12", 'ship_date' : "7/4/19", 'vessel' : order.vessel, 'POE' : order.POE, 'ETA' : order.ETA, 'booking_no' : order.booking_no, 'manifest' : manifest, 'totalCNF' : totalCNF, 'totalFOB' : totalFOB, } doc.render(context) doc_io = io.BytesIO() # create a file-like object doc.save(doc_io) # save data to file-like object doc_io.seek(0) # go to the beginning of the file-like object response … -
TypeError - string indices must be integers - Django rest framework
I'm retrieving a json response from an api, with this method: class MyView(APIView): def get(self, request): data = urlopen("https://url/api/").read() output = json.loads(data) objects = Model.objects.all() serializer = ModelSerializer(objects, many=True) for object in output: if object['id'] not in [i.id for i in objects]: Model.objects.create(id=object['id'], name=object['field1'], street=object['field2'], email=object['field3'], phone=object['field4']) return Response(serializer.data) Everytime I try to access this, it throws: Traceback (most recent call last): File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/rest_framework/views.py", line 497, in dispatch response = self.handle_exception(exc) File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/rest_framework/views.py", line 457, in handle_exception self.raise_uncaught_exception(exc) File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/rest_framework/views.py", line 468, in raise_uncaught_exception raise exc File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch response = handler(request, *args, **kwargs) File "/home/user/django_projects/myproject/proj/app/views.py", line 37, in get if object['id'] not in [i.id for i in objects]: TypeError: string indices must be integers This is my model: from django.db import models class Model(models.Model): field1 = models.CharField(max_length=255, blank=True, null=True) field2 = models.CharField(max_length=255, blank=True, null=True) field3 = models.EmailField(max_length=254, blank=True, null=True) field4 = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return … -
Django UniqueConstraint on related model property
I have a model that looks like this, and it works ok: def BookModel(TimeStampedModel): user = models.ForeignKey(User, on_delete=models.CASCADE) bookname = models.CharField() class Meta: constraints = [ models.UniqueConstraint(fields=['user ', 'bookname'], name='StackOverflow.Question') ] Each user can only have one BookModel with a specific bookname. However, now I'd like to introduce the concept of LibraryModel class LibraryModel(TimeStampedModel): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=32) def BookModel(TimeStampedModel): library = models.ForeignKey(LibraryModel, on_delete=models.CASCADE) bookname = models.CharField() class Meta: constraints = [ models.UniqueConstraint(fields=['library_user', 'bookname'], name='StackOverflow.Question') ] Behavior should stay the same: the constraint should still be enforced based on the associated user, but the user id now lies within LibraryModel. When I run migrate, it says django.core.exceptions.FieldDoesNotExist: BookModelhas no field named 'library_user'. I've also tried fields=['library__user' and fields=['library.user', to no avail. Is this possible to do? Or should I put the user property in both models, violating some DRY principles? -
403 Forbidden error for Django app on Apache
I've followed this deploy tutorial of Django for Apache, and did everything as in there. When I try to enter the page with server's ip, I get Forbidden You don't have permission to access / on this server. Apache/2.4.29 (Ubuntu) Server at <my-ip> Port 80 Running the app with python manage.py runserver 0.0.0.0:8000 works fine and I can access the app. Via the apache2 logs I got: Current thread 0x00007fc84606fbc0 (most recent call first): [Wed Aug 14 01:11:51.141895 2019] [core:notice] [pid 31839:tid 140498145049536] AH00051: child pid 32108 exit signal Aborted (6), possible coredump in /etc/apache2 $preter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' My config file: ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ernest/[my-project-name]/static <Directory /home/ernest/[my-project-name]/static> Require all granted </Directory> Alias /media /home/ernest/[my-project-name]/datagather/uploaded_files <Directory /home/ernest/[my-project-name]/datagather/uploaded_files> Require all granted </Directory> <Directory /home/ernest/[my-project-name]/[my-project-name]/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/ernest/[my-project-name]/[my-project-name]/wsgi.py WSGIDaemonProcess my_app python-path=/home/ernest/[my-project-name] python-home=/home/[my-project-name]/venv WSGIProcessGroup my_app </VirtualHost> I've done following changes to [my-project-name]/settings.py: DEBUG = False ALLOWED_HOSTS = ['[my-server-ip]', 'localhost'] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' … -
I don't know why my page isn't paginating i don't get any errors pls help :)
The page is suposed to get paginated but it doesn't i don't know what i did wrong if anyone can help me figure it out i will apreciate This is for a comment section on a site and i don't really know how to fix it i've been looking the problem up on the web with no results then came here from django.core.paginator import Paginator def Home_view(request): posts = Post.objects.order_by("-date_posted") all_experiences = Experience.objects.order_by("-id") all_educations = Education.objects.order_by("-id") all_skills = Skill.objects.all() paginator = Paginator(posts, 1) page = request.GET.get('page') post_list = paginator.get_page(page) context = { 'posts': posts, 'all_experiences': all_experiences, 'all_educations': all_educations, 'all_skills': all_skills, } return render(request, 'resume.html', context) Html Page suposed to get paginated {% if is_paginated %} <div class="pagination"> <span class="step-links"> {% if post_list.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ post_list.previous_page_number }}">previous </a> {% endif %} <span class="current"> Page{{post_list.number}}of{{post_list.paginator.num_pages}}. </span> {% if post_list.has_next %} <a href="?page={{ post_list.next_page_number }}">next</a> <a href="?page={{ post_list.paginator.num_pages }}">last&raquo; </a> {% endif %} </span> </div> {% endif %} {% else %} the page is supposed to show 5 posts at once but doesn't and doesn't throw out any errors it just doesn't work -
Sum column data model property
plz i need your help, i cant sum RESTE the return of model property , tried lot of methods but no success. have you any idea about that ? i'm using django framework 2.2 class Reglement(models.Model): """Model definition for Reglement.""" # TODO: Define fields here client = models.ForeignKey(Client, on_delete=models.CASCADE) montant = models.DecimalField(max_digits=10, decimal_places=2) date_reglement = models.DateField(default=timezone.now) date_expiration = models.DateField(default=timezone.now) actif = models.BooleanField(default=True) abonnement = models.ManyToManyField(Abonnement) class Meta: """Meta definition for Reglement.""" verbose_name = 'Reglement' verbose_name_plural = 'Reglements' def __str__(self): """Unicode representation of Reglement.""" return f'{self.client} {self.montant}' @property def get_tarif(self): data = self.abonnement.values_list('tarif',) newData = "" if len(data) > 1: list_data = [] for i in data: for j in i: list_data.append(j) newData = sum(list_data) else: newData = data[0][0] total = newData - self.montant return total