Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django passing multiple ids through URL
For POST/GET (etc) requests I have the following URL for one user: v1/users/userid123 registered as so: router.register(r"v1/users", accounts_views_v1.UserViewSet) What modifications should I make so that I can pass multiple user IDs like: v1/users/?ids=["userid123","userid456"]? It worked without any modification for another model of mine, with the same criteria, but this one keeps giving a 403 error when I try it -
I have problem using Celery, Redis and Django
I have problem using Celery, Redis and Django. I am trying to use them to create a simple task. However, an error occurs shortly after the task has been executed. I will specify below a part of the code to better understand.I thank you for your attention. CELERY_BROKER_URL = 'redis://:password@REDIS:6379/0' CELERY_RESULT_BACKEND = 'redis://REDIS:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'America/Recife' CELERY_BEAT_SCHEDULE = { 'task-send': { 'task': 'app.tasks.task_send_email', 'schedule': crontab(hour=5, minute=44) } } Console Celery [config] app: sistema:0x7fa254a5d6f4 transport: redis://:**@redis:6379/0 results: redis://redis:6379/0 concurrency: 1 (prefork) task events: OFF (enable -E to monitor tasks in this worker) [queues] exchange=celery(direct) key=celery [tasks] app.tasks.task_send_email INFO/MainProcess] Connected to redis://:**@redis:6379/0 INFO/MainProcess] mingle: searching for neighbors INFO/MainProcess] mingle: all alone After execute the task a error occur RuntimeWarning: Exception raised outside body: ResponseError('NOAUTH Authentication required.',): The task is not completed. -
How to fix django inconsistent date fields?
I have a model that has attribute models.DateField(db_index=True) i insert datetime.strptime("2019-07-08", "%Y-%m-%d") into it. Now, when I get() on it I get: datetime.date(2019, 7, 1) as opposed to datetime.datetime(2019, 7, 1, 0, 0) Why is it inconsistent? :( -
Redirect celery task to other queue but don't consume it
I wish to create task which will redirects itself to other queue in case of error. The purpose of this is to store failed task message with all tasks data and for example use CLI to redirect data to proper queue or remove all of them. But the problem is that if I run task on the other queue the tasks is consumed and RabbitMQ doesn't store any data. Is there any way to prevent queue from consuming messages from RabbitMQ? @shared_task(bind=True) def my_task(self, arg): try: ... except MaxRetriesExceededError: my_task.apply_async([arg], queue='failed_queue') my_task.apply_async(['arg'], queue='my_queue')``` -
What do I put for 'ALLOWED_HOSTS' in django settings when deployed using a proxy server?
I got my React/Django website running on an AWS EC2 instance using Nginx and Supervisor. I'm trying to do a proper deployment rather than just put up my development environment. When I set DEBUG to False in Django's settings.py, the supervisor logs give me the error "CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False." However, every combination I've tried so far has given me errors. I know that Nginx is essentially sending every request I get through my IP to localhost on the server (right?) so I figured just having 'localhost' would work but that gives me 404 errors when trying to retrieve the static files. Then I tried using my domain (currently just my public DNS from AWS since I haven't connected the domain yet) and that gives me a 400 (Bad Request) error. Using both also gets me a 404. Then I tried the wildcard ('*') since I figure Nginx is handling the traffic anyway but I STILL get a 404. TL;DR table ALLOWED_HOSTS value Result ----------------------------------------------------- ['localhost'] 404 (Not Found) ----------------------------------------------------- ['http://....amazonaws.com/'] 400 (Bad Request) ----------------------------------------------------- ['localhost', 404 (Not Found) 'http://....amazonaws.com/'] ----------------------------------------------------- ['*'] 404 (Not Found) ----------------------------------------------------- all three 404 (Not Found) ----------------------------------------------------- ['34.xxx.xx.xx'] 400 (Bad … -
Django Rest Framework HTTPResponse Download File
I am trying to process an XML file that is uploaded by the user on the fly and return the processed XML as download to the user. The following django code works as expected and after coversion, the user is prompted with Save Dialog from OS to save the file. def processXML(request): if request.method == "POST": input = request.FILES['upload'] translator = xmlProcessor.Translator() path = default_storage.save('tmp/somename-'+str(int(round(time.time() * 1000)))+'.xml', ContentFile(input.read())) tmp_file = os.path.join(settings.MEDIA_ROOT, path) try: response = HttpResponse(content_type="application/atom+xml") translator.Translate(tmp_file, response) response['Content-Disposition'] = 'attachment; filename=export.xml' return response except RuntimeWarning as e: message = "Error encountered during conversion."+str(e) except: message = "Error encountered during conversion" context ={ 'status':message, } return render(request, 'pages/error.html', context) Now, I want to convert this build the Rest API equivalent using django rest framework. So far, I have been successful in receiving the upload from user via api, do the conversion. However, after the conversion, I want to provide response as a file download so that user will be prompted with Save Dialog of their OS. This is the Rest API code I have come up with. @api_view(["POST"]) def processXMLAPI(request): if request.method == 'POST': input = request.FILES['upload'] translator = xmlProcessor.Translator() path = default_storage.save('tmp/somename-'+str(int(round(time.time() * 1000)))+'.xml', ContentFile(input.read())) tmp_file = os.path.join(settings.MEDIA_ROOT, path) … -
How can i set the initial value of a form to be html or Template Language in Django?
I have this form, where i set the MyField value to be non-editable, so that it can be sent to my database without being edited by the user. I want the default value to be retrieved from my db. For example, if, on that html template, i add the following line: {{value.number}}, on the template i will see 909. Now i want the same to happen with the form, the problem is that my actual code won't render 909, for example, but instead it will render the whole string: {{value.number}}. Is there a way to solve this? class MyForm(forms.ModelForm): MyField = forms.CharField( initial="{{value.number}}", disabled=True, widget=forms.TextInput) -
Django: Counting the number of objects changed in a migration
I have a Django app. I'd like to add a decorator around each of my migrations that will count the number of objects that were changed by my migration. So basically, disregarding migrations right now, I need a way to tell Django: "Starting at this point, please count the number of ORM objects that had any fields modified" and then at the end, get a count of these objects. Is that possible with Django? -
Django - access parameters of the previous request
The problem: I am working on a webapp that has a 'StudentListView' that should have the following features: Display a list of students Have a searchbox above that allows the user to filter / search this list (Submitting 'Peter' should return all students with 'Peter' in their name) An 'export' button should allow the user to export this (possibly filtered!) list to a .csv file I've implemented the code below to allow the user to filter the list, which works as intended. I've also created an export_students function that creates an .csv file of all students in the supplied queryset. This function also works as intended. However, when exporting a filtered list the program does not behave as the user expects. The user will first filter the list by providing search parameters, which will trigger an request and refresh the page. The user than presses the 'export' button, but since he did not re-submit the search parameters (why would he, the list he sees is already filtered) none are provided in the request and thus the csv file contain all students in the database, instead of the filtered selection he expects. Possible solution This problem would be solved if I … -
Dynamically path: Ensure that urlpatterns is a list of path
I have tons of generic pattern like this: urlpatterns = [ path('json/ay/<int:pk>', AyView.as_view(), name='json_ay'), path('json/by/<int:pk>', ByView.as_view(), name='json_by'), ... ] (Of course, the classes are not simply Ay or By this is for the sake of clarity), I'm trying to convert them into a generic function like this: first_cap_re = re.compile('(.)([A-Z][a-z]+)') all_cap_re = re.compile('([a-z0-9])([A-Z])') def convert(name): s1 = first_cap_re.sub(r'\1_\2', name) return all_cap_re.sub(r'\1_\2', s1).lower() def json_view(view_class): view_name = '_'.join(convert(view_class.__name__).split('_')[:-1]) return path(f'json/{view_name}/<int:pk>', view_class.as_view(), name=f'json_{view_name}'), and then call it like this: urlpatterns = [ json_view(AyView), json_view(ByView), ... ] I get this error: ERRORS: ?: (urls.E004) Your URL pattern (<URLPattern 'json/ay/<int:pk>' [name='json_ay']>,) is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. HINT: Try using path() instead of a tuple. I dont know why, any idea? -
How can I solve openid auth connection failed in django and keycloak?
I'm getting this error every time I logged into secured page using django and keycloak : OpenID Connect authentication has failed Error message is: Invalid response invalid_grant. Query content was: Also this error: Exception: this login is not valid in this application ERROR:django.request:Internal Server Error: /openid/callback/login/ this is my settings.py # OIDC auth_uri = "http://localhost:8080/auth/realms/test" client_id = "test" public_uri = "http://localhost:8000" scope = ['openid', 'profile', 'email'] from bossoidc.settings import * configure_oidc(auth_uri, client_id, public_uri, scope) Am logged in I can see this from my keycloak server session. But it doesn't redirect to the page where I want to give it. My keycloak redirect url is okay i guess http://localhost:8080/* I've used these 3 libraies: $ pip install git+https://github.com/jhuapl-boss/django-oidc.git $ pip install git+https://github.com/jhuapl-boss/drf-oidc-auth.git $ pip install git+https://github.com/jhuapl-boss/boss-oidc.git -
Django admin: detect which inline fields have been changed
I have two models named A and B: class A(models.Model): name = models.CharField(max_length=250) description = models.TextField() class B(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) title = models.CharField(max_length=250) deadline = models.DateTimeField('Deadline', null=True) and in the admin.py class BInline(admin.TabularInline): model = B extra = 0 fields = ('project', 'title', 'deadline') @admin.register(LunchRule) class A(admin.ModelAdmin): list_display = ('name', 'description') inlines = (BInline, ) def save_model(self, request, obj, form, change): """Here I can access to the fields that have been changed""" print('changed_data', form.changed_data) def save_related(self, request, form, formsets, change): """here I need to access to the fields of Model B""" I have tried to use for form_set in formsets: if form_set.has_changed(): print('Form_set',form_set) It shows new changed values but not shows the fields that has been changed I need to check the value of filed if it has been changed. For example, if project's deadline has been changed I need to validate if the time has passed etc Is it possible? -
Wagtail admin: Linking to tabbed section via language formatted id
I want to be able to go to a certain tab in the admin interface, but Im unsure how to go about it since Its language specific. I have this in my tabbed interface: edit_handler = TabbedInterface( [ ObjectList(content_panels, heading=_("Content")), ObjectList(form_content_panels, heading=_("Forms")), ObjectList(event_registration_panels, heading=_("Participants")), ObjectList(message_panels, heading=_("Messages")), ObjectList(promote_panels, heading=_("Promote")), ObjectList(TranslatablePage.settings_panels, heading=_("Settings")), ] ) I now want to link directly to the messages tab for example. But the id for this is based on the gettext formatted heading, in swedish: <section id="tab-meddelanden" class=" "> in english: <section id="tab-messages" class=" "> This makes it hard to link correctly. How can I supply a non-language formatted id? -
I am facing an error in django 2.2 i.e NOT NULL constraint failed: home_profile.user_id
i am creating a edit profile form only for authenticated user.the user is authenticated but when completing the edit profile form it gives error i.e "NOT NULL constraint failed: home_profile.user_id" deleting migration and re-migrating if request.method=="POST": firstname = request.POST.get('firstname') middlename = request.POST.get('middlename') lastname = request.POST.get('lastname') bloodGroup = request.POST.get('bloodGroup') professionalStatus = request.POST.get('professionalStatus') image = request.POST.get('image') prof_update = Profile(firstname=firstname, lastname=lastname, middlename=middlename, bloodGroup=bloodGroup, ) prof_update.save() form saved -
How to add specific permission view to certain users based on their field in Django?
So basically i have to make sure Users that are from the same department field to view and create any datas in the database. Not sure how to apply it using field-based user permissions? class Profile(AbstractUser): class Meta: verbose_name_plural = 'Profiles' company = models.CharField(max_length=30, null=True) contact = models.CharField(max_length=20, null=True) branch = models.ForeignKey('generals.Branch', on_delete=models.CASCADE) department = models.ForeignKey('generals.Department', on_delete=models.CASCADE) created_by = models.CharField(max_length=20) modify_by = models.CharField(max_length=20) modify_date = models.DateTimeField(default=datetime.now, blank=True) is_active = models.BooleanField(default=False, null=True, blank=True) is_superuser = models.BooleanField(default=False, null=True, blank=True) is_staff = models.BooleanField(default=False, null=True, blank=True) def __str__(self): return self.username -
bootstrap datepicker not working in django
i am trying to integrate bootstrap datepicker but its not working setting.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main_site', 'crispy_forms', 'bootstrap_datepicker_plus', 'bootstrap4' ] forms.py: from django import forms import datetime from bootstrap_datepicker_plus import DatePickerInput class BookartistForm(forms.Form): name = forms.CharField() email = forms.EmailField(label = 'email', required=False) number = forms.CharField(required=False) artist_name = forms.CharField(required=False) artist_category = forms.ChoiceField(choices = [('singer','Singer'),('dancer','Dancer'),('comedian','Comedian'),('model','Model'),('celebrities','Celebrities'),('photographer','Photographer')]) #Event_Type = forms.ChoiceField( choices = [('question','Question'),('other','Other')]) budget = forms.CharField(required=False) date = forms.DateField(widget=DatePickerInput(format='%m/%d/%Y')) location = forms.CharField(required=False) description = forms.CharField(widget = forms.Textarea, required=False) html template: {% extends 'main_site/base.html' %} {% load static %} {% block content %} {% load crispy_forms_tags %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} <div class="container"> <section> <form method = 'post'> {% csrf_token %} {{ form|crispy }} <button type="submit" class="bg bg-primary">Submit</button> </form> </section> {% endblock content%} also its unable to import on forms.py as i get error showing this: unable to import bootstrap datepicker_plus this is the output i'm getting -
Database multiple data not show in html file - django 2.1
i making a web page to get data from database and show in web page.i used .get() and it only get one data from database. and a tried .all() with many times. but can't show any data in html file. i need to get multiple data from database and show in web page here my code views.py from django.shortcuts import render from django.http import HttpResponse from .models import data # Create your views here. def index(request): return render(request, 'index.html') def about(request): return render(request, 'about.html') def postjob(request): data.objects.all() context = { "title": data.title, "jobType": data.jobType, "des": data.description, "jImg": data.jImg } return render(request, 'jobpost.html', context) models.py from django.db import models # Create your models here. class data(models.Model): title = models.TextField() jobType = models.TextField() description = models.TextField() jImg = models.ImageField(upload_to="media") urls.py from django.contrib import admin from django.urls import path from diligent.views import index, about, postjob from webDiligent import settings from django.contrib.staticfiles.urls import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='index'), path('about/', about, name='about'), path('jobpost/', postjob, name='postjob'), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) jobpost.html <div class="row"> {% for con in context %} <!-- single product --> <div class="col-lg-4 col-md-6"> <div class="single-product"> <img class="img-fluid" src="{{con.jImg.url}}" alt=""> <div class="product-details"> … -
DRF request.data has no attribute _mutable
I'm using Django 2.x and Django REST framework. I'm using django-oauth-toolkit to enable OAuth2 authentication and django-rest-auth for login and django-allauth for user registration. I want to generate access token in the response when a user is successfully registered. For that, I'm using a custom registration view. For that, I have created a function utils like def generate_token(request, user): # Get OAuth application to use application_: Application = Application.objects.filter( client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_PASSWORD ).first() if not application_: raise Exception('No OAuth2 Application is setup') auth_data = { 'username': user.username, 'password': password, 'grant_type': 'password', 'client_id': application_.client_id, 'client_secret': application_.client_secret } if request.data: mutable = request.data._mutable request.data._mutable = True request.data.update(auth_data) request.data._mutable = mutable if request.POST: mutable = request.POST._mutable request.POST._mutable = True request.POST.update(auth_data) request.POST._mutable = mutable return TokenView().create_token_response(request=request) When the endpoint is hit by Postman it works fine and request.data has _mutable attribute. But when it is hit by Angular application, it gives error 'dict' object has no attribute '_mutable' and the error points to mutable = request.data._mutable Why _mutable is missing for some requests? -
How to fix Expecting value: line 1 column 1 (char 0) error
After changing the url of my website from example1.com to example2.com I got the error of JSONDecodeError Expecting value: line 1 column 1 (char 0) Moreover, thinking that may the woocommerce key and secret caused the problem I changed them also, but the problem remains. Here is my code: def create_woocommerce_products_individually(wcapi,name,code,regular_price): data = { "name": name, "sku": code, "regular_price": str(regular_price), } wcapi.post("products", data).json() class ProductCreateView(LoginRequiredMixin, CreateView): model = Product form_class = ProductForm template_name='products/product_create_form.html' def form_valid(self, form): if self.request.method == 'POST': form = ProductForm(self.request.POST) if form.is_valid(): self.object = form.save(commit=False) name=self.object.description code=self.object.code wholesale_status=self.object.wholesale_status regular_price=self.object.retail_price wcapi=get_wcapi_b2b() create_woocommerce_products_individually(wcapi,name,code,regular_price) r=wcapi.get("products?filter[sku]='"+code+"'").json() post_id=r[0]['id'] self.object.pid=post_id self.object.save() else: form = ProductForm() return super(ProductCreateView, self).form_valid(form) My aim is to create a Product both in my db and woocommerce api, that's why I call the create_woocommerce_products_individually function. How can I fix this error and save properly? Here is the Traceback: Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/mixins.py" in dispatch 56. return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/edit.py" in post 217. … -
10 Applications streaming live locations
I am building a mobile application for forest touring users who need to stream their live locations to a real time web system so that they can be tracked for the entire time they are in the forest. Of course consent is to be granted and this has been taken care of. My problem is the design and how to put the pieces together. Below are some things I have figured out. I will use services library to get live location of the use user with the app installed and logged in. Lets say after every one minute. My backed server is based on Django. I am using REST APIs. I will use google maps to show the locations in the live web page. Questions: Should I keep the changing coordinates in the database? How do i live stream the changes in coordinate in the web page? -
Django celery unregistered task | relative imports
I'm trying implement periodic tasks in django app by using celery (v 4.3.0). My tasks.py looks like below: # forepy is the simple package created by me from forepy import Instrument from forepy import oanda_api from celery import shared_task @shared_task def sum_numbers(a, b): return a + b Problem is that celery worker returns error Received unregistered task of type 'fxsignal.tasks.sum_number'. I think that cause of problem is two import statements at the top of tasks.py (forepy imports). When I comment out those two lines my periodic task sum_numbers works correctly. For your reference, structure of forepy package is as below: forepy\ downloaders\ __init.py__ oanda_api.py __init__.py instruments.py utils.py And forepy's init.py: # -*- coding: utf-8 -*- """Top-level package for forepy.""" __author__ = """Elgin Jahangirov""" __email__ = 'cahangirove@gmail.com' __version__ = '0.2.0' from forepy.instrument import Instrument from forepy.downloaders import oanda_api __all__ = ['Instrument', 'oanda_api'] I've read this part of celery documentation and get rid of all . imports in my forepy package, but still problem exists. What can I do further to solve this problem? -
django.db.utils.OperationalError: (1698, "Access denied for user 'root'@'localhost'")
I m new to django I m learning how to connect django to mysql but I m getting error django.db.utils.OperationalError: (1698, "Access denied for user 'root'@'localhost'") my database is mysql user root database PyDjangoSQL2019 password nothing port 3306 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'PyDjangoSQL2019', 'USER': 'root', `enter code here` 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3306' } } please help me what is problem and what I do? thanks -
How to add columns to some row of a table with reportlab?
I've been looking for an alternative for a few days but I can't find it. I paste a fragment of my code in which I generate a table with the questions and answers, most rows will have a single column, but in particular cases I need to show information in more than one column in the same row (it can be in 2, 3, 4, columns etc.) Is there any way to add columns to certain rows? o Specify the number of columns per row? Or another alternative. Of course, thanks for your help def answer_data(self, style): answers = [] style_bodytext = style['BodyText'] for a in self._answers: question = Paragraph(a['question_code'] + " - " + a['question'], style_bodytext) answer_paragraph = Paragraph(self.serializer_answer(a['answers']), style_bodytext) answers.append([ question ]) answers.append([ answer_paragraph ]) try: table_dependent = [] qs = [] aws = [] for d in a['dependent']: q = Paragraph(d['question_code'] + " - " + d['question'], style_bodytext) ans = Paragraph(self.serializer_answer(d['answers']), style_bodytext) qs.append(q) aws.append(ans) table_dependent.append(qs) table_dependent.append(aws) answers = answers + table_dependent except KeyError: pass table = Table(answers, colWidths=18 * cm) table.setStyle([ ("BOX", (0, 0), (-1, -1), 0.25, colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ]) for each in range(len(answers)): bg_color … -
Quickst Gmail api setup with djanogo
I try to send an email with my Django project and I like to use quickstart Gmail API instead of SMTP How can edit my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') -
How to prevent toast message on button click if form having a validation on some text field?
I used something similar to toast message in my html page, when i click on submit. It shows the message. But the problem is i have given some validation to some text field, if validation error occurs still it shows that toast message. How to prevent that? I tried to check the fields whether its null or not if its null, shows a message if not, shows successful and submit the form. <a class="white-button submit" id='test'>SUBMIT</a> $('#test').click(function () { var name=$('#con-name').val(); var email=$('#con-email').val(); var phone=$('#con-phone').val(); var address=$('#con-address').val(); var nation=$('#con-nation').val(); if(name!=""&&email!=""&&phone!=""&&address!=""&&nation!=""){ $(".success").click(function(){ toastr.success('Form submitted.', 'Success Alert', {timeOut: 5000}) }); $('form#feedback').submit(); } else{ $(".warning").click(function(){ toastr.warning('Fill the fields', 'Warning', {timeOut: 5000}) }); } }) What i want is toast message should be displayed only when form is submitted without any validation error.