Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pop None from serializer.data in python?
When i looping through serializer.data is shows None inside that. I want to pop None from that. If I have: serializer.data = OrderedDict([('customer', OrderedDict([('name', 'Sachin'), ('email', 'abc@gmail.com'), ('created_at','2021-03-12T15:04:25.695147+05:30'), ('updated_at','2021-03-12T15:04:25.695147+05:30'), ('user', 9)]))]) None OrderedDict([('customer', OrderedDict([('name', 'Sachin'), ('email', 'abc@gmail.com'), ('created_at', '2021-03-12T15:04:25.695147+05:30'), ('updated_at', '2021-03-12T15:04:25.695147+05:30'), ('user', 9)]))]) -
I can't find the GitHub API for extract the code of a repository .{please help}
I am working with GitHub API. But I don't find any API that will help me to see and extract the different version of code. Please help me. I use these two API for show the repository and search users. "user_repositories_url": "https://api.github.com/users/{user}/repos{?type,page,per_page,sort}", "user_search_url": "https://api.github.com/search/users?q={query}{&page,per_page,sort,order}" Please help me to find the GitHub API. -
CustomUser relation doesn't exist : Django migration error
I'm quite new to Django and ran into a problem while trying to create a custom user. I followed all the steps outlined to create one, but because I initially started out with the default User model I deleted all my migrations and my postgres db to start from scratch (if not, I read it would cause problems). makemigrations works fine, but then when I want to migrate I get the following error: django.db.utils.ProgrammingError: relation "cyclabApp_customuser" does not exist. Applying admin.0001_initial...Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "cyclabApp_customuser" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards … -
Django, makemigrations doesn't detect model changes
I am learning Django and I am using this tutorial: https://www.youtube.com/watch?v=F5mRW0jo-U4&t=912s I created an app called products and I have it in installed_apps. Upon creating a Products class in the models.py file in the products app folder, I created some properties such as price. However, when I tried to use the makemigrations command, no changes detected was reported. Folder Layout and Settings Models.py I checked if there were any issues with the Products class but there doesn't seem to be any as far as I can see, so I am at a loss as to why no changes were detected. -
Can I send requests to the server from HTML in email?
I am trying to implement the following functionality. The server sends an email to a user who doesn't necessarily have an account in the server. In the email, the user is asked to rate a certain model (send a request to the server). Can I make it in such a way that the user can click the button and doesn't get redirected to some other page, but sends the request directly to the server. I am using django. -
Django - crispy form not showing
I'm trying to render this form: class LoadForm(forms.Form): class Meta: model = Load def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Row( 'whouse', 'supplier', 'company', 'product', 'quantity', 'unit_price', 'load_date', ) ) with the following view: def load(request): form = LoadForm() context = { 'form': form, 'title': 'Nuovo Carico', } return render(request, 'warehouse/load.html', context) and the following template: {% extends "masterpage.html" %} {% load static %} {% block headTitle %} <title>{{title}}</title> {% endblock %} {% block contentHead %} {% endblock %} {% block contentBody %} {% load document_tags %} {% load custom_tags %} {% load crispy_forms_tags %} <FORM method="POST" autocomplete="off"> {{ form.media }} {% csrf_token %} <div class="alert alert-info"> {{ title }} </div> {% crispy form %} <input type="submit" class="btn btn-primary margin-left" value="CARICA"> </FORM> {% endblock %} For some strange reason the form will not show up, I just see the title and the input button. I've tried the very simple form.as_p with no crispy, but still nothing... By looking at the sourse code on the browser I see there is a div with class 'form-row' but not form in it... looks strange. Any help? thank you very much. Carlo -
Call Postgres functions From Django
I am working on a Django Project with a Postgres SQL Database. I have written a function that runs perfectly on Postgres 10. CREATE FUNCTION sample_insert(_sno integer, _siid integer, _sd date, _ed date, _sid integer, _status boolean) RETURNS void AS $BODY$ BEGIN INSERT INTO sample (sno, siid, sd, ed, sid, status) VALUES (_sno, _siid, _sd, _ed, _sid, _status); END; $BODY$ LANGUAGE 'plpgsql' COST 100; -
Creating room link with models
I've been developing a sports team application with Django and Channels where the room name (included in the link) corresponds to the 'team code' (Primary key). The users are connected to the teams via a foreign key and I'm trying to find a way to redirect users to their team's chat room once they log in/register. Models.py: class Team(models.Model): Name = models.CharField(max_length=60) code = models.CharField(max_length=6, blank=True, primary_key=True) def __str__(self): return self.Name def save(self, *args, **kwargs): # Saves the generated Team Code to the database if self.code == "": code = generate_code() self.code = code super().save(*args, **kwargs) class User(AbstractBaseUser, PermissionsMixin): USER_CHOICES = [ ('CO', 'Coach'), ('PL', 'Parent'), ('PA', 'Player'), ] User_ID = models.UUIDField(default=uuid.uuid4, primary_key=True) email = models.EmailField(verbose_name='email', max_length=60, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) is_active = models.BooleanField(default=True) ## Everything within these comment tags is_admin = models.BooleanField(default=False) ## define the permissions is_staff = models.BooleanField(default=False) ## that the user will have unless is_superuser = models.BooleanField(default=False) ## changed by the superuser/admin. is_coach = models.BooleanField(default=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) # Ensures that the user isn't deleted when a team is deleted user_type = models.CharField(choices=USER_CHOICES, default='CO', max_length=20) # Useful for when the app wants to identify who has certain … -
Django 3.2 exception: django.core.exceptions.ImproperlyConfigured
I'm upgrading to django 3.2 but as per it's release notes, it says: The SECRET_KEY setting is now checked for a valid value upon first access, rather than when settings are first loaded. This enables running management commands that do not rely on the SECRET_KEY without needing to provide a value. As a consequence of this, calling configure() without providing a valid SECRET_KEY, and then going on to access settings.SECRET_KEY will now raise an ImproperlyConfigured exception. I'm pretty certain that error is because of such. Can someone help me to solve this? How can i check if my secret key is valid or not and also generate new if needed? -
python-django load model OSError
model = load_model('./saved_model.h5') "OSError: SavedModel file does not exist at: ./saved_model.h5{saved_model.pbtxt|saved_model.pb}" The model is well called in python, not in django, but not in django. The model is in the same folder as the code. What is the problem? (For your information, I already installed h5py..!) -
Can I replace django admin panel login code by Amazon Cognito?
I want to replace admin or superuser login by cognito credentials. Is it possible to do that? -
Input Search in django admin filter
Is it possible to create input search in django admin filter without custom template? Something like this, but without custom template? Example of search field -
django uwsgi logto function not work in docker
dockerizing a django app with uwsgi uwsgi [uwsgi] chdir = /app http = :12345 socket=127.0.0.1:8002 wsgi-file=leak/wsgi.py static-map = /static=static processes=4 threads=2 master=True log-master = true threaded-logger = true logto=/var/log/leak.log log-maxsize = 100000 threaded-logger = true pidfile=uwsgi.pid env = DJANGO_SETTINGS_MODULE=leak.settings.development dockerfile FROM python:3.6.8-alpine COPY requirements /app/requirements WORKDIR /app RUN apk update && apk add make \ && apk add --virtual mysqlclient-build gcc python3-dev musl-dev \ && apk add --no-cache mariadb-dev \ && apk add --virtual system-build linux-headers libffi-dev \ && apk add --no-cache jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev \ && apk add --no-cache bash bash-doc bash-completion libxml2-dev libxslt-dev \ && pip install --upgrade pip setuptools wheel \ && pip install -r requirements\ COPY . /app CMD ["sh","run.sh"] run.sh #!/usr/bin/env sh uwsgi --ini uwsgi.ini after docker build && docker run the logpath "/var/log/leak.log" not create and without any errors. but its worked without docker. how can i fix it -
Django Admin Add Object - Customize Dropdown
Moin Moin! I have this model in my models.py: class BranchChief(models.Model): BranchChiefID = models.ForeignKey(User, on_delete=models.CASCADE) BranchID = models.ForeignKey('Branch', db_column='BranchID', on_delete=models.CASCADE) When adding a new object I get a dropdown-field for the field BranchChiefID showing all available usernames. How can I change it to show first_name and last_name to identifiy the user in the dropdown-field? (username is (and must be) a random-number) Thank you for your help! -
Django query fails with _id that is not used or created or referenced to
I have used the queryset before though this is my first attempt to JOIN tables but it's not working so far. I am using django 3.2 and python 3.8.1 my models.py class Mainjoinbook(models.Model): fullsitename = models.TextField(primary_key=True) creationdate = models.DateTimeField() entrytypeid = models.BigIntegerField(blank=True, null=True) title = models.TextField(blank=True, null=True) tickettype = models.TextField(blank=True, null=True) ticket = models.TextField(blank=True, null=True) status = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'mainlogbook' class Sitelocation(models.Model): site_name = models.TextField(primary_key=True) latitude = models.TextField(blank=True, null=True) longitude = models.TextField(blank=True, null=True) sites = models.ForeignKey(Mainjoinbook, on_delete=models.DO_NOTHING) class Meta: managed = False db_table = 'tblsiteaccess' I am trying to get all values from both tables joined in my views.py qrylocations = Sitelocation.objects.select_related('sites').filter(sites__status='OPEN') this results in this error as that column is created by django but doesn't belong to the table. I still can't workout how to resolve this as I have tried many options but always get in some kind of error and I hope someone can help me to see what I'm doing wrong in joining the tables on the primary keys defined psycopg2.errors.UndefinedColumn: column tblsiteaccess.sites_id does not exist the SQL output shown is as below. output from qrylocations.query SELECT "tblsiteaccess"."site_name", "tblsiteaccess"."latitude", "tblsiteaccess"."longitude", "tblsiteaccess"."sites_id", "mainlogbook"."fullsitename", "mainlogbook"."log_id", "mainlogbook"."creationdate", "mainlogbook"."entrytypeid", "mainlogbook"."title", "mainlogbook"."tickettype", "mainlogbook"."ticket", "mainlogbook"."status" … -
a bytes-like object is required, not 'FieldFile'
I am building a BlogApp and I am trying to download the .zip of the blogs. What i am trying to do :- I am trying to download all the texts with images in .zip file BUT when i remove image from the download files then it works fine BUT when i add image in download items then it is keep showing me :- a bytes-like object is required, not 'FieldFile' models.py class Blog(models.Model): name = models.CharField(max_length=25,default='username.txt') image = models.FileField(default='') views.py def download(request): response = HttpResponse(content_type='application/zip') zf = zipfile.ZipFile(response, 'w') zf.writestr(README_NAME, README_CONTENT) scripts = Blog.objects.all() for snippet in scripts: zf.writestr(snippet.name, snippet.image) response['Content-Disposition'] = f'attachment; filename={ZIPFILE_NAME}' return response When i remove snippet.image then it download prefectly but after adding it it is showing that error. I have no idea what to do. Any help would be Appreciated. Thank You in Advance. -
how to create django-views links within javascript
I have django-application with a template-html which contains a javascript which uses AJAX to get results (while typing) of a search engine and populate a list. Now, I want this list to be links with django-patterns based on these results. How would I do that. As far as I understand, I cannot use django template-syntax within javascript. Can anybody help me with some hints? (Sorry, if any information is missing - I'm new to django/javascript/ajax) -
I cannot Display MySql data in html after fetching from database fetched data can be seen in Server ( CMD )
i have tying to display data from database only by writing query in python django but i am facing some issue what cause this issue model.py class add_topic(models.Model): test_id=models.IntegerField() topic_name=models.CharField(max_length=100) class Meta: db_table = "opicc"; view.py def addassessment(request): c = connection.cursor() c.execute('SELECT test_id, topic_name FROM test_topic') results=c.fetchall() context={"topics":results} return render(request,'add_assessment.html',context) display.html <div class="form-group"> <label>Post To</label> <select name="event_made_for" required="" class="custom-select"> <option>Select Whome you want to set this Event</option></select> {% for i in topics %} <option value="{{i.test_id}}">{{i.topic_name}}</option> {%endfor%} </select> <!--If i print that context--!> {topics} </div> output: ((8, 'hello'), (9, 'Antony')) i am getting this values if i run the code but i cant display individual values -
Matching Primary key with url in Django. When I am trying to enter the url: (localhost:8000/detail/S1111111A/) it always shows a mismatch error
Below is my view, url and model. I have stored some values in my database, and I make patientNRIC as the primary key, now I wanted to access the respective patient details through their patientNRIC, however, I could not do that, it always show me the error of mismatch. plss helllpp meeeee. Thanks #view.py from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import PatientDetail from .serializer import PatientSerializer # Create your views here. @api_view(['Get', 'POST']) # @csrf_exempt def patient_list(request): if request.method == 'GET': patientdetails = PatientDetail.objects.all() # serialization serializer = PatientSerializer(patientdetails, many=True) # return Json return Response(serializer.data) elif request.method == 'POST': #data = JSONParser().parse(request) serializer = PatientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['Get', 'PUT','DELETE']) @csrf_exempt def patient_detail(request,patientNRIC): try: patientdetails = PatientDetail.objects.get(patientNRIC) except PatientDetail.DoesNotExist: return HttpResponse(status=404) if request.method == "GET": # serialization, getting one data only serializer = PatientSerializer(patientdetails) # return Json return JsonResponse(serializer.data) elif request.method == "PUT": data = JSONParser().parse(request) serializer = PatientSerializer(patientdetails, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': patientdetails.delete() return HttpResponse(status=204) #url.py from django.urls import path from .views import … -
How can I show gender names in HTML template
Whenever I am signup for a customer on my website all the data are shown on my dashboard but in the gender field, showing me a number. Check the below image to better understand: models.py class Customer(models.Model): GenderChoice = ( ("0","Male"), ("1","Female"), ) first_name = models.CharField(max_length=20, null=True) last_name = models.CharField(max_length=20, null=True) address = models.CharField(max_length=500, null=True) phone = models.CharField(max_length=10, null=True) gender = models.IntegerField(choices=GenderChoice, default=1) email = models.CharField(max_length=100, null=True) password = models.CharField(max_length=8, null=True) Thanks! -
How to serialize string geojson in Django when part of multipart?
I am sending a multipart POST. One field of the data sent is footprint which is string geojson. I converted it to string since it cannot be send as a dict object unlike when sent POST as json. self.thumbnail = open('apps/data/thumb.png','rb') self.footprint = """{"type": "Polygon", "coordinates": [[[121.79168701171875, 16.909683615558635], [122.12539672851561, 16.909683615558635], [122.12539672851561, 17.19983423466054], [121.79168701171875, 17.19983423466054], [121.79168701171875, 16.909683615558635]]]}""" self.data = { 'thumbnail': self.thumbnail, 'footprint': self.footprint, } self.client.post('/data_management/capture_group_products/', data=self.data, format='multipart') I am using a Field Serializer in Django to extract the geojson and input to a GeometryField. class FootprintSerializer(serializers.Field): def to_internal_value(self, data): geom_data = data #geom_data = json.dumps(geom_data) print(geom_data, type(geom_data)) return GEOSGeometry(geom_data) #footprint = FootprintSerializer(source='*') When I input it to GEOSGeometry, when the data is in string, I get the error: ValueError: too many values to unpack (expected 2) {"type": "Polygon", "coordinates": [[[121.79168701171875, 16.909683615558635], [122.12539672851561, 16.909683615558635], [122.12539672851561, 17.19983423466054], [121.79168701171875, 17.19983423466054], [121.79168701171875, 16.909683615558635]]]} <class 'str'> But when I use json.dumps(geom_data), I also get backslashes from the geojson and get the error: ValueError: String input unrecognized as WKT EWKT, and HEXEWKB. Backslashed geojson: "{\"type\": \"Polygon\", \"coordinates\": [[[121.79168701171875, 16.909683615558635], [122.12539672851561, 16.909683615558635], [122.12539672851561, 17.19983423466054], [121.79168701171875, 17.19983423466054], [121.79168701171875, 16.909683615558635]]]}" <class 'str'> I also have tried: geom_data = json.dumps(json.loads(geom_data)), and also did not work. Had error like the first … -
how to convert date with format 01/01/2019 08:36 to python datetime object?
if dict_value: field_type = col.get_internal_type() # logger.info(field_type) if field_type == 'DateTimeField': dict_value = each_data.get(uploaded_header) Here in variable dict_value , i am receiving date as 01/01/2019 08:36, I need the format to converted to python datetime field value and passed back to the dict_value. How is it possible? -
Re populate images when ValidationError occurs
Good day SO. I would like to ask when trying to upload images and a ValidationError happens. As per 2011 SO Answer, this is a browser thing when trying to upload images and getting a validation error, the uploaded images are removed. Do you have any workarounds with this? If not, any suggestions? Ideas? -
How to get image url from embed tag of RichText field?
I have a RichText field in wagtail project in which the images are stored in block text as: [{'type': 'text', 'value': '<p>Image below:</p><p></p><embed alt="Screenshot from 2021-04-01 18-55-15.png" embedtype="image" format="left" id="55"/><p></p>', 'id': 'de338256-7af9-48b1-9b5a-1dda81b80e83'}] It is showing perfectly on wagtail cms, but I want to return this data in api. How do I convert the <embed> to <img>? -
Large quantity of Videos to be stored?
recently I am building a web app. since I am new to deploying and hosting; I was wondering how and where to store all the video's that my app works on them? my web app has one feature that let users upload a video of their profiles. I don't know where to store them? maybe AWS S3? or is there any other better way of doing this?