Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django sign up first name not valid
I'm 100% sure this thing worked before but now every time I try to sign up Django says "First name not valid.". This happens during the form.is_valid() check, everything about the sign up view is Django default so I did not implement anything on my own. The only constraint on first_name in the DB is that it must not be NULL or greater than 150 characters. This is the function in myapp.views: def register(request): if request.user.is_authenticated: return redirect('/') if request.method != 'POST': form = RegisterForm() else: form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('login') This is the form: -
I would like to embed a pdf, which i get from a api, in an iframe
The pdf is created in the backend of my React/Django application and i would like to display it in the frontend. Is there a way to prevent this error? Can i allow the application to open stuff from diffrent sources? Here's the code for the frontend: const PDFViewer = () => { return ( <div> <Navbar /> <Login /> <div id="PDF"> <iframe src="/api/pdf"/> </div> </div> ); } -
Is it possible to reorder django fields with rest api (getting the new order with requests)?
I have a Django model like this (hypothetical): class Person(models.Model): name = models.CharField() last_name = models.CharField() age = models.IntegerField() I access this with an API call so I get the json {name: "John", last_name: "Doe", age: 20} and show this as an ordered list like this John Doe 20 I want to reorder this list by dragging the elements (that's easy with this) but once saved and reloaded the data returns to original order because the order isn't saved. Is there a way to achieve this? The best I can think of is getting a new field fields_order that keeps the fields names with the specified order but I think that should be a better approach. -
How to fix TypeError('Object of type ExternalUnifiedEvent is not JSON serializable)?
I am retrieving a list of objects from an external API that I need to send as the payload to a webhook using post request in python. The structure of the data returned from get_data() looks like this [{"eventId": 1, "eventType": "test", "properties": { "property1": "value1", "property2": "value2", "property3": "value3", }}, {"eventId": 2, "eventType": "test", "properties": { "property1": "value1", "property2": "value2", "property3": "value3", }}, {"eventId": 3, "eventType": "test", "properties": { "property1": "value1", "property2": "value2", "property3": "value3", }}] headers = {"Content-Type": "application/json",} payload = get_data() response = requests.post(webhook_url, headers=headers, data=json.dumps(payload)) it raises a TypeError('Object of type ExternalUnifiedEvent is not JSON serializable); if i remove the json.dumps() and just pass in the payload as the data, I'm getting TypeError('cannot unpack non-iterable ExternalUnifiedEvent object') -
SQLAlchemy Postgresql database django
I am new to Django and have a question in regards to whether or not I have to re-enter data or can use existing data from a postgres database and apologize if this has been asked before. I have a Postgres database in which I created with SQLAlchemy ORM. I use this database for data analysis and want to create a web app for the data presentation. I know that Django has its own modeling system and ORM, do I have to recreate the database from scratch since I created this with SQLAlchemy's ORM? Thank you in advance. -
django-redis persisting json data
I have a small django site which controls an anstronomy dome and house automation. On start up the project loads 3 json files: relays, conditions and homeautomation. To avoid constant reading and writing to the Pi4's ssd I load the json files into REDIS (on start up in apps, see below). I already have REDIS running in a docker as the project uses celery. My problem is that within a few minutes of loading the json into REDIS it clears the data out of cache. I load the json file in the form of a dictionary (dict) in apps cache.set("REDIS_ashtreeautomation_dict", dict, timeout=None) and set CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://redis:6379", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "SERIALIZER": "django_redis.serializers.json.JSONSerializer", "TIMEOUT": None } } } I don't need the data to persist if the dockers go down and I don't need db functions. Caching these files is ideal but I need them to 'stay alive' for the lifetime of the server. Thank you. -
using serializer methodfield to access FK informations
I use DRF writable nested serializer to create multiple object at once : class NestedDocumentLocationSerializer(WritableNestedModelSerializer): # organisme_name = serializers.SerializerMethodField(source='organisme.nom') nda = DocumentSerializer(allow_null=True, required=False) kbis = DocumentSerializer(allow_null=True, required=False) qualiopi = DocumentSerializer(allow_null=True, required=False) rib = DocumentSerializer(allow_null=True, required=False) contrat = DocumentSerializer(allow_null=True, required=False) class Meta: model = DocumentLocation fields = ['location', 'nda', 'kbis', 'qualiopi', 'rib', 'contrat'] # extra_kwargs = { # 'organisme_name': {'read_only': True} # } # def get_organisme_name(self, obj): # return obj.location.organisme.nom The creation part works perfectly But when it comes to my Location, only the ID is showing : { "location": 2, "nda": { "id": 136, "nom": "ça fonctionne ?", "description": "ça fonctionne ?", "chemin": "ça fonctionne ?", "stockage_interne": false }, "kbis": { "id": 137, "nom": "ça fonctionne ?", "description": "ça fonctionne ?", "chemin": "ça fonctionne ?", "stockage_interne": false }, "qualiopi": { "id": 138, "nom": "ça fonctionne ?", "description": "ça fonctionne ?", "chemin": "ça fonctionne ?", "stockage_interne": false }, "rib": { "id": 139, "nom": "ça fonctionne ?", "description": "ça fonctionne ?", "chemin": "ça fonctionne ?", "stockage_interne": false }, "contrat": { "id": 140, "nom": "ça fonctionne ?", "description": "ça fonctionne ?", "chemin": "ça fonctionne ?", "stockage_interne": false } } So i wanted to use SerializerMethodfield to get the informations i want, my organisme … -
POST request forbidden
I am using django-rest-framework. I have a few APIs which I use to GET data. When I am testing a new API to post information, I am getting a 403 forbidden while making the request as vanilla xhr object, as well as using jQuery. The same API is working properly from Postman and django-rest-framework API interface as well. What can be the reason for this? -
Delete and edit comment django
i been trying multiple ways to add a edit/delete function to my django comment section but cant seem to figure it out anyone can help me how to code this or give me some tips? I been trying for some time and searching alot but cant figure it out. Been looking at documentation and other stackoverflow posts and youtube videos but cant figure it out. product_detail.html {% extends "base.html" %} {% load static %} {% block page_header %} <div class="container header-container"> <div class="row"> <div class="col"></div> </div> </div> {% endblock %} {% block content %} <div class="overlay"></div> <div class="container-fluid"> <div class="row"> <div class="col-12 col-md-6 col-lg-4 offset-lg-2"> <div class="image-container my-5"> {% if product.image %} <a href="{{ product.image.url }}" target="_blank"> <img class="card-img-top img-fluid" src="{{ product.image.url }}" alt="{{ product.name }}"> </a> {% else %} <a href=""> <img class="card-img-top img-fluid" src="{{ MEDIA_URL }}noimage.png" alt="{{ product.name }}"> </a> {% endif %} </div> </div> <div class="col-12 col-md-6 col-lg-4"> <div class="product-details-container mb-5 mt-md-5"> <p class="mb-0">{{ product.name }}</p> <p class="lead mb-0 text-left font-weight-bold">${{ product.price }}</p> {% if product.category %} <p class="small mt-1 mb-0"> <a class="text-muted" href="{% url 'products' %}?category={{ product.category.name }}"> <i class="fas fa-tag mr-1"></i>{{ product.category.friendly_name }} </a> </p> {% endif %} {% if product.get_rating > 0 %} <small … -
getting DisallowedHost at / error on python anywhere
I am trying to deply my blog application to python anywhere. I added 'codewizblog.pythonanywhere.com' to ALLOWED_HOSTS in my settings file but I keep getting the disallowed host error. Any help would be much appreciated. -
Google OAuth2.0 error while authenticating, while being deployed on heroku
I have created an application which accesses sheets api using django. I am successfully able to authenticate using OAuth2.0, locally. But when I deployed my django code onto heroku, i am unable to authenticate. I am getting this can’t establish a connection to the server at localhost:8080. -
How to create an endpoint (GET) with disabled authentication where I just want to visualize the data in map?
May be an basic question about a creation of a new endpoint in DRF. I'm newbie in DRF and got stuck in a creation of an new endpoint that unauthenticated users could just GET the data, visualize. My django project is organized in three apps: core, user, and markers. The "user" app performing POST, GET, PUT, PATCH, and POST. The app "markers" enable the user to create (POST) geolocations and other information associated to the coordinates (name, coordinates, images...). My challenge now is to create a new endpoint where anonymous user/unauthenticated could visualize the data (in a map), created by the users data. I've created the map, inside markers folder and didn't have success in data visualization because of the authentication. Any clue or example how to enable the visualization? Thanks github repo [https://github.com/silveiratcl/sun_coral_report_app][1] user model models.py: class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new User""" if not email: raise ValueError('User must have an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """Creates and saves a new super user""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user marker model models.py: class Marker(models.Model): """A marker object.""" … -
django model date form validation
hello I am a newbie django user and I created a model form I am using 2 fields one is a DateField and another is a TimeField since separating them instead of using DateTimeField seemed better for my particular model, and I want to make sure that the user can't select a date in the past and a they can only select a time between 10am-11pm, to be more specific this is a restaurant reservation model, I found similar questions when I was looking for a solution on google but I couldn't understand them and apply them to my project, my model - https://gyazo.com/7947589283f52925d85608957cc6a7e4 my view - https://gyazo.com/1b0f6cd1b8af52960c7f197476bdd5b3 my form.py - https://gyazo.com/78e8617e1a6332fc53b91900aa46e017 as I said I found similar questions, on stackoverflow and links to django documentation but I couldn't apply them to my project, so any help would be appreciated -
Struggling with reoccuring checklist functionality (Django)
Here's my current setup, simplified class projects(models.Model): fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE) title = models.CharField(max_length=150) class projects_checklistItems(models.Model): fk_project = models.ForeignKey(projects, on_delete=models.CASCADE) b_task1 = models.BooleanField(defaut=False) b_task2 = models.BooleanField(defaut=False) b_task3 = models.BooleanField(defaut=False) The problem is, I want users to be able to add their own checklist items to each project, as they will have their own dependencies and conditions. As a result, I could do this instead: class projects(models.Model): fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE) title = models.CharField(max_length=150) fkj_checklistItems = models.ManyToManyField(checklistItems, through="j_projects_checklistItems") class checklistItems(models.Model): name = models.CharField(max_length=150) class j_projects_checklistItems(models.Model): fk_project = models.ForeignKey(projects, on_delete=models.CASCADE) fk_checklistItem = models.CharField(checklistItems, on_delete=models.CASCADE) b_completed = models.BooleanField(default=False) However I want there to be a default / starting selection of checklist items (i.e. tasks) that are shared for each project. So once a project is created, it is automatically assigned a collection of 20, 30, maybe 50 checklist items" From there, the user can deselect those that are irrelevant and add new ones. Perhaps by ammending the junction model as such: class j_projects_checklistItems(models.Model): fk_project = models.ForeignKey(projects, on_delete=models.CASCADE) fk_checklistItem = models.CharField(checklistItems, on_delete=models.CASCADE) b_completed = models.BooleanField(default=False) * b_active = models.BooleanField(default=True) But I'm unsure how to set these default items that all projects should share. -
Mypy library and Django exclude app directories
I have several apps in my Django project, but I wanted to exclude directories or apps, how can this be done. Below is my mypy.ini file, but it doesn't work : [mypy] ignore_missing_imports = True exclude = customers As you can see above customers is one of my django apps (directory), what could be the best solution here? -
Condition on avg in a queryset in django
I have two models class A(models.Model): field1 = models.CharField(max_length=100) class B(models.Model): a_field = models.FoereignKey(A,on_delet=models.SET_NULL,related_name='bs') datetimefield = models.DateTimeField(auto_now_add=True) amountfield = models.FloatField() I want to count the number of elements of A per month where Avg(amountfield)=0 Here's how I did it but it doesn't work: B.objects.values('datetimefield__month').annotate(Count('a_field',filter=Q(amountfield__avg=0))) How can I solve this problem? Thanks in advance. -
return the values only if it exists in python
I want to return the values only if the particular row exist but I couldn't able to achieve it.Here, what I tried def CurrentRunning(UserId): cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivity] @UserId=%s', (UserId,)) result_set = cursor.fetchall() data= [] data.append({ 'TaskId':row[0], 'Value1':row[1], 'Value2' :row[2], 'SelectedTeam':0 if row[3] is exists else row[3], 'Level1':'0' if row[4] is exists else row[4], 'Level2':'0' if row[5] is exists else row[5], 'Level3':'0' if row[6] is exists else row[6], 'Level4':'0' if row[7] is exists else row[7], 'TotalVolume':'0' if row[8] is exists else row[8], 'ReturnDate':'0' if row[9] is exists else row[9], }) print('Activity') return Response(data) -
DRF Nested serializer, creating object and select instance from a model on the same request
Here is my problem : i'm using the lib drf-writable-nested to create multiple object on the same request. This part is working perfectly: class DocumentLocationSerializer(WritableNestedModelSerializer): nda = DocumentSerializer(allow_null=True, required=False) kbis = DocumentSerializer(allow_null=True, required=False) qualiopi = DocumentSerializer(allow_null=True, required=False) rib = DocumentSerializer(allow_null=True, required=False) contrat = DocumentSerializer(allow_null=True, required=False) class Meta: model = DocumentLocation fields = '__all__' But with the same Serialier i would like to have the choice to select instance from another model created before, So i can create my documents and select the instance from a model. I tried to add this : location = LocationSerializer(allow_null=True, required=False, read_only=True) so i can select my location but with the readonly option set to True i can't even choose a location, and if i set it to False, i have to create a new location object. Thanks and sorry for my english. -
Passing data from bootstrap modal form to main form
I'm having a problem that I don't really know how to execute, I have this two forms one is on my parent page and shows the sales history of products and then have a form to input the quantity of products for the next months. Main page table Then I have a modal that follows the model of the main page but instead of individual products it tracks the quantity of products by product type. I want to pass the data that is in the modal form to the form fields in the parent page table input fields. Modal table (Note that both include roughtly the same fields product/product type name, quantities from past months up to last, then already paid this month, sold but not paid this month, avg from last 3 and 6 months, sum of paid+not paid this month, form of expeted quantities from this month until this month+6) But how do I do this? The in my context I have the list of products that I use to generate my parent page table with the form and the product type list that I use to generate the modal table. In the product list they have data … -
In django Downloaded xls file is not opening and showing error
This is my code for xls file download. File is downloaded properly, but not opening as you can see in below image. Code for download file is here. views.py def downloadfile(request, filename=''): if filename != '': BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'SampleExcel.xls' filepath = BASE_DIR + "\SampleExcel\SampleExcel.xls" path = open(filepath, encoding='cp437') mime_type, _ = mimetypes.guess_type(filepath) response = HttpResponse(path, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response else: return HttpResponseRedirect("adduser", {}) Please help me as I am new to django and python. -
How can I set 'or' in two django model fields
Suppose I have a django model of an Image: from django.db import models class Image(models.Model): ... image = models.ImageField(upload_to='some_place') image_url = models.URLField() ... and I want that a user can upload either image or its url so I can not set both field null=True because I want atleast one of them to show in template. How can I do this? -
Reverse accessor clasher with Django
First of all, this is not duplicate question. I saw solution for such question, but it did not work for me. Please assist. I have such model in app: class Company(models.Model): owner = models.ForeignKey(User, verbose_name="User", on_delete=models.CASCADE, default=None, null=True, blank=True) name = models.CharField(max_length=128, blank=True, null=True, default=None) created = models.DateTimeField(auto_now_add=True, auto_now=False, null=True, blank=True) updated = models.DateTimeField(auto_now_add=False, auto_now=True, null=True, blank=True) def create_folder(**kwargs): instance = kwargs.get('instance') print(instance.id) os.mkdir(f"media/company_{instance.id}") def delete_folder(**kwargs): instance = kwargs.get('instance') print(instance.id) full_patch_folder = f"media/company_{instance.id}" if os.path.isdir(full_patch_folder): shutil.rmtree(full_patch_folder) post_save.connect(create_folder, sender=Company) post_delete.connect(delete_folder, sender=Company) class Folder(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=128, blank=True, null=True, default=None) unique_folder_name = models.CharField(max_length=128, blank=True, null=True, default=None) full_path = models.CharField(max_length=256, blank=True, null=True, default=None) parent_folder = models.IntegerField(verbose_name="Parent Folder", blank=True, null=True, default=0) company = models.ForeignKey(Company, verbose_name="Company", on_delete=models.CASCADE, default=None) share = models.BooleanField(verbose_name="Share folder", null=True, default=False) created = models.DateTimeField(auto_now_add=True, auto_now=False, null=True, blank=True) updated = models.DateTimeField(auto_now_add=False, auto_now=True, null=True, blank=True) def __str__(self): return "(id.%s) - %s - %s - %s - %s" % (self.id, self.name, self.unique_folder_name, self.share, self.company) and I get below error: apps.Company.owner: (fields.E304) Reverse accessor for 'Company.owner' clashes with reverse accessor for 'Company.owner'. HINT: Add or change a related_name argument to the definition for 'Company.owner' or 'Company.owner'. main.Company.owner: (fields.E304) Reverse accessor for 'Company.owner' clashes with reverse accessor for 'Company.owner'. HINT: Add or change a … -
FormatException: SyntaxError: Unexpected token < in JSON at position 1 in Flutter
I have a project, backend with Django and frontend with Flutter framework. The project was working fine until I changed the proxy in my Nginx from HTTP to HTTPS. Still working in most cases without any Problem. just in some cases, where I have no Data in my Data Table, I want/have to return an empty list from the backend, I got an error: GET https://servername/project-name/api/commitments/?email=emailaddress%40companyname.de&jahr=2022&kunde=adac-ev 500 FormatException: SyntaxError: Unexpected token < in JSON at position 1 code in flutter: var uri = (APIPROTOCOL == 'http://') ? Uri.http(APIHOST, '/api/commitments/', uriQuery) : Uri.https(APIHOST, '$APIHOST_PREFIX/api/commitments/', uriQuery); try { final response = await http.get( uri, headers: {"Authorization": "Bearer $authToken"}, ); And this is working on localhost and on a server with HTTP but the problem is only on a sever with HTTPS, any idea? how can debug the code on the server? or how can I change my localhost from http:://localhost:protNumber/ to something like https://myweb/myapp/. Any idea that could help me to debug the code with https? -
Celery 'update_status' function is not working
I am using celery and django-celery-results in my Django application. My celery results are being stored in the backend and this is what celery.py looks like. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shoonya_backend.settings") # Define celery app and settings celery_app = Celery( "shoonya_backend", result_backend="django-db", accept_content=["application/json"], result_serializer="json", task_serializer="json", ) celery_app.config_from_object("django.conf:settings", namespace="CELERY") celery_app.autodiscover_tasks() I am trying to update the state of a task from within the celery function if I get an exception as follows. try: result = resource.import_data(imported_data, raise_errors=True) # If validation checks fail, raise the Exception except Exception as e: self.update_state( state=states.FAILURE, meta={ "exc_type": type(e).__name__, "exc_message": traceback.format_exc().split("\n"), }, ) The following command doesn't result in any change in the TaskResult table even when the exception is raised and the Task is always a success. -
'QuerySet' object has no attribute 'videos_set'
i am trying to get all the videos related to a curriculum, i have tried curriculum.videos.all but it return this error that says 'QuerySet' object has no attribute 'videos', i also tried using curriculum.videos_set.all then it shows the same error but this time with a 'QuerySet' object has no attribute 'videos_set'. what can be the issue with this problem? models.py class Course(models.Model): course_title = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(unique=True) course_thumbnail = models.ImageField(upload_to=user_directory_path, blank=True) class Curriculum(models.Model): course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE, related_name="curriculum") title = models.CharField(max_length = 100 , null = False) slug = models.SlugField(unique=True) def __str__(self): return f'{self.course.course_title} - {self.title}' class Video(models.Model): title = models.CharField(max_length = 100 , null = False) curriculum = models.ForeignKey(Curriculum , null = False , on_delete=models.CASCADE, related_name="videos") serial_number = models.IntegerField(null=False) video_id = models.CharField(max_length = 100 , null = False) def __str__(self): return self.title Now this is the view that i have written for it View.py # @login_required def course_details(request, course_slug): if request.user.is_authenticated: user = request.user course = Course.objects.get(slug=course_slug) curriculum = Curriculum.objects.filter(course=course) serial_number = request.GET.get('lecture') videos = curriculum.videos_set.all().order_by("serial_number") ...