Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django, API Call with user input
I’m currently building a little Django Project and I’ve got a question. I would like to make an API Call to an external API with a user input. How can I achieve that? Pretty new to Django sorry. Regards, -
Connecting a Neo4j graph database to a Django REST API app
I am trying to connect a remote Neo4j database to a Django app with a REST API. I am trying to specify the database in the settings.py file using the following code: DATABASES = { 'default': { 'NAME': 'papers.db', 'ENGINE': 'django.db.backends.sqlite3', 'USER': '', 'PASSWORD': '', 'PORT': '', }, } I would like to know: What python libraries need to be installed in order to do this? What is the 'ENGINE' that needs to be specified in the code above? The Neo4j database has a URI, but does not provide us with an IP address - am I able to use this URI? I am confident that I know what the other parameters need to be. Thanks in advance -
pip install django-jalali-date problm
Import "jalalienter image description here_date" could not be resolved After installation, I will make a mistake. Thank you for your help -
Can i use Django Admin for the user interface when there will only be 2-3 users?
i am working on a project where i am creating a project management webapp for a small team (4-5 users). They will use it mainly for data management (CRUD operations for projects, resources, work hours, budgets etc.) and creating reports. For the CRUD part of the application i want to use Django Admin. Only 2-3 users will apply CRUD operations on the data. So i want to call them "administrators" and use the built-in Admin app because it literally has all the functionalities i need. It will save a lot of time and costs which is very important for this project I read that Admin is only meant for site administrators and this is not recommended. My question is: With this use case for the application can i use a Django admin app as a part of the User interface? Thanks in advance -
convert ManyToManyField to ForeignKey in Django
I have 3 models: class Series(models.Model): . . . series_name = models.CharField(max_length=50, unique=True) class Lists(models.Model): . . name = models.CharField(max_length=50, unique=True) class Article(models.Model): . . . lists = models.ForeignKey(Lists, blank=True, null=True, related_name='article_has', on_delete=models.CASCADE, default=None) series = models.ManyToManyField(Series, related_name='series', blank=True) is_published = models.BooleanField(default=False) Initially I created some Articles without 'lists' field. Now i want to add the 'Lists' field to the Article model but I am running into errors after makemigrations and migrate. I did the following: python manage.py makemigrations blog python manage.py migrate python manage.py makemigrations --empty blog modified the new empty generated migration file as follows: # Generated by Django 4.0.3 on 2022-05-03 13:54 from django.db import migrations def migrate_m2m_to_fk(apps, schema_editor): Article = apps.get_model("blog", "Article") for article in Article.objects.all(): article.lists = None article.lists.save() class Migration(migrations.Migration): dependencies = [ ('blog', '0001_initial'), ] operations = [ migrations.RunPython(migrate_m2m_to_fk) ] python manage.py migrate and at the step 5 I get the following error due to Article.objects.all() : MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'blog_article.lists_id' in 'field list'") -
Django collectstatic to look for assets directory in every app in django project
Currently I have 6-7 apps present inside my Django project. In settings.py for STATICFILES_DIRS I need to specify assets directory full path present inside all my apps which is cumbersome in case when I increase my apps everytime I need to add the path here. Isn't there one setting with which I can specify just the assets folders and the collectstatic command will look for static files inside assets in all my apps? This is what I currently have: STATICFILES_DIRS = [ BASE_DIR / "app1/templates/assets", BASE_DIR / "app2/templates/assets", BASE_DIR / "app3/templates/assets", BASE_DIR / "app4/templates/assets", BASE_DIR / "app5/templates/assets", BASE_DIR / "app6/templates/assets", ] What I needed was something like this and the collectstatic would have gone to all my apps(1-6) looking for the assets directory. STATICFILES_DIRS = [ 'templates/assets', ] Is there any way to do the same? -
TypeError at / sequence item 0: expected str instance, _SpecialGenericAlias found in Django templates?
I am working on an application that can parse resume content and summarize it. This application is taking input in pdf format and when I upload the pdf file of resume it is showing this error on rendering the template. I am adding a code snippet for my template folder in which it is showing this error. Error during template rendering In template D:\all projects and programs\Machine Learning Projects\resume1\resume_Shortlisting\Application\ResumeParser\resume_parser\parser_app\templates\messages.html, error at line 4 {% if messages %} <div class="messages" style="margin-top: 2%;"> {% for message in messages %} <div {% if message.tags == 'error' %} class="alert alert-danger" {% else %} class="alert alert-{{ message.tags }} "{% endif %}> {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %} {{ message }} </div> {% endfor %} </div> {% endif %} -
how to convert function base api views into class base api views?
In my project, I have the following 4 APIs (function base API view) save_user() login_user() get_user_info() update_user() I want to convert it into class base API view class UserApi(APIView): def post(): #save user def get(): #for get user info def put(): #for update user info so how to use login() in class base views. OR use function base view for login? to use a mixture of class based API view and function base API view in a single views.py file is good or bad? -
GET Error takes from 2 to 3 positional arguments but 12 were given in Djnago Rest Framework
Hi Everyone i am trying to create api using raw sql query, but when i hit url get getting error please help me out. as per me issue in dates parameter where i am using 7 days but something gets wrong, thats why getting error, i didn't know how to solve this, please help me. views.py # this is views file where i have executing my query. class CardailyReportViewset(viewsets.ModelViewSet): queryset=Car_dash_daily.objects.all() serializer_class=CarDashdailySerializer def retrieve(self, request, *args, **kwargs): params= kwargs params_list=params['pk'].split(',') dates=params_list[0] team_id=params_list[1] start_date=params_list[2] end_date=params_list[3] car_report= connection.cursor() car_report.execute(''' SELECT temp2.car_number,sum(temp2.trips)as total_trips, temp2.status, case when sum(temp2.day1_trips)=-10 then 'BD' when sum(temp2.day1_trips)=-20 then 'ND' when sum(temp2.day1_trips)=-30 then 'R' when sum(temp2.day1_trips)=-40 then 'I' when sum(temp2.day1_trips)=-50 then 'P' else sum(temp2.day1_trips) end AS day1_trips, case when sum(temp2.day2_trips)=-10 then 'BD' when sum(temp2.day2_trips)=-20 then 'ND' when sum(temp2.day2_trips)=-30 then 'R' when sum(temp2.day2_trips)=-40 then 'I' when sum(temp2.day2_trips)=-50 then 'P' else sum(temp2.day2_trips) end AS day2_trips, case when sum(temp2.day3_trips)=-10 then 'BD' when sum(temp2.day3_trips)=-20 then 'ND' when sum(temp2.day3_trips)=-30 then 'R' when sum(temp2.day3_trips)=-40 then 'I' when sum(temp2.day3_trips)=-50 then 'P' else sum(temp2.day3_trips) end AS day3_trips, case when sum(temp2.day4_trips)=-10 then 'BD' when sum(temp2.day4_trips)=-20 then 'ND' when sum(temp2.day4_trips)=-30 then 'R' when sum(temp2.day4_trips)=-40 then 'I' when sum(temp2.day4_trips)=-50 then 'P' else sum(temp2.day4_trips) end AS day4_trips, case when sum(temp2.day5_trips)=-10 then 'BD' when … -
ModuleNotFoundError: No module named 'scanner.wsgi'
2022-05-04T03:48:55.987895+00:00 app[web.1]: File "", line 1027, in _find_and_load 2022-05-04T03:48:55.987896+00:00 app[web.1]: File "", line 1004, in _find_and_load_unlocked 2022-05-04T03:48:55.987896+00:00 app[web.1]: ModuleNotFoundError: No module named 'scanner.wsgi' 2022-05-04T03:48:55.988039+00:00 app[web.1]: [2022-05-04 03:48:55 +0000] [9] [INFO] Worker exiting (pid: 9) 2022-05-04T03:48:56.025390+00:00 app[web.1]: [2022-05-04 03:48:56 +0000] [4] [INFO] Shutting down: Master 2022-05-04T03:48:56.025449+00:00 app[web.1]: [2022-05-04 03:48:56 +0000] [4] [INFO] Reason: Worker failed to boot. 2022-05-04T03:48:56.211911+00:00 heroku[web.1]: Process exited with status 3 2022-05-04T03:48:56.415253+00:00 heroku[web.1]: State changed from starting to crashed 2022-05-04T07:19:55.297563+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=eth-scan.herokuapp.com request_id=ebd93840-9d54-4797-ac0c-b095b1c69601 fwd="102.89.33.169" dyno= connect= service= status=503 bytes= protocol=https 2022-05-04T07:19:55.695154+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=eth-scan.herokuapp.com request_id=7a30fa28-053b-46f6-ab2e-3e3d9216c040 fwd="102.89.33.169" dyno= connect= service= status=503 bytes= protocol=https -
Django and Javascript Uploading Images with Progress Bar
Good day, I am trying to upload multiple images in django with a progress bar. Currently, I have a working solution for only one image but now I want to add more fields and I need to show progress bar for all the images I am uploading. Below is my working code and the commented out code in the forms.py are the new fields I want to add. models.py class ProductImage(models.Model): product = models.OneToOneField(Product, on_delete=models.CASCADE, null=True, blank=True) main_image = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_one = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_two = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_three = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_four = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_five = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) forms.py class StoreDashboardProductUpdateForm(forms.ModelForm): class Meta: model = ProductImage fields = [ "main_image", # "img_one", # "img_two", # "img_three", # "img_four", # "img_five" ] views.py def store_dashboard_product_update_view(request, slug, product_slug, pk): product = get_object_or_404(Product, pk=pk) form = StoreDashboardProductUpdateForm(request.POST or None, request.FILES or None) if request.is_ajax(): if form.is_valid(): form.instance.product = product form.save() return JsonResponse({'message': 'hell yeah'}) context = { 'form': form, "object": product } return render(request, 'store/dashboard/product_update.html', context) product_update.html {% extends 'store/dashboard/base/products-second.html' %} {% load crispy_forms_tags %} {% load widget_tweaks %} {% block content %} <style> .not-visible { display: none; … -
Django user check_password returns False in tests
I've customized my User manager created create_user and create_superuser method and it's working fine but when I run test on it it fails because of user.check_password() it returns False. I found this post according to it Django unable to identify the correct hasher. This is my UserManager class class UserManager(BaseUserManager): def create_user(self, email, passowrd=None, **extra_fields): '''Creates and saves a new user''' phone = extra_fields.get('phone') if not email: raise ValueError("User must have an email address") if not phone: raise ValueError("User must have a phone number") user = self.model(email=self.normalize_email(email), **extra_fields) user.phone = phone user.set_password(passowrd) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): '''Creates and saves a new superuser''' user = self.create_user(email, password, **extra_fields) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user and this my test method for testing user creation def test_create_user_with_email_and_phone(self): '''Test creating new user with an email and phone successfuly''' email = 'demo@gmail.com' password = 'demo@1234' phone = 1234567890 user = get_user_model().objects.create_user( email=email, password=password, phone=phone ) self.assertEqual(user.email, email) self.assertEqual(user.phone, phone) print(f'\n User Password : {user.password} \n') print(f'\n Check Password : {user.check_password(password)} \n') self.assertTrue(user.check_password(password)) this is output of print() function User Password : !dAqIjSVT6hpEhKj4JEjLLDAB3hAJt042Zaj8JS8R Check Password : False -
Django channel group_send all messages to one channel in the group
I am trying to make a real time chat web app with Django channel. When I am trying using Postman build multiple WS connections with it. I encountered some weird thing, let's say I have 2 connections to the same server at 8000 port. Then I send a message via group_send, ideally each connection will get 1 message, but it turn out 2 messages are send to the newer connection. Here is my consumer: class RealtimeConsumer(AsyncJsonWebsocketConsumer): async def websocket_connect(self, event): user_id = self.scope['user'] await self.channel_layer.group_add( str(user_id), # use id as the group name self.channel_name ) await self.accept() await self.send_json( { "connectionKey": self.channel_name, "clientId": str(user_id), }, ) async def send_message(self, event): message = event["message"] await self.send_json( { "messages": message, "connectionKey": self.channel_name, }, ) async def websocket_disconnect(self, message): user_id = self.scope['user'] await self.channel_layer.group_discard( str(user_id), # group name self.channel_name ) Send to group func: def send_single_user_msg(channel_name, message): channel_layer = get_channel_layer() async_to_sync(channel_layer.send)( channel_name, { 'type': 'send_message', "text": message, } ) I'm using local redis server as the channel layer. Any idea will be really appreciated. -
"no such table: Sport" on exporting a table from sqlite db (django view)
In my django view, after updating a table, I put this code for exporting that table into csv file: # export Data print ("Export data into csv file..............") conn = sql.connect('sqlite3.db') # I tried: db.sqlite3 -> same cursor=conn.cursor() cursor.execute("select * from Sport") with open("heartrateai_data.csv", "w") as csv_file: csv_writer = csv.writer(csv_file, delimiter="\t") csv_writer.writerow([i[0] for i in cursor.description]) csv_writer.writerows(cursor) dirpath = os.getcwdb()+"/heartrateai_data.csv" print("Data exported Successfully into {}".format(dirpath)) conn.close() But it gives me the error: Exception Value: no such table: Sport. I am sure that the table name is correct because is the same in my model.py. -
css and other assets not loading for my django webapp
CSS, JS, fonts, images and other assets are not being loaded into my django app index.html. All the assets for the app are present inside the application app in my django project under "templates/assets". I have tried the other answer which I was getting as suggestion to this question but even that solution did not work for me. [04/May/2022 05:48:50] "GET /assets/js/glightbox.min.js HTTP/1.1" 404 2311 Not Found: /assets/js/count-up.min.js [04/May/2022 05:48:50] "GET /assets/js/count-up.min.js HTTP/1.1" 404 2308 Not Found: /assets/js/main.js [04/May/2022 05:48:50] "GET /assets/js/main.js HTTP/1.1" 404 2284 Here is my dir tree structure : Project Name : myproject App name that serves index.html : app ├── app │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── admin.cpython-38.pyc │ │ ├── apps.cpython-38.pyc │ │ ├── models.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── views.cpython-38.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-38.pyc │ ├── models.py │ ├── templates │ │ ├── 404.html │ │ ├── assets │ │ │ ├── css │ │ │ │ ├── LineIcons.2.0.css │ │ │ │ ├── animate.css │ │ │ │ ├── bootstrap.min.css │ │ │ │ ├── glightbox.min.css │ … -
Django paginator and zipping
I want to iterate a list and query set in my html render, but am unable to get the Django paginator to work. I zipped the list and queryset so I could iterate them together. Here's my views.py code. Oddly enough, I am able to access the data in both lists with {% for item1, item2 in posts %}, but {{ posts.next_page_number }} is just blank. How can I access the page in the templating engine? -
I have this error: "error": "invalid_client" in postman
I have this error when I use Django Oauth2 Provider. How can I fix it? Sorry because my english is bad. enter image description here -
Handling SSO between two Django applications
There is two Django-based application under a single platform with different sub-domain. One of the applications is using an OpenSource project. Here databases are different between these applications and both respective user tables. We want to avoid making any major changes to this 2nd application(OSS one) to make sure there is maintainability. The question is how can we have an SSO in a place where the user's signup on the 1st application(our main application), the users should be auto-logged in on the 2nd application too. The 1st application should ideally handle all sign-up/sign-in processes. Both applications support SessionAuthentication. -
Deploy Django to Azure Web Service - Failed running 'collectstatic' exited with exit code
I am trying to deploy a Django app to Azure App Services. It runs on the server now, but without the style.css. When I run it on localhost, everything shows correctly with the style.css. Here is the collectstatic part from the deployment log: 11:23:09 PM voicify: Running collectstatic... 11:23:12 PM voicify: 130 static files copied to '/tmp/8da2d7d5197a819/staticfiles'. 11:23:12 PM voicify: "2022-05-03 07:00:00"|WARNING|Failed running 'collectstatic' exited with exit code . Below is my settings.py file: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] And here is my project structure: voice-project -- app-- settings.py -- wsgi.py -- urls.py -- manage.py --db.sqlite3 -- asgi.py -- static -- website --style.css -- website -- .git -
Python showing remember me checkbox in login page with cookies
My login page needs a remember me checkbox so that it doesnot need to login with password again.I have the html code for it but django code shows error.Can anyone help me to find the code. -
Is there any way to control all the configuration of settings.py from models in django?
I want to control everything from admin panel so that it is easy for the non technical person to control everything from admin panel.Is there any way to control everything from admin panel?? -
I want to compare now time with Django DateTimeField Filed in Django Templates
I want compare now time with Django DateTimeField Filed in Django Templates. -
django.db.utils.ProgrammingError: column _____ does not exist
There are a lot of similar posts to this but none that I have found seem to resolve the program. I have tried to add a field to a custom user model that inherits from Django's AbstractUser: class AppUser(AbstractUser): credibility_rating = models.FloatField(default=0) When I save this and try to run python manage.py makemigrations it gives me this error: Traceback (most recent call last): File "/Users/jhcscomputer1/.local/share/virtualenvs/senior_project-hOu14Mps/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column api_appuser.credibility_rating does not exist LINE 1: ...ppuser"."is_active", "api_appuser"."date_joined", "api_appus... When I replace the field credibility_rating with pass the error goes away. Similarly, when I try to add a new field in a different model, the error doesn't occur either. I am not sure if this matters, but I am using Postgres. My settings.py file does include AUTH_USER_MODEL = "api.AppUser" where api is the name of my app. I am not sure where I am going wrong. Thank you for any help. Full traceback: Traceback (most recent call last): File "/Users/jhcscomputer1/.local/share/virtualenvs/senior_project-hOu14Mps/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column api_appuser.credibility_rating does not exist LINE 1: ...ppuser"."is_active", "api_appuser"."date_joined", "api_appus... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File … -
Django DRF - Is it possible to have a pre-defined form in the browsable API using function-based views?
I have an API built with Django DRF. I'm using function based views and I was wondering if it's possible to add a defined form (based on the model serializer) for the browsable API? I want to turn this (the browsable API I get with function based views): Into this (what I get with class based views): -
Django Model not defined
I've been working on some views and using a model for like a week now and there was no issues until now: I did not change anything but add a new field to the model, and now myModel.objects.create() gives me a name is not defined error. I have the model imported and as I said, I've been working on this for a week and I created several models using the exact same code. models: class Prescription(models.Model): prescription_id = models.CharField(max_length=26, default=prescription_id, editable=False, unique=True) # THIS IS THE FIELD I ADDED BEFORE HAVING THIS ERROR appointment = models.ForeignKey('booking.Appointment', on_delete=models.SET_NULL, null=True, blank=True) doctor = models.ForeignKey('core.Doctor', on_delete=models.CASCADE) patient = models.ForeignKey('core.Patient', on_delete=models.CASCADE) overriden_date = models.DateField(null=True, blank=True) control = models.BooleanField(default=False) control_date = models.DateField(null=True, blank=True) send_email = models.BooleanField(default=False) posted = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Ordonnance" verbose_name_plural = "Ordonnances" def __str__(self): return str(self.id) class PrescriptionElement(models.Model): prescription = models.ForeignKey('Prescription', on_delete=models.CASCADE) drug = models.ForeignKey(Drug, on_delete=models.CASCADE, null=True) custom = models.CharField("Elément", max_length=25, null=True, blank=True) dosage = models.CharField(max_length=45, null=True, blank=True) posologie = models.CharField(max_length=256, null=True, blank=True) duration = models.CharField("Durée", max_length=15, null=True, blank=True) views: PrescriptionElement.objects.create(prescription=prescription, drug=listemedicament, custom=medicament, dosage=dosage, posologie=posologie, duration=duree) error: name 'PrescriptionElement' is not defined