Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django can’t establish a connection to the server
I'm using docker to start a project using django after I did build I get no error and I did up I get no error but still can't connect to server my docker ps return CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 385d949fdb65 yacosql_web "python manage.py ru…" 2 minutes ago Up 2 minutes 0.0.0.0:8000->8000/tcp yacosql_web_1 754707984f75 mysql:5.7 "docker-entrypoint.s…" 11 minutes ago Up 2 minutes 0.0.0.0:3306->3306/tcp, 33060/tcp yacosql_db_1 in docker-compose up : web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | web_1 | You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. web_1 | Run 'python manage.py migrate' to apply them. web_1 | April 25, 2021 - 02:44:17 web_1 | Django version 2.2, using settings 'yacosql.settings' web_1 | Starting development server at http://127.0.0.1:7777/ web_1 | Quit the server with CONTROL-C. my docker-compose.yml : version: "3.3" services: db: image: mysql:5.7 ports: - '3306:3306' environment: MYSQL_DATABASE: yacosql MYSQL_USER: yacosql MYSQL_PASSWORD: yacosql MYSQL_ROOT_PASSWORD: yacosql web: build: context: . dockerfile: ./docker/Dockerfile command: python manage.py runserver 127.0.0.1:7777 volumes: - .:/usr/src/app ports: - "8000:7777" depends_on: - … -
React: Add JSX to project
I am trying to integrate React into Django project for production usage. First I tried Add React in One Minute, and the website render the JSX starter code correctly. Then I tried Add JSX to a Project, my HTML file is as bellow {% load static %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <link rel="stylesheet" href="{% static 'resume/index.css' %}"> <script src="{% static 'resume/index.js' %}"></script> <title>Tik Tak Toe</title> </head> <body> <div id="root"></div> </body> </html> Then I use Django to run the server, but the website render nothing and display this error in the console index.js:45 Uncaught ReferenceError: React is not defined at index.js:45 I tried added import React from 'react'; import ReactDOM from 'react-dom'; but then this error showed up Uncaught SyntaxError: Cannot use import statement outside a module. My static/resume/src/index.js is as bellow 'use strict'; class LikeButton extends React.Component { constructor(props) { super(props); this.state = { liked: false }; } render() { if (this.state.liked) { return 'You liked this.'; } return ( <button onClick={() => this.setState({ liked: true })}> Like </button> ); } } let domContainer = document.querySelector('#root'); ReactDOM.render(<LikeButton />, domContainer); and my static/resume/index.js is as bellow var _createClass = function () { function defineProperties(target, props) { for (var … -
DigitalOcean App-platform: Host Dockerized Django app with Gunicorn on a non-root URL
I recently deployed a dockerized Django app on DigitalOcean app platform alongside a react static site using the app spec file. Because of the static site, I opted to serve Django on a non-root URL (something like https: //mydomain .com/api) and serve the react app on the root URL (https: //mydomain .com). If I visit the Django URL, Django comes up but throws a "path not found error". None of the routes on my Django app works. The solution doesn't seem to be on google either and I don't know why. here is what my app.yaml looks like name: test region: nyc services: - name: backend-api github: branch: deployment_app_platform repo: NdibeRaymond/test deploy_on_push: true http_port: 8000 instance_count: 1 instance_size_slug: basic-xxs source_dir: backend/ dockerfile_path: backend/compose/django/Dockerfile routes: - path: /api static_sites: - name: frontend environment_slug: node-js github: branch: deployment_app_platform repo: NdibeRaymond/test deploy_on_push: true source_dir: frontend/test/ build_command: npm run build routes: - path: / gunicorn configuration exec /usr/local/bin/gunicorn test.wsgi --threads=3 --bind 0.0.0.0:8000 --chdir /backend/test root URL file urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('summernote/', include('django_summernote.urls')), path('', include('APIS.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I also tried urlpatterns = [ path('api/admin/', admin.site.urls), path('api/api-auth/', include('rest_framework.urls')), path('api/summernote/', include('django_summernote.urls')), path('api/', include('APIS.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
'ON CONFLICT' error for new single insert through Django admin to postgres
Today, for the first time, I got an 'ON CONFLICT' error while trying to insert a new entry through the Django admin to my postgres database: ignored_wrapper_args (False, {'connection': <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f0bb08e3d90>, 'cursor': <django.db.backends.postgresql.base.CursorDebugWrapper object at 0x7f0bb094ab50>}) params (3351, 48, 3351, 212, 3351, 31) self <django.db.backends.postgresql.base.CursorDebugWrapper object at 0x7f0bb094ab50> sql ('INSERT INTO "ktab_entry_tags" ("entry_id", "tag_id") VALUES (%s, %s), (%s, ' '%s), (%s, %s) ON CONFLICT DO NOTHING') 3351 is the id that would have been auto assigned to the entry had it been accepted. 48, 212, and 31 are the ids of the 3 tags I was going to put on this entry. I have been using this blog app - which I created - for almost 3 years. Not only have I never come across this error before, it does not make sense to me. Each entry has a unique id. Therefore it's hard to imagine a case where there would be a conflict due to a combination of entry_id, tag_id, and entry_tag_id being repeated. Therefore, any such constraint would be redundant and unnecessary. But it looks like I do have it: ktab.public.ktab_entry_tags.ktab_entry_tags_entry_id_tag_id_0900d285_uniq(entry_id, tag_id) and ktab.public.ktab_entry_tags.ktab_entry_tags_entry_id_tag_id_0900d285_uniq(entry_id, tag_id) UNIQUE If the 2nd one is unique, why do both end … -
Reverse for 'post_edit' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/edit/$']. Can some please help me?
NoReverseMatch at /post/2/ Reverse for 'post_edit' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/edit/$'] Request Method: GET Request URL: http://127.0.0.1:8000/post/2/ Django Version: 3.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'post_edit' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/edit/$'] Exception Location: C:\Users\hp.virtualenvs\blog-p5Wsl8r-\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\hp.virtualenvs\blog-p5Wsl8r-\Scripts\python.exe Python Version: 3.9.4 Python Path: ['C:\Users\hp\Desktop\blog', 'c:\users\hp\appdata\local\programs\python\python39\python39.zip', 'c:\users\hp\appdata\local\programs\python\python39\DLLs', 'c:\users\hp\appdata\local\programs\python\python39\lib', 'c:\users\hp\appdata\local\programs\python\python39', 'C:\Users\hp\.virtualenvs\blog-p5Wsl8r-', 'C:\Users\hp\.virtualenvs\blog-p5Wsl8r-\lib\site-packages'] Server time: Sun, 25 Apr 2021 00:57:10 +0000 -
Display image from Django database to React JS frontend
I'm having an issue where the images I upload to Django database aren't displaying into the React JS frontend. I created this model: class Project(models.Model): title = models.CharField(max_length=100, null=False) description = models.CharField(max_length=10000, null=False) thumbnail = models.ImageField(upload_to='images/', null=False) I'e serialized it and all that. I then upload that information to the database by going to the /admin url where I can see the database. After that, I make an api call to the database and fetch all the data. Now this is where the issue occurs. I move that data into a useState([]) and then map that state. The title and description do get displayed on the screen, but the image doesn't. Here is the code where I map the useState([]): {projData.map(data => ( <div key={data.id}> <img className="thumbnail" src={data.thumbnail}/> <span className="title">{data.title}</span> <p className="description">{data.description}</p> </div> ))} So like I said, the title and description do successfully get called, but this is the error I get for the image: [Error] Failed to load resource: http://127.0.0.1:8000/images/background.png the server responded with a status of 404 (Not Found) (background.png, line 0) The image does get moved into the images folder. But for some reason, it doesn't display into the actual website. What can I do? -
Django model select between two columns/fields?
I have a Slider module that i want to include items from movies_movie and shows_show table. An item can either be a show or movie. How do i make user select between movie and show? Currently i have columns for movie and show but how do i force user to select between the two? also title_en is a column in movie or tv show tables. So the title of the movie/show selected should display in row after save. class Slider_items(models.Model): order = models.IntegerField(max_length=3, blank=True) movie = models.ForeignKey('movies.movie', on_delete=models.CASCADE, blank=True) show = models.ForeignKey('shows.show', on_delete=models.CASCADE, blank=True) def __str__(self): return self.title_en class Meta: verbose_name = "Slider Items Module" verbose_name_plural = "Slider Item Module" Also if a show is selected and a movie isn't, how do i know title_en will be taken from show and not movie? -
How to share data between Django files within one project?
I'm a Django newbie, so I'm trying to learn by slowly build my own expenses and income website on PythonAnywhere. I know my project is not properly spec'd, but it works perfectly ... except for one thing: The home page can pull data from my expenses table but not my income table. There's no error, it just returns zero records. I'm convinced the problem is related to the fact that I've put income-related items in a separate income.py file. I don't want to merge the income stuff into the larger views.py file. Can you please give me some suggestions on how I can access the Income table data from the HomePageView in views.py? Thanks, Jason Django Site Structure: Django01 ---Django01 __init__.py asgi.py income.py # created later, contains income_list(request) models.py # contains definitions for both an Expenses table and an Income table settings.py urls.py # holds all urls for site views.py # contains HomePageView(TemplateView) and expense_list(request) wsgi.py ---static ---templates ---Django01 base.html expenses_list.html home.html # Page where I'd like to access BOTH Expense and Income table incomes_list.html views.py: # =============================================================================== # views.py # =============================================================================== from django.views.generic import TemplateView from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from … -
Creating a Nested Serializer with two "Sibling" Models
I'm attempting to get a JSON output similar to this: { name: John Doe, best_buy_price: 420, best_sell_price: 69, player_profile: { tsn_link: https://a_link.com } playerlistingadvanced: { # This is where I'm having the issue sales_minute: 7, } } I have three models. playerProfile being the "main" model and playerListing and playerListingAdvanced are connected to playerProfile via a one-to-one relationship. playerPfofile will have its own endpoint, but I'd also like to create an endpoint that is primarily the listings and advanced listing data (as seen above). Here is a stripped down version of the model.py file: class PlayerProfile(models.Model): card_id = models.CharField(max_length=120, unique=True, primary_key=True) name = models.CharField(max_length=420, null=True) tsn_link = models.CharField(max_length=420, null=True) class PlayerListing(models.Model): player_profile = models.OneToOneField( PlayerProfile, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=420, null=True) best_sell_price = models.IntegerField(null=True) best_buy_price = models.IntegerField(null=True) class PlayerListingAdvanced(models.Model): player_profile = models.OneToOneField( PlayerProfile, on_delete=models.CASCADE, null=True) sales_minute = models.DecimalField(max_digits=1000, decimal_places=2, null=True) Here is the serializer.py I have tried, but haven't gotten to work. class PlayerListingAdvancedForNestingSerializer(serializers.ModelSerializer): class Meta: model = PlayerListingAdvanced fields = ( 'sales_minute', 'last_week_average_buy', 'last_week_average_sell', ) class PlayerListingSerializer(serializers.ModelSerializer): player_profile = PlayerProfileForListingSerializer() # works playerlistingadvanced = PlayerListingAdvancedForNestingSerializer() #doesn't work class Meta: model = PlayerListing fields = ( 'name', 'best_sell_price', 'best_buy_price', 'playerlistingadvanced', 'player_profile' ) I'm assuming because playerListing and playerListingAdvanced are not … -
Django returning 500 Internal Server Error instead of index.html when Debug = False
I have a problem in my django web application in which django returns a 500 error when trying to get the index.html file. This only happens when Debug = False and it only happens with this one template. All the other templates render normally without errors. I have already tried the whitenoise settings, favicon.ico errors, checked all routes and everything seems to be fine, I really can't find the error. The weird thing is that it is only happening in index.html. If someone can help I will really appreciate it, thanks in advance. settings.py DEBUG = False ALLOWED_HOSTS = ['vilytic.herokuapp.com', '127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'accounts', 'comparer', ] REST_FRAMEWORK = { 'DEFAULT_THROTTLE_RATES': { 'video_search': '8/day', 'video_id': '8/day' } } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' Error that appears in terminal "GET / HTTP/1.1" 500 145 urls.py from django.contrib import admin from django.urls import path, include from . import views … -
Data structure accessible from anywhere in Django, as a global variable, in all views, and all sessions, without using cache or session variables
First of all, I know this question has been asked many times on stackoverflow. I read them all... few times. But somehow none of them are specific to my scenario. I have a data structure that I want to be like a variable, accessible from all views, for all users, for all sessions. Specifically the data structure I need is a tree, a Trie, that I am using for autocompletion a search bar. So obviously this view will be called very often, at every key-press, and needs to be fast, less than a second. I have tried the following from django.core.cache import cache cache.get('key_of_the_trie_inside_cache') This works, but this "cache.get()" takes 4 seconds - and even more, as the data structure increases inside. That is unnacceptably slow for autocompletion in a search bar, to perform on every key press. Another advice from the stackoverflow answers, was to use request.session('key_of_the_trie_inside_session') However, in session, I can store only something which is JSON serializable. I checked these forums on how to do that as well - turns out, I can get the data inside the Trie into a JSON, but I am no longer able to call the functions of the Trie, like trie.get_autocompletion_for_this_string(somestring) … -
Django don`t serve static files with NGINX + GUNICORN
Everything worked very well before gunicorn and nginx, static files we re served to the website. But now, dont work anymore. Any help is greatly appreciated. Many thanks. Settings.py STATICFILES_DIRS = [ '/root/vcrm/vcrm1/static/' ] STATIC_ROOT = os.path.join(BASE_DIR, 'vcrm/static') STATIC_URL = '/static/' MEDIA_ROOT = '/root/vcrm/vcrm1/vcrm/media/' MEDIA_URL = '/media/' /etc/nginx/sites-available/vcrm server { listen 80; server_name 195.110.58.168; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /root/vcrm/vcrm1/vcrm; } location = /media { root /root/vcrm/vcrm1/vcrm; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } when i run collectstatic: You have requested to collect static files at the destination location as specified in your settings: /root/vcrm/vcrm1/vcrm/static This will overwrite existing files! Are you sure you want to do this? and then: Found another file with the destination path 'admin/js/vendor/jquery/jquery.min.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. 0 static files copied to '/root/vcrm/vcrm1/vcrm/static', 251 unmodified. -
Next and previous buttons for a queryset in a DetailView
I'm new to Django, and I'm working on my first real (i.e., non-tutorial) project. I have class-based ListViews on four models, and the lists can be filtered in various ways. The user can click on anything in a filtered list to get a DetailView of the item. This is all straightforward and works fine. I would like to have Previous and Next buttons on the detail pages that allow the user to step through the current filtered set in the default order (which is not date or id). I've found various bits and pieces on StackExchange and elsewhere that look like parts of a solution, but I haven't been able to figure out how to make them all work together in my views. Here is slightly simplified code for one of my tables. "Works" are various items (plays, operas, ballets, etc.) that were performed in one of two theaters. models.py class Work(models.Model): title = models.CharField(max_length=100) sort_title = models.CharField(max_length=100) genre = models.CharField(max_length=50) class Meta: ordering = ['sort_title'] The field sort_title strips off articles at the beginnings of titles (which are in German and French) and deals with accented characters and the like, so that the titles will sort correctly alphabetically. This … -
Nginx returning a 403 instead of proxying to uWSGI
I am currently facing an issue. I have a Flask application set up on a DigitalOcean server with endpoints that will later be called from within a Django project. Hitting these endpoints from Insomnia or Postman works well, but when the endpoints are triggered from within the Django application, Nginx returns a 403. Here's my nginx configuration for the Flask app: server { listen 443 ssl; listen [::]:443 ssl; #listen 80; ssl_certificate /etc/ssl/certs/site.com.pem; ssl_certificate_key /etc/ssl/private/site.com.key; server_name app.site.com; #location = /favicon.ico { access_log off; log_not_found off; } location / { include uwsgi_params; uwsgi_pass unix:/home/site/server/server.sock; } } What could be wrong guys? -
Transfer Django 2D list to Javascript Array
Views.py op=[[19.076, 72.87], [28.557166, 77.163675]] op=simplejson.dumps(op) context={'coord':op} return render(request, 'output.html' , context) Template.html var a = "{{coord |safe}}"; Still, the 'a' variable comes out to be string type and not array type.How to make it a 2d array. -
Django / Heroku Deploying - ModuleNotFoundError: "No module named 'django'"
I get the ModuleNotFoundError: "No module named 'django' if I deploy my Django-Project to Heroku. Does anyone know why that is? the complete log file, which comes after opening, is attached. I've been searching for several hours, but can't solve it.. 2021-04-24T21:54:55.188701+00:00 heroku[web.1]: State changed from crashed to starting 2021-04-24T21:54:59.835950+00:00 heroku[web.1]: Starting process with command `gunicorn MPLoadManagement.wsgi --log-file -` 2021-04-24T21:55:02.907766+00:00 app[web.1]: [2021-04-24 21:55:02 +0000] [4] [INFO] Starting gunicorn 19.9.0 2021-04-24T21:55:02.908183+00:00 app[web.1]: [2021-04-24 21:55:02 +0000] [4] [INFO] Listening at: http://0.0.0.0:3028 (4) 2021-04-24T21:55:02.908277+00:00 app[web.1]: [2021-04-24 21:55:02 +0000] [4] [INFO] Using worker: sync 2021-04-24T21:55:02.909677+00:00 app[web.1]: /app/.heroku/python/lib/python3.9/os.py:1023: RuntimeWarning: line buffering (buffering=1) isn't supported in binary mode, the default buffer size will be used 2021-04-24T21:55:02.909678+00:00 app[web.1]: return io.open(fd, *args, **kwargs) 2021-04-24T21:55:02.912935+00:00 app[web.1]: [2021-04-24 21:55:02 +0000] [7] [INFO] Booting worker with pid: 7 2021-04-24T21:55:02.919805+00:00 app[web.1]: [2021-04-24 21:55:02 +0000] [7] [ERROR] Exception in worker process 2021-04-24T21:55:02.919807+00:00 app[web.1]: Traceback (most recent call last): 2021-04-24T21:55:02.919817+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2021-04-24T21:55:02.919818+00:00 app[web.1]: worker.init_process() 2021-04-24T21:55:02.919818+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 129, in init_process 2021-04-24T21:55:02.919818+00:00 app[web.1]: self.load_wsgi() 2021-04-24T21:55:02.919819+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2021-04-24T21:55:02.919819+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-04-24T21:55:02.919820+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-04-24T21:55:02.919820+00:00 app[web.1]: self.callable = self.load() 2021-04-24T21:55:02.919820+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 52, in … -
Upload image file from Angular to Django REST API
I want to select an image and POST that to the Django REST API that I have built but I am getting an error in doing so ""product_image": ["The submitted data was not a file. Check the encoding type on the form."]" I can create and update strings and integers but when I try add the image field I get this error. I can POST images through Postman so I don't think its my API that's at fault. Can anyone help me out here as I have looked around but can't seem to find anything. add-product.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { ApiService } from 'src/app/api.service'; import { Product } from 'src/app/models/Product'; import { Location } from '@angular/common'; import { Shop } from '../../../models/Shop'; @Component({ selector: 'app-add-product', templateUrl: './add-product.component.html', styleUrls: ['./add-product.component.css'] }) export class AddProductComponent implements OnInit { product!: Product; selectedFile!: File; colours = [ 'Red', 'Blue', 'Orange', 'Yellow', 'White', 'Black', 'Navy', 'Brown', 'Purple', 'Pink' ] categories = [ 'Food & Beverages', 'Clothing & Accessories', 'Home & Garden', 'Health & Beauty', 'Sports & Leisure', 'Electronic & Computing' ] stock = [ 'In … -
Can we use filter while defining manytomanyfiled in django?
I have a user table with user type as actor, singer, producer etc. I have another table Movies name = models.CharField(max_length=100) category = models.ManyToManyField(Category, related_name='movies_category') release_date = models.DateField() actors = models.ManyToManyField(User, related_name='movies_actors') producer = models.ManyToManyField(User, related_name='movies_producers') singers = models.ManyToManyField(User, related_name='movies_singers') length = models.TimeField() when I create movie object then for actors fields only those user object should come which has user_type as actor and same for producer and other fields, how can I do that? -
Error trying to create new groups using django Group model
I am creating a role management using django groups, but I am running into a problem and it is that when I want to create new groups through the Group model with a serializer, it generates the following error str object has no attribute _meta: This is my serializer: class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('name',) This is my view: class CreateGroup(APIView): def post(self, request, format=None): serializer = GroupSerializer(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) -
how to add picture field in forms.py Django-Allauth
how to add picture or image field in forms.py Django-Allauth , i tried do this but when i click signup it don't save my image to user profile why forms.py : class CustomSignupForm(SignupForm): first_name = forms.CharField(required=True,label='First Name') last_name = forms.CharField(required=True,label='Last Name') image = forms.ImageField(required=True,label='your photo') def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.image = self.cleaned_data['image'] user.save() return user -
using custom model fo django djoser
i am creating api endpoints for user management using Djoser and i want to use a custom model to create user and login i only want to use email. the user entity given to me does not have a username field below i will share the various settings i have set up for my apps #accounts/model.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): username = None email = models.EmailField(unique=True) REQUIRED_FIELDS = ['first_name', 'last_name'] USERNAME_FIELD = 'email' def __str__(self): return self.email My serializer file #accounts/serializers.py from djoser.serializers import UserCreateSerializer, UserSerializer from rest_framework import serializers from rest_framework.fields import CurrentUserDefault from .models import CustomUser class UserCreateSerializer(UserCreateSerializer): class Meta: model = CustomUser fields = ['id', 'email', 'first_name', 'last_name'] #settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSIONS_CLASSES': ( 'rest_framework.permissions.IsAuthenticated' ) } AUTH_USER_MODEL = 'accounts.CustomUser' DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'SERIALIZERS': { 'user_create': 'accounts.serializers.UserCreateSerializer', 'user': 'accounts.serializers.UserCreateSerializer', # 'current_user': 'accounts.serializers.CurrentUserSerializer' } when i try to register user i get TypeError at /auth/users/ create_user() missing 1 required positional argument: 'username' Request Method: POST Request URL: http://127.0.0.1:8000/auth/users/ Django Version: 3.1 Exception Type: TypeError Exception Value: create_user() missing 1 required positional argument: 'username' Exception Location: /home/femiir/.virtualenvs/codegarage/lib/python3.8/site-packages/djoser/serializers.py, line … -
How to restore postgress db on pythonanywhere
I couldn't find guidelines on how to restore Postgres DB 'pythonanywhere' on their documentation. Any help is appreciated! -
Django ValueError: Cannot use QuerySet for "": Use a QuerySet for "User"
I'm working on a project in CS50w where I have to show the posts of the user I'm following and I'm getting the following error ValueError: Cannot use QuerySet for "Following": Use a QuerySet for "User". models.py: class Post(models.Model): """Tracks all the posts""" text = models.TextField(max_length=256) user = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(auto_now_add=True) class Following(models.Model): """Tracks the following of a user""" user = models.ForeignKey(User, on_delete=models.CASCADE) following = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followers") And this how I'm trying to retrieve the posts of the users I'm following: views.py # Gets all the posts from the users the current user is following followings_usernames = Following.objects.filter(user=request.user) posts = Post.objects.filter(user=followings_usernames) Any help is appreciated. -
Why "None" is appearing in between Navbar and Body in Django cms
I haven't any thing in between navbar and body but this None is appearing and I am unable to understand why. I am sharing my Home template where it is appearing. Check the code between navbar and placeholder Slider. {% load cms_tags menu_tags sekizai_tags static %} <!--load template libraries of Sekizai and CMS tag --> {% load thumbnail %} <!DOCTYPE html> <html lang="{{ LANGUAGE_CODE }}"> <!-- in case you want other languages --> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> {% page_attribute "meta_description" %} <!--should have description of pages--> <meta name="author" content=""> <title>Smart Learn - {% page_attribute "page_title" %} </title> <!--In title page name should come first then website title --> {% render_block "css" %} <!-- loading css here render_block comes with sekizai lib to allow templates to included--> <!-- Bootstrap core CSS --> {% addtoblock "css" %} <!--for sekizai tags --> <link href="{% static "vendor/bootstrap/css/bootstrap.min.css" %}" rel="stylesheet"> {% endaddtoblock %} <!-- Custom styles for this template --> {% addtoblock "css" %} <link href="{% static "css/smart-learn.css" %}" rel="stylesheet"> {% endaddtoblock %} </head> {% cms_toolbar %} <!-- from cms toobar --> <body> <!-- Navigation --> <nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="container"> <a class="navbar-brand" href="/">Smart … -
Django Shell with autocomplete and colored text
About 6 months ago, I was developing with Django and could do the usual python manage.py shell, and the command line would come up with colored text, and allow me to type in a few characters, press tab, and it would suggest completions. It was a huge help for learners like me, I think. Now, it no longer does this. It's a boring black/gray terminal and tab completion doesn't work. I'm using a Python 3.9 virtual environment, Django 3.2, and Pycharm (April 21). Does the terminal show colored text and do completions for anyone else currently? If so, please share your django/python versions & setup. I would gladly replicate to get this functionality back.