Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to upload CSV for testCase and getting " MultiValueDictKeyError: "'file'""
trying to upload my csv for testing and I keep getting " MultiValueDictKeyError: "'file'" Not sure what I am doing wrong here. def test_import_existing_order(self): data = File(open('TestCSV - OrderTest.csv', 'rb')) upload_file = SimpleUploadedFile('data.dump', data.read(),content_type='multipart/form-data') request = self.seller_client.put( IMPORT_ORDERS_URL, {'file':upload_file,}, format="multipart", content_disposition="attachment; filename=data.dump") def importOrdersToDict(request): import csv line_count = 0 response_data = {"orders":{}, "orderCount":0, "dropOffLocations":0, "totalCases":0, "locations":{}, } csv_file = request.FILES['file'] csv_file.seek(0) csv_reader = csv.DictReader(csv_file) -
Change root url in Django
I'm building a Django application that I'm running on two servers and I would like to be able to change what it considers its root url when it's building urls. For example, if one instance is running on 127.0.0.1 and the other is at 127.0.0.2/abc/, using path('home/', views.home, 'home') on the second instance will point to "127.0.0.2/home" instead of "127.0.0.2/abc/home" I currently have something like this set up in my urls.py file site_patterns = [ path('home/', views.home, 'home')] urlpatterns = [ path('abc/', include(site_patterns)), # root ] Which works fine, but it seems like there should be a more elegant way to do this, like maybe a setting? I just can't seem to figure out how. -
Register celery periodic tasks to see it within django admin
I am trying to code some periodic background tasks within Django and Celery. My tasks are working well, I manage to start those periodically when launching my celery worker with beat scheduler : celery -A parifex worker -B -l info Discovered tasks by the worker As you can see in the above image, my tasks are well discovered. However, the autodiscover on INSTALLED_APPS was not working as expected, so I had to include the path to the app where I want to find tasks in Celery instantiation. Requirements pip freeze |grep "celery\|Django" celery==4.4.1 Django==3.1.2 django-celery==3.3.1 Into the base app where settings stands: celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'parifex.settings') # Define the Celery configuration and include <app>.tasks to discover it app = Celery('parifex', include=['device.tasks']) # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True) @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') settings.py djcelery.setup_loader() CELERYD_HIJACK_ROOT_LOGGER = False # http://celery.readthedocs.org/en/latest/configuration.html#celery-redirect-stdouts-level CELERY_REDIRECT_STDOUTS = True # par défaut CELERY_REDIRECT_STDOUTS_LEVEL = 'DEBUG' CELERY_BROKER_URL = 'redis://:Redi$DB_withCelery@127.0.0.1:6234' # store schedule in the DB: … -
Determining Site Language in Django Model
I am writing a get_absolute_url method for a model in Django. This method is later used in building a sitemap. I am trying to form a url, but there is an issue in that I do not know how to get the language argument at the model stage. That is, the urls in the sitemap end up looking like example.com/news/123, whereas I would like them to look like example.com/en/123. How can this be done? class News(models.Model): title = models.CharField(_("Название"), max_length=255) body = HTMLField(configuration='CKEDITOR_SETTINGS_BODY') image = models.ForeignKey(NewsImageModel, on_delete=models.CASCADE) background_image = FilerFileField(on_delete=models.SET_NULL, null=True, blank=True) created = models.DateTimeField(default=datetime.now) author = models.ForeignKey(User, on_delete=models.CASCADE) view_count = models.PositiveIntegerField(default=0) @property def full_name(self): return '%s %s' % (self.author.last_name, self.author.first_name) @property def short_description(self): return truncatewords(self.body, 10) @property def clear_date(self): return date(self.created, "d.m.y") def __str__(self): return self.title def get_absolute_url(self): return "/news/" + str(self.id) We are using DjangoCMS, so in settings.py, we have something like this: LANGUAGES = ( ('ru', gettext("ru")), ('en', gettext("en")), ) CMS_LANGUAGES = { 'default': { 'public': True, 'hide_untranslated': False, 'redirect_on_fallback': True, }, 1: [ { 'public': True, 'code': 'ru', 'hide_untranslated': False, 'name': gettext("ru"), 'redirect_on_fallback': True, }, { 'public': True, 'code': 'en', 'hide_untranslated': False, 'name': gettext("en"), 'redirect_on_fallback': True, }, ], } -
I keep getting and error Nameerror in my urls
Running Django 3.10 I keep getting NameError: name 'products_api_detail_view' is not defined Urls re_path(r'api/products/(?P\d+)/', products_api_detail_view), views def product_api_detail_view(request, pk, *args, **kwargs): try: obj = Products.objects.get(pk=pk) except Products.DoesNotExist: return JsonResponse({"message": "Not found"}) # return JSON with HTTP status code of 404 return JsonResponse({"id": obj.id}) -
How can I take my docker web application and host it using IIS?
I have created django-react web application that I am currently running on my localhost using docker containers (one for front end and one for backend). I also use a cloud hosted mongodb cluster to store data. I would like to deploy the web app using IIS. I have an IIS server configured in a virtual environment. The web app is also running locally in that same virtual environment. I run the web app locally by using "docker-compose build" and "docker-compose up". How can I deploy the app so that it is running in that IIS server? I have two dockerfiles, one for the frontend and one for the backend. Can I simply change the directories that these dockerfiles COPY into to the C:\inetpub\wwwroot directory? -
How to Add "lang" Attribute to a <pre> Tag in python-markdown?
I'm using django-pygmentes in order to highlight my code-blocks. I'm writing the contents with markdown and convert it to HTML in the view part. Everything is ok. Now, I want to implement the highlighting side. The Pygmentes package needs something like this in order to apply the colors: <pre lang="python">...</pre> But, it's what I get when I write a code block in my post: <pre><code clas="language-python">...</code></pre> Here is my markdown: ```python print('Hey') So, Pygments could not find the element. Is there any way to override any method and apply the changes? -
How can I disable a Django cache?
I have written a small django app and in it I can upload some documents and at another point I can make a reference from a payment to the corresponding document. But my problem is that the list of documents is always outdated. But when I kill my gunicorn and start the webserver again, then the dropdown list with documents loads correctly and also shows the newest file uploads. Do you have an idea why Django behaves like that? Best regards -
how to get setup python app icon on cpanel on bluehost
I want to deploy django app. I tried with apache in manual and Iam failing to do that. I want to deploy through setup python app icon by following this video - https://www.youtube.com/watch?v=Y1jJPVhanzU&t=528s But no such icon is present on my bluehost filemanager. The support chat person said that has to install from my side. Python and apache are installed on whm but how to get that icon -
Gunicorn reflect changed code dynamically
I am developing a django web application where a user can modify the code of certain classes, in the application itself, through UI using ace editor (think of as gitlab/github where you can change code online). But these classes are ran by celery worker at some point. Once code changes are saved, the changes are not picked by django or celery due to gunicorn (running it locally using runserver works fine and changes are picked by both django and celery). Is there a way to make gunicorn reflects the changes of certain directory that contain the classes without reloading the whole application? and if reloading is necessary, is there a way to reload gunicorn's workers one-by-one without having any downtime? the gunicron command: /usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 --chdir=/app The wsgi configuration file: import os import sys from django.core.wsgi import get_wsgi_application app_path = os.path.abspath(os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir)) sys.path.append(os.path.join(app_path, 'an_application')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") application = get_wsgi_application() -
Get choice django with post request
I have found many solutions to get choice in Django field but they work when using a template such as get_foo_display CATEGORY_CHOICES = ( ('M', 'Male'), ('F', 'Female'), But what I have to do if I need to get Male or Female with request.POST in views.py. Currently I am using request.POST['gender'] But this is giving me M or F -
Django Dynamic initial values for current user file upload
I've be struggling the last to days. I want the current user to be able to add a file without selecting himself the user of the file being uploaded. For now, I need to manually select a user from the list to add a file related to him. Big thanks in advance! Hugo Here's models.py from django.db import models from django.contrib.auth.models import User class Client(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class fichier4(models.Model): user = models.ForeignKey(Client, on_delete=models.CASCADE) file = models.FileField() date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.file my view.py code form3 = FichierUpload() initial_data = { 'user' : request.user } if request.method == 'POST': form3 = FichierUpload(request.POST or None, request.FILES, initial=initial_data) if form3.is_valid(): form3.save() return redirect('allfiles') forms.py class FichierUpload(ModelForm): class Meta: model = fichier4 fields = '__all__' -
Good practice to use javascript
I am currently working on a Django project and I have some invoice section. I am using javaScript and jQuery for adding items, price, quantity, discount, taxes, etc. My main concern is that javascript loads on browsers and users can edit JS code and I want to prevent that. I know that it is not possible to completely protect js code but what are some good practices to use javascript. Will obfuscation and minification work? (I know about them but haven't tried yet). I am curious to know what techniques do experienced developers use while working on javascript. And what technique should I use in my case? Thanks in advance. (New web developer looking for some help from experienced seniors :) ) -
Redirecting to folder inside public html from a django app hosted in cpanel
I have a django app hosted in cpanel outsite public html folder running on https://example.com. And also I have a codeigniter site inside the public html folder say name "abc". When I try to access abc using "https://example.com/abc" it shows django page not found error. How can I add a redirect url in urls.py file so that I can redirect to this link. -
Getting keyError while accessing django querySet result
I'm new to django and trying out the following. Have 3 models - model1, model2, model3. Model1: class Model1(models.Model): id = models.CharField(primary_key=True, max_length=-1) Model2: class Model2(models.Model): id = models.CharField(primary_key=True, max_length=-1) Model3: class Model3(models.Model): model1 = models.ForeignKey(Model1) model2 = models.ForeignKey(Model2) Serializer3: class Serializer3(serializers.ModelSerializer) serializer1 = Serializer1(required=True) serializer2 = Serializer2(required=True) Queryset: queryset = Model3.objects.filter(model2__id=param).order_by('someField') result = Serializer3(queryset, many=True) list = [] for item in result.data: list.append(item["id"]) Now coming to the question, list.append(item["id"]) throws KeyError: 'id' as both model1 and model2 have "id" in them. I need to access id of model1. Please help me with the right way to access. -
How to make a toastr notification display on success of jquery ajax In django
So I have an ajax code that takes an Id and sends it to a view and I want display a notification using toastr if the ajax request succeed currently I have an alert() to make an alert box pop up but I want it to be toastr instead -
Create a customer in a Django webshop
I'm working on a Django webshop and want to create a customer as in the title. I've made a login form in HTML and a respond in JSON back to the server. Creating a new user in the database works fine. Then there is the customer part, because if I don't assign a customer for each individual user I get an error: "User has no customer". So I tried using this function to create a new customer in the database and assign it the newly created user. c = Customer(user="Lukas", name="Lukas", email="lukas@lukasalstrup.dk", about="Account has just been created") # Create a new customer and assign the newly created user c.save() # Save the customer in the system When I do that I get an error: Cannot assign "'Lukas'": "Customer.user" must be a "User" instance. although I have a user called Lukas in the system. This will of course be changed later, but I just want to make it work, before I put in a variable. My models.py customer class class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank = True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200, null=True) about = models.CharField(max_length=100, null=True) def __str__(self): return self.name views.py register page: def registerPage(request): if … -
Filter queryset by containing a string
I need to filter all Alert objects whose substring is in the given text. class Alert(..): substring = CharField... class Article(...): text = ... I was trying __in but it doesn't seem to be working. alerts = alerts.filter(Q(substring__isnull=True) | Q(substring='') | Q(substring__in=article.text)) Do you know how to do that? I can't use contains since it's reverse. -
Django TypeError when related model is None
guys. I'm trying to generate a contract in .pdf Not every contract has a 'fiador' (guarantor), so I'm getting this error when I try to generate a contract without one. 'Contrato' (Contract) is a Model. 'Fiador' (guarantor) is another. class Fiador(PersonAttr): contrato = models.ForeignKey('Contrato', on_delete=models.CASCADE, related_name='fiador') I made a function to get the correct article (in portuguese, 'a' is for females and 'o' for males). def artigo_fiador(pk): contrato = get_object_or_404(Contrato, pk=pk) masculino = [] feminino = [] if hasattr(contrato, 'fiador'): [masculino.append(1) for f in contrato.fiador.all() if f.genero == 'Masculino'] [feminino.append(1) for f in contrato.fiador.all() if f.genero == 'Feminino'] if len(contrato.fiador.all()) > 1: if len(masculino) < 1: artigo_fiador = 'as' genero_fiador = 'as' return artigo_fiador, genero_fiador else: artigo_fiador = 'os' genero_fiador = 'es' return artigo_fiador, genero_fiador else: for fiador in contrato.fiador.all(): if fiador.genero == 'Feminino': artigo_fiador = 'a' genero_fiador = 'a' return artigo_fiador, genero_fiador else: artigo_fiador = 'o' genero_fiador = '' return artigo_fiador, genero_fiador And in my views, I'm trying to pass the function like this: from .logic import artigos as at class Contract(view): [...] artigo_fiador, genero_fiador = at.artigo_fiador(pk) data = { 'artigo_fiador': artigo_fiador, 'genero_fiador': genero_fiador, I'm using xhtml2pdf. The error i'm getting is the following: TypeError at /contrato/16/contrato_p cannot unpack … -
Passing values to form when initializing in views django?
forms.py class PermissionForm(forms.Form): def __init__(self, *args, **kwargs): self.rolesChoices = kwargs.pop('rolesChoices') super(PermissionForm, self).__init__(*args, **kwargs) print(self.rolesChoices) self.fields['roles'].queryset = self.rolesChoices print(self.fields['roles'].queryset) roles = forms.ModelChoiceField( queryset=None, widget=forms.CheckboxSelectMultiple, empty_label=None) views.py def privileges(request): rolesChoices = Permission.objects.filter( content_type=ContentType.objects.get_for_model(Group)) for role in rolesChoices: role.name = role.name.replace("group", "role") form = PermissionForm(rolesChoices=rolesChoices) return render(request, 'crm/privileges.html', {'form': form}) I am passing group objects to my form when I am initializing it in views.But I am done a small change, I replaced group with role.So the problem is role get changed with group automatically.I don't know why it's happenging. For example self.roleChoices contains Can add role When I assign self.roleChoices to self.fields['roles'].queryset it changes to Can add group -
How can I make database Mysql accepts numbers in this format (445.795.2 | 301.653.23)
When I try to save my data in database , django shows me an error and I realized that it's about this number format. could not convert string to float: '445.795.2' Even if I set the number in this way... float(445.795.2) -
How do we customise the password fields not matching in Django?
I wanted to know how do we customize the error message that shows up when we enter 2 different passwords in the password1 and password2 fields from the built-in UserCreationForm in Django. I have tried this def __init__(self,*args, **kwargs): super(CreateUserForm,self).__init__(*args, **kwargs) self.fields['password2'].error_messages.update({ 'unique': 'Type smtn here!' }) Am I doing something wrong in this process? In my template, this is the code for the error message. <span id="error">{{form.errors}}</span> Please tell me if there is another way to do this. I am using model forms. class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2'] def __init__(self,*args, **kwargs): super(CreateUserForm,self).__init__(*args, **kwargs) self.fields['password2'].error_messages.update({ 'unique': 'Type smtn here!' }) -
I can't get authenticatewith my api using django
I am trying to make curl requests to my api server that I have secured by this: I then use the ubuntu app for windows the following way: curl http://127.0.0.1:8000/orbitalelements/ -X POST -H 'Authorization: Token 5894b35af2dde31c2d271a9348901312d3cbe348' -H 'Content-Type:application/json' -d '{"Object":"bs", "Epoch": "49400", "TP":"1", "e":"1 ", "I":"1", "w":"1", "Node":"1", "q":"1", "QL":"1", "P":"1", "MOID":"1", "ref":"bs", "object_name":"bs"}' The token I use here is in the database: However I can't get it to accept the token: Does anyone know why this isn't working? -
How to redirect to another url after sending a POST request to admin:auth_user_password_change in Django?
I'm using the built in django admin site for the application's admin site in a sense that POST requests are built identically to its equivalent admin site, and sent to the same urls. So it's like the application admin site is just a wrapper for the admin site. My problem is, I don't know how to redirect back to url where it was originally posted. Currently it redirects to the Change User admin page. I'd like it to redirect back to the page. Here's my change-password-template.html: <div class="form-group col-sm-12" id="form-item-entry"> <form action="{% url 'admin:auth_user_password_change' user.pk %}" method="post" id="change-password-form" class="text-center border border-light p-5"> {% csrf_token %} # ... here goes the password fields <input type="submit" value="Change password" class="user-form-button"> </div> <input type="hidden" name="next" value="{% url 'change_password' id=user.pk%}"> # my attempt at trying to redirect back to the original webpage </div> </form> </div> So, it does correctly post to admin/auth/user/{{user.pk}}/password/ but instead of redirecting back to the that page it instead redirects to: admin/auth/user/{{user.pk}}/change/. How can I make it do so? -
Why should you not use the MEDIA_ROOT and MEDIA_URL convention in the production level of Django static files?
I'm trying to find the answer for the name of the question that I posted, but I couldn't seem to find the answer. I've been looking at several tutorials in Django and they keep on telling me that you should not use the MEDIA_URL and MEDIA_ROOT type of convention when you're at the production level of Django. But why is that? Is there a specific reason for it?