Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use a value from a query into another query in django
I have the following code in my view: # default group view for group admins def adminGroupView(request): # get group id => group data and messages group_id = GroupUser.objects.get(username_id=request.user.id) groupdata = Group.objects.get(group_id=group_id) groupmessages = MessageBoard.objects.filter(group_id=group_id) groupmembers = GroupUser.objects.filter(group_id=group_id) form = SendMessageForm() context = { "groupdata":groupdata, "groupmessages":groupmessages, "groupmembers":groupmembers, "form":form } return render(request, 'base/group-admin.html', context) I keep getting a typeerror TypeError at /group/ Field 'group_id' expected a number but got <GroupUser: 9>. when i replace the group_id with a number, the code works just fine. How do i use the value from the other query. -
How to display django model column values horizontally on django template
my issue is displaying the model data on django template horizontally. I have a model named "Main" with 3 columns. When I display on the template it looks like this- I want to filter it by category that will look like this- Main.objects.filter(category='food') My goal is to show the category name on the template with the price horizontally on the side with plus signs. It should look something like this- food= 8+10+11 I tried for...in loop both on template and on views.py both failed. Tried something like this- print(f"{i.category}={i.price}+") with for loop. Didn't work. output+=f'{i.price}+' with a for loop, holding it in a variable and display that variable on template. Different combinations of those, all failed. Since += is mainly for integers, I tried with i.price without turning it into a string, failed. Most answers I found here on "displaying model data horizontally on Django template" are about using css to display form elements side by side,which I know how to do and not exactly my problem. Can anyone point me to the right direction? Here is my models.py class Main(models.Model): name = models.CharField(max_length = 60, blank = True) category = models.CharField(max_length = 60, blank = True) price = models.CharField(max_length … -
how to set up a docker with an existing database?
I have a project in Django, I want to configure my docker with an existing postgres database, but the tutorials I see are from a database without data. who could give me a guide, please It's my set up Docker-compose: services: web: build: . command: python3 manage.py migrate command: python3 manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" volumes: - .:/code depends_on: - db db: image: postgres Docker file FROM python:3.9 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code RUN pip install -r requirements.txt File setting in django project DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME':'postgres', 'USER': 'postgres', 'HOTS': 'db', 'PORT': 5432, } } -
I cannot understand why 3rd path is not activated
I am new to Django and I have no idea why this is not working. I am trying to add a new path to newyear/ but it looks as if it's just not accepting a new path. Heres the code: In setting.py you can see I added newyear app INSTALLED_APPS = [ 'hello', 'newyear', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] urls.py: (this is where the problem supposedly is) from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include("hello.urls")) path('newyear/', include("newyear.urls")) ] urls.py(for the newyear app): from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index") ] and finally views.py: import datetime from django.shortcuts import render # Create your views here. def index(request): now = datetime.datetime.now return render(request, "newyear/index.html", { "newyear": now.month == 1 and now.day == 1 }) This is the error its marking: path('hello/', include("hello.urls")) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: invalid syntax. Perhaps you forgot a comma? Sorry if I wasn't clear enough. I've been trying to solve this for hours, any help would be appreciated. Thanks! -
Getting my backend url in verification email instead of frontend url
Like the title says, I'm receiving the wrong link in an activation email and I'm not quite sure how to change it... So far I have been able to sign users up, but when they receive the account activation email, it includes the wrong url. Right now it currently includes my backend url that I used to make the post request. I am still very much new to redux and django so I'm still trying to figure out everything. I know it likely has something to do with my .env file and I believe my auth.js actions file, but I'm not a 100%. Email: You're receiving this email because you need to finish activation process on total-weather-backend.herokuapp.com. Please go to the following page to activate account: https://total-weather-backend.herokuapp.com/activate/:uid/:token However, the link is meant to go to the front end like so: https://total-weather-frontend.com/activate/:uid/:token I'm just not sure where the email is getting this url exactly. I figured it has to be from the .env and either the signup or verify action from the post request. If it is getting it from the post request, is there a way to redirect the user to the right url? I know I was using localhost:8000 … -
How to turn django into .exe that auto launches browser?
I have made a djangoproject with a venv folder. With cmd I can launch my project by: activating the environment with: venv\Scripts\activate then inside the environment: python manage.py runserver 8000 opening my browser and going to http://127.0.0.1:8000/ I am trying to turn my django project into something my client can run without having python. And that will auto start the server and open the browser link with just one click of a button. I used pyinstaller on manage.py to turn the whole thing into windows exe's, but the problem is that now when I click on that exe, it doesn't run the server. It just gives me the same output than if I'd run manage.py directly (without 'runserver'): Type 'djangoProject.exe help <subcommand>' for help on a specific subcommand. Available subcommands: [...] How do I make it so that I get an exe which does the 'runserver' command, and launches the browser? What I've tried: I thought maybe I could create another script that runs the exe, but doing djangoProject.exe runserver in cmd just gives me the error: RuntimeError: Script runserver does not exist. And I also tried doing something like writing a python script (shown below) that would do the … -
How to address "sqlite3.OperationalError: attempt to write a readonly database" In django migration when sqlite db file is writable
This is not the usual writable file problem. With a new database on django 3.2.7, sqlite 3.31.1: I can run the django shell, create an sqlite3 db directly using sqlite (using the settings DATABASE parameters). I can even stick tables in it etc. using a cursor in the shell without any problems. However, if I run django's migrate command it gives: Traceback (most recent call last): File "/tools/cliosoft/sos/7.10.p3/sos_7.10.p3_linux64/sosmgrweb/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/tools/cliosoft/sos/7.10.p3/sos_7.10.p3_linux64/sosmgrweb/venv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 381, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: attempt to write a readonly database If there is no initial sqlite3 file, the django migrate command creates a new file of zero bytes in size and gives the same error as above. The user is the same throughout and has write permission to the folder (and to the sqlite3 db file). The virtual environment is on a read only mounted volume (I'm thinking this must be somehow causing the problem) but everything else in the venv appears to be working. -
How to customize SocialAccount on django-allauth?
So, I'm integrating django-allauth on an django application. The Users table has not only email as a unique field. It has email + company, so the data might be like below: ID Email Company --------------------------------- 1 john@example.com Google 2 john@example.com Microsoft ... 9 john@example.com Apple Note that there are three accounts with the same email, but with different companies. Depending on the different interface (apple.my-app.com; google.my-app.com), John can log in to all these accounts. Now, we want to integrate SocialLogin to this app. In the current approach, django-allauth socialaccount keeps the accounts unique with unique_together = ("provider", "uid"). Each account is also linked with one single user account. See here My working approach would be unique_together = ("provider", "uid", "company"), so by that having the Social Accounts table like: User UID Provider Company --------------------------------- 1 abc GitHub Google 2 abc GitHub Microsoft 9 abc GitHub Apple Any idea how this can achieved WITHOUT FORKING THE REPO? -
django-filter: ModelMultipleChoiceFilter does not validate GET request parameter?: ValueError if not int
Problem I have a working django-filter based ModelMultipleChoiceFilter implementation (see below). A valid (and functional) request could be: http://fqdn/?authors_filter=9684 But if I get a "malicious" request, say: http://fqdn/?authors_filter=9xyz4 I get a ValueError: Field 'id' expected a number but got '9dyz4'., resulting in a ServerError with DEBUG = False. Questions Where am I missing some kind of validation/sanitizing for these kind of URL GET parameters? How can this filter validate the type (here: integer) before trying to build a queryset filter? And fail silently if the parameter is not an integer? Guesswork Perhaps the ModelMultipleChoiceFilter does not handle this validation, but another filter (eg. NumberFilter) must be used in conjunction with ModelMultipleChoiceFilter (mentioned in https://github.com/carltongibson/django-filter/issues/824#issuecomment-343942957)? But I did not manage to mix these two filters successfully... Implementation # models.py class Author(models.Model): last_name = models.CharField(max_length=255) first_name = models.CharField(max_length=255, blank=True) # filters.py class PublicationFilter(django_filters.FilterSet): authors_filter = django_filters.ModelMultipleChoiceFilter( field_name='authors__id', to_field_name='id', queryset=Author.public_objects.all(), ) class Meta: model = Publication strict = False fields = ( 'authors_filter', ) -
Ngnix Guniorn Django bare minimum site-available
My gunicorn server is running at: 123.123.123.123:8000 //my server ip and sth.sthmore.org:8000 // my domain name /etc/nginx/sites-available/mypro // mypro is a filename server { listen 80; server_name sth.sthmore.org; location / { proxy_pass http://127.0.0.1:8000; // 123.123.123.123:8000 doesn't work either proxy_set_header Host $host; // no idea what is this for proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; // no idea ... } } This comes from here : https://gunicorn.org/#deployment If i call 123.123.123.123 or sth.sthmore.org I get the default ngnix page and not the gunicorn page which runs on ...:8000. How does the right file should look like? -
tell me what it means this symbol ` ` and what programming language we can use and how we use it?
please tell me what it means for this symbol `` and what programming language we can use and how we use it? I tried a lot of documentations and I can't find answers. I'd like to know how to use it in my code. -
SMTPServerDisconnected at /auth/users/
I am currently working with Python 3.10.0 and Django 4.0 on the back end, and React/Redux on the front end. I have an app where after a user signs up, an activation email will be sent. However, the email never shows up and while visiting the backend, I see this error inside the network tab in devtools. I switched from gmail due to the work arounds that ended up not working for me so I went with SendGrid, but haven't gotten that to work yet either. From all of the posts I have seen so far, this looks right. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'api' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'email@gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True auth.js // sign up function export const signup = (email, password, re_password) => async (dispatch) => { const config = { headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, }; const body = JSON.stringify({ email, password, re_password }); try { const response = await axios.post( `${process.env.REACT_APP_API_URL}/auth/users/`, body, config ); dispatch({ type: SIGNUP_SUCCESS, payload: response.data, }); } catch (err) { dispatch({ type: SIGNUP_FAIL, }); } }; -
How to update a single column in MySQL using API from DRF
I want to auto-increment the value of the column upon URL hit using DRF class-based API. Proposed URL: /autoincrememt/<id>/ I have the functional API but it is returning 201 even the element to update is not present in the database. @api_view(['POST']) @permission_classes([permissions.IsAuthenticatedOrReadOnly]) def updateClick(request, uri_id): p = Url_data.objects.filter(uri_id=uri_id).update(clicks=F('clicks')+1) print("PPPP: ", p) url_obj = Url_data.objects.all() serializer = ClickSerializer(url_obj, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.status_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is what I wrote so far... class Increment(APIView): """ Update click count when hit. * Requires token authentication. """ permission_classes = [permissions.IsAuthenticatedOrReadOnly] def patch(self, request, uri_id, *args, **kwargs): if request.method == 'PATCH': patch_url = Url_data.objects.get(uri_id=uri_id) This is also my question asked earlier. -
How to get updates from the input field in Django
I have this code in template {% block content %} <script> function onChange(value) { console.log("log") } </script> <h3>List</h3> <input type="text" placeholder="Filter by..." onchange="onChange(this.value)" value={{ searching_value }} > But it doesn't seem to work.. -
how to bulk_create in DRF Serializer to seperate django instances
I get an array of urls and the goal is to write each url as separate model instance with other constant params that are same for all urls django model: class BlockedUrl(models.Model): url = models.URLField() date_add = models.DateField(auto_now_add=True) class Meta: app_label = 'main' db_table = 'blocked_url' ordering = ['-date_add'] django view: from main.models import BlockedUrl from api.serializers import BlockedUrlSerializer class BlockedUrlsViewSet(GenericViewSet, CreateModelMixin): queryset = BlockedUrl.objects.all() serializer_class = BlockedUrlSerializer permission_classes = (AllowAny,) django serializer: class BlockedUrlSerializer(Serializer): urls = ListField(child=URLField(), min_length=1, max_length=1024) # create - to do (iter the list of urls and insert separately into model with one transaction) def create(self, validated_data): crawler = validated_data['crawler'] blocked_urls = [BlockedUrl(url=url) for url in validated_data['urls']] return BlockedUrl.objects.bulk_create(blocked_urls) # update - raise not implemented error def update(self, instance, validated_data): raise NotImplementedError but it does not work as I get AttributeError: 'list' object has no attribute 'urls' -
Python Pillow load font file .ttf from server
I am using Pillow and I need to load a font from a server, lets say AWS, I bet its possible but I'm not sure how. font = ImageFont.truetype("https://criptolibertad.s3.us-west-2.amazonaws.com/img/fonts/Roboto-LightItalic.ttf", size=40) img_draw.multiline_text((20, 200), "Watevs", font=font, fill=(255, 0, 0)) It doesn't work. How do I load the font file from a server? OSError at /courses/certificate_preview/1 cannot open resource -
Problem in passing attribute to view section
In my settings.urls of main project, the url is as follows: path('announcements/', include('Post.urls'), {'url_type':'announcement'}) In my Post app the URL is as follows: path('all', PostList.as_view()) My view section is as follows: class PostList(generics.ListCreateAPIView): permission_classes=[permissions.IsAuthenticatedOrReadOnly] queryset = Post.objects.all() serializer_class = InstructorSupportSerializer def get_queryset(self): return self.queryset.filter(post_type = self.url_type) As per as the django documentation, url_type was supposed to be passed to view section. What am I doing wrong? Here is the error: AttributeError: 'PostList' object has no attribute 'url_type' -
Django 3.2.11 LTS admin change form and change list page shows all the models
I am using django version 3.2.11, and on change form, change list page of every model it shows all the models. I have attached the image. PS: collectstatic command is run too. -
Changes list_display when choosing different filter options
I need to change the displayed columns of django model For example, I have the following model id - user - type1 - type2 - type3 - type4 And a filter with the following fields - filter1 - filter2 - filter3 How can I display only id - user - type1 fields when filter1 is selected, when filter2 is selected, display only id - user - type2 fields, when filter3 is selected, display only id - user - type3 - type4 fields, is there such a possibility in django? -
CSRF Failed HTTP header incorrect while posting with django axios
I'm getting a 403 Forbidden error while making a post request with axios to django. CSRF Failed: CSRF token from the 'X-Csrftoken' HTTP header incorrect. I am using session authentication. GET requests works fine, but POST requests are all rejected! These are my settings: PROTOCOL = "https://" if PRODUCTION else "http://" SESSION_COOKIE_DOMAIN = ".mywebsite.com" CSRF_COOKIE_NAME = "csrftoken" CSRF_USE_SESSION = True CSRF_TRUSTED_ORIGINS = [ "http://localhost:3000", "https://mywebsite.com", "https://gestione.mywebsite.com", "https://api.mywebsite.com", ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOWED_ORIGINS = [ f"{PROTOCOL}mywebsite.{EXT}", f"{PROTOCOL}api.mywebsite.{EXT}", f"{PROTOCOL}gestione.mywebsite.{EXT}", f"{PROTOCOL}admin.mywebsite.{EXT}", "http://127.0.0.1:3000", "http://localhost:3000", ] CORS_ALLOWED_ORIGIN_REGEXES = [ r"^https://\w+\.mywebsite\.com$", r"^http://\w+\.mywebsite\.local$", ] if PRODUCTION: SESSION_COOKIE_SECURE = True MIDDLEWARE = [ "django_hosts.middleware.HostsRequestMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "django_hosts.middleware.HostsResponseMiddleware", ] and my axios configuration is: const api = axios.create({ xsrfHeaderName: "X-CSRFToken", xsrfCookieName: "csrftoken", responseType: "json", withCredentials: true, baseURL: "https://api.mywebsite.com" }); What is wrong? -
Error: That Port is already in use (Heroku/Django)
When I run heroku local on my machine I get the following error: 07:44:21 web.1 | Watching for file changes with StatReloader 07:44:22 web.1 | Error: That port is already in use. [DONE] Killing all processes with signal SIGINT 07:44:22 web.1 Exited with exit code null When I run sudo lsof -i tcp:5000 This is what I see: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME ControlCe 83303 x 19u IPv4 0x874167a5a53a48c7 0t0 TCP *:commplex-main (LISTEN) ControlCe 83303 x 20u IPv6 0x874167a5922f00af 0t0 TCP *:commplex-main (LISTEN) I've tried to kill the above processes using kill -9 but they don't seem to go away - I'm not sure if these are what are causing the issue either. Any help appreciated. -
Own django tokens authentication
I would like to have standard super user in Django app. On the other side, I have to make login system and authentication system for "users of myapp" (generate and using tokens for rest requests). So do I have to inheritate User class with my models class Worker or I can make to use tokens without that. I think that this would make that everyone can access to system as super user, because every user I make would be super user, or I have to give him some privileges? Is this necessary to inheritate AbstractBaseUser class: class Worker(AbstractBaseUser): username = models.CharField(max_length=30, unique=True, default="user") password = models.CharField(max_length=300, default="password") company = models.ForeignKey(Company, on_delete=models.RESTRICT) workerName = models.CharField(max_length=50) workerSurname = models.CharField(max_length=50) workerPhoneNumber = models.CharField(max_length=30) Or, is there any way to generate and use tokens with Worker objects, and to separate Worker accounts from super user admin account? -
Google Cloud Run, Django and "no such table" during build
I am following this tutorial to upload my existing Django project running locally on sqlite to Google Cloud Run / Postgres. I have the cloud_sql_proxy service running and can sign into Postgres. I am at the point of running the command gcloud builds submit --config cloudmigrate.yaml \ --substitutions _INSTANCE_NAME=INSTANCE_NAME,_REGION=REGION It runs for a while making good progress but then fails with: Step #2 - "apply migrations": django.db.utils.OperationalError: no such table: registration_setting Finished Step #2 - "apply migrations" ERROR ERROR: build step 2 "gcr.io/google-appengine/exec-wrapper" failed: step exited with non-zero status: 1 I do have a settings table in my registration app. But I don't understand where its missing from. Is this just the first table it's trying to create? Do I have to do something first to have it create the initial tables in Postgres? When I inspect Postgres I don't see any tables created in it. I tried wiping out my migration and pycache folders and recreating them. -
Use django-taggit package with graphene mutations
I'm using the package django-taggit with graphene-django. Initially, I was getting the error specified in this question (Don't know how to convert the Django field skills (<class 'taggit.managers.TaggableManager'>); but thanks to the answers there, I resolved the issue. However, there's another issue! I have the following mixin: class GrapheneRenderTaggitTags: """ Use this mixin to enable graphene-django correctly render django-taggit tags (as a list of strings). The corresponding model of the graphene type using this mixin should have a property `get_tags` that returns the tags of the model (e.g. obj.tags.all()) """ # Make django-taggit's TaggableManager interpretable to graphene @convert_django_field.register(TaggableManager) def convert_field_to_string(field, registry=None): print(field) print("i'm in the taggit parser function") return List(String, source='get_tags') When I use this mixin with the DjangoObjectType from graphene, it works flawlessly. However, when it comes to mutations, it raises the error Don't know how to convert the Django field skills (<class 'taggit.managers.TaggableManager'>) ! By the way, to prevent manually creating CUD mutations, I tried external packages such as graphene_django_extras, graphene_model_mutations, graphene_django_cud; but all of them raise the same error with or without the aforementioned mixin. Note that I get this error only when using the mutation classes provided by these packages. Please, what can I do to … -
How to Make Rest API Views and EndPoint URL of following Django Modol Code
it's my Django Web Code of Friend Request Functionality. We are moving to making RestAPIs of same functionalities in DjangoREST Framework. Confused how to make serializes, urls and API Views in DjangoREST API. Please Help. Code from django.db import models from userAuth.models import UserAuth class FriendList(models.Model): user = models.OneToOneField(UserAuth, on_delete=models.CASCADE, related_name="user") friends = models.ManyToManyField(UserAuth, blank=True, related_name="friends") def add_friend(self, account): """ Add a new friend. """ if not account in self.friends.all(): self.friends.add(account) self.save() def remove_friend(self, account): """ Remove a friend. """ if account in self.friends.all(): self.friends.remove(account) def unfriend(self, removee): """ Initiate the action of unfriending someone. """ remover_friends_list = self # person terminating the friendship # Remove friend from remover friend list remover_friends_list.remove_friend(removee) # Remove friend from removee friend list friends_list = FriendList.objects.get(user=removee) friends_list.remove_friend(remover_friends_list.user) def is_mutual_friend(self, friend): """ Is this a friend? """ if friend in self.friends.all(): return True return False class FriendRequest(models.Model): """ A friend request consists of two main parts: 1. SENDER - Person sending/initiating the friend request 2. RECEIVER - Person receiving the friend request """ sender = models.ForeignKey(UserAuth, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey(UserAuth, on_delete=models.CASCADE, related_name="receiver") is_active = models.BooleanField(blank=False, null=False, default=True) timestamp = models.DateTimeField(auto_now_add=True) def accept(self): """ Accept a friend request. Update both SENDER and RECEIVER friend lists. …