Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CORS not filtering anything out
I'm trying to see if CORS is working on my Django application. I call my own API from a JS static file in my project. After implementing CORS to not allow any requests to my API, I still am able to call the API successfully from my script. Shouldn't CORS reject my call since I'm not on the "ALLOWED_ORIGINS"? CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOWED_ORIGINS = [] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', .... ] INSTALLED_APPS = [ ... 'corsheaders', ] -
Uploading files in subdirectories in media directory in Django
I am using Django 3. I am trying to upload files to specific directories. location='media/dentist/diplomas/' and location='media/dentist/government_docs/' directories. But still files are directly uploaded to /media directory. But i want files to be uploaded into dentist directory under media directory. def create_account_dentist(request): if request.method == 'POST': #Upload Dentist Diploma and Government Document uploaded_file_url = "" uploaded_file_url2 = "" if request.FILES['customFileInput1']: myfile = request.FILES['customFileInput1'] fs = FileSystemStorage(location='media/dentist/diplomas/') filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) if request.FILES['customFileInput2']: myfile2 = request.FILES['customFileInput2'] fs2 = FileSystemStorage(location='media/dentist/government_docs/') filename2 = fs2.save(myfile2.name, myfile2) uploaded_file_url2 = fs.url(filename2) print(uploaded_file_url2) return redirect(reverse('dentist-section')) #Forward to Dentist Main Page return render(request, 'create-account-dentist.html') -
GraphQL Code Generator - Failed to load schema from http://localhost:8000/graphql - Request with GET/HEAD method cannot have body
I've built a GraphQL API using strawberry and strawberry-django-plus that is hosted on http://localhost:8000/graphql using Django. I am able to successfully interact with the API using GraphiQL on the localhost page. I'm now trying to access the API from my frontend using GraphQL Code Generator and React Query. When I run the command yarn graphql-codegen, the following error occurs: ✔ Parse configuration ❯ Generate outputs ❯ Generate src/generated/graphql.ts ✖ Load GraphQL schemas → Failed to load schema Load GraphQL documents Generate ❯ Generate ./graphql.schema.json ✖ Load GraphQL schemas → Failed to load schema Load GraphQL documents Generate Found 2 errors ✖ ./graphql.schema.json Failed to load schema from http://localhost:8000/graphql: Request with GET/HEAD method cannot have body. TypeError: Request with GET/HEAD method cannot have body. at new Request (mydir/.yarn/cache/undici-npm-5.6.0-b513316628-b9052c2cb9.zip/node_modules/ undici/lib/fetch/request.js:437:13) at Agent.fetch (mydir/.yarn/cache/undici-npm-5.6.0-b513316628-b9052c2cb9.zip/node_modules/ undici/lib/fetch/index.js:114:21) at fetch (mydir/.yarn/cache/undici-npm-5.6.0-b513316628-b9052c2cb9.zip/node_modules/undici /index.js:90:22) at fetch (mydir/.yarn/cache/cross-undici-fetch-npm-0.4.8-4bdc960eeb-7645fde142.zip/node_mo dules/cross-undici-fetch/dist/create-node-ponyfill.js:130:16) at fetch (mydir/.yarn/cache/cross-undici-fetch-npm-0.4.8-4bdc960eeb-7645fde142.zip/node_mo dules/cross-undici-fetch/dist/create-node-ponyfill.js:125:18) at defaultAsyncFetch (mydir/.yarn/__virtual__/@graphql-tools-url-loader-virtual-1d0d6b13ee /0/cache/@graphql-tools-url-loader-npm-7.12.0-ad4affabf8-6db87eec05.zip/node_modules/@graphql-tools/url-loader/cjs/defaultAsyncFetch.js:6:43) at mydir/.yarn/__virtual__/@graphql-tools-url-loader-virtual-1d0d6b13ee/0/cache/@graphql-t ools-url-loader-npm-7.12.0-ad4affabf8-6db87eec05.zip/node_modules/@graphql-tools/url-loader/cjs/index.js:212:36 at new ValueOrPromise (mydir/.yarn/cache/value-or-promise-npm-1.0.11-924f226d8c-13f8f2ef62 .zip/node_modules/value-or-promise/build/main/ValueOrPromise.js:14:21) at executor (mydir/.yarn/__virtual__/@graphql-tools-url-loader-virtual-1d0d6b13ee/0/cache/ @graphql-tools-url-loader-npm-7.12.0-ad4affabf8-6db87eec05.zip/node_modules/@graphql-tools/url-loader/cjs/index.js:186:20) at mydir/.yarn/__virtual__/@graphql-tools-url-loader-virtual-1d0d6b13ee/0/cache/@graphql-t ools-url-loader-npm-7.12.0-ad4affabf8-6db87eec05.zip/node_modules/@graphql-tools/url-loader/cjs/index.js:504:35 GraphQL Code Generator supports: - ES Modules and CommonJS exports (export as default or named export "schema") - Introspection JSON File - URL of GraphQL endpoint - Multiple files with type definitions (glob expression) - String in … -
Use Serializer Method Field in another Method field
In my serializer, I have a method field, that I would want to use in another method field. This will be best explained in code: class ExampleSerializer(serializers.ModelSerializer): data = serializers.CharField() analyzed_data = serializers.SerializerMethodField() analyzed_analyzed_data = serializers.SerializerMethodField() class Meta: model = DataProviderModel fields = "__all__" def get_analyzed_data(self, obj): pass def get_analyzed_analyzed_data(self): # use analyzed_data here pass So I want users to see the first step of data analysis and then analyze the same data further. Is that possible? Maybe that is something I shouldn't do? -
Why is CORS better than just checking request.headers['origin'] = 'example.com?
I'm using Django REST framework. Why is it better to use CORS framework instead of just checking that the request origin is from my own site? Why can't I just check in my view that request.headers['origin'] (exists) and request.headers['origin'] == 'example.com' as opposed to using the Django CORS framework? -
Display the README.md file content in my website
i want to display the content of the README.md file in GitHub from my repository on my website. I'm relatively new to programming so im a little bit lost. as far as i can tell: i need to input my repository URL which displays the readme.md file in the front page then access the markdown file's information and copy it (and possibly translate) into my HTML page im using Django if it makes any difference -
how to make React i18next accessing json file in django
I'm using React build folder inside Django. When React i18next uploads locales/en/translation.json from the build folder in Django I get an error as wsgiserver uploads the file as text/html instead of json. is there a way to call this file as json or make wsgiserver/django ignor upload it as json ? can i add function to this line in i18n.js to make sure it's fetched as json : backend: { loadPath: '/locales/{{lng}}/{{ns}}.json', }, i18n.js ; import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import Backend from 'i18next-http-backend'; import LanguageDetector from 'i18next-browser-languagedetector'; // don't want to use this? // have a look at the Quick start guide // for passing in lng and translations on init const Languages = ['ar', 'en', 'fr'] i18n .use(Backend) .use(LanguageDetector) .use(initReactI18next) // passes i18n down to react-i18next .init({ lng: 'en', react: { useSuspense: true, }, // the translations // (tip move them in a JSON file and import them, // or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui) supported: ["en", "fr", "ar"], fallbackLng: "en", detection: { order: ['path', 'cookie', 'htmlTag', 'localStorage', 'subdomain'], caches: ['cookie'], }, debug: true, whitelist: Languages, interpolation: { escapeValue: false, // not needed for react as it escapes by default … -
Django: Change Queryset of already defined Prefetch object
Context I really want to, but I don't understand how I can limit an already existing Prefetch object Models class MyUser(AbstractUser): pass class Absence(Model): employee = ForeignKey(MyUser, related_name='absences', on_delete=PROTECT) start_date = DateField() end_date = DateField() View class UserAbsencesListAPIView(ListAPIView): queryset = MyUser.objects.order_by('first_name') serializer_class = serializers.UserWithAbsencesSerializer filterset_class = filters.UserAbsencesFilterSet Filter class UserAbsencesFilterSet(FilterSet): first_name = CharFilter(lookup_expr='icontains', field_name='first_name') from_ = DateFilter(method='filter_from', distinct=True) to = DateFilter(method='filter_to', distinct=True) What do I need With the Request there are two arguments from_ and to. I should return Users with their Absences, which (Absences) are bounded by from_ and/or to intervals. It's very simple for a single argument, i can limit the set using Prefetch object: def filter_from(self, queryset, name, value): return queryset.prefetch_related( Prefetch( 'absences', Absence.objects.filter(Q(start_date__gte=value) | Q(start_date__lte=value, end_date__gte=value)), ) ) Similarly for to. But what if I want to get a limit by two arguments at once? When the from_ attribute is requested - 'filter_from' method is executed; for the to argument, another method filter_to is executed. I can't use prefetch_related twice, I get an exception ValueError: 'absences' lookup was already seen with a different queryset. You may need to adjust the ordering of your lookups.. I've tried using to_attr, but it looks like I can't access it … -
Model Relationship django
I'd appreciate your help. I have two models. In the Bids model you will find current_bid_cmp. I would like from the ListingAuctions model to be able to access the corresponding current_bid_cmp of the Bids model. I only have found information to do querys from the model which contains the foreingKey. My view: I use get_context_data because I have been trying anothers querys. perhaps its not the more aproppiate class index(ListView): model = ListingAuctions template_name = "auctions/index.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['object'] = ListingAuctions.objects.all() return context My Models: class ListingAuctions(BaseModel): title_auction = models.CharField('Title of the auction',max_length = 150, unique = True) description = models.TextField('Description') user = models.ForeignKey(User, on_delete = models.CASCADE) category = models.ForeignKey(Category, on_delete = models.CASCADE) initial_bid = models.FloatField(default=False) content = models.TextField('Content of auction') image = models.ImageField('Referential Image', null=True, upload_to = 'images_auctions', max_length = 255, default= 'noimage.png') class Bids(BaseModel): user = models.ForeignKey(User, on_delete = models.CASCADE, related_name='offer_user') listing_auctions = models.ForeignKey(ListingAuctions,null=True, on_delete= models.CASCADE, related_name='l_auctions') initialized_bid = models.BooleanField(default=False) current_bid_cmp = models.FloatField('Current Bid Cmp',blank=True, null=True ) offer = models.FloatField(default=0 ,null=True, blank=True) My HTML Current bid: $ {{post.l_auctions.current_bid_cmp}} its my attemp l_auctions is the relate name from listing_auctions in Bids model. Post is a ListingAuction object: {% for post in object_list %} <div class=" … -
I am trying to python manage.py runserver but keep getting the Django ModuleNotFoundError: No module named 'website.settings'
This is the first time that I use django for my website. I have been 5 hours trying to figure out the django and still haven't gotten to the HTML. I have had this same error (no module named 'website.settings' for the past 3 hours. I have been trying everything and looked it up various times but don't know what to do. Any help? here I append my whole github repository. You should be able to download it. Thanks -
I want to learn Full stack development what to do? [closed]
I want to be a full-stack web developer, I have learned HTML, a little bit of CSS, and currently learning Django. Should I learn React and javascript to get handy with the front end? Will I be able to get jobs on the internet or companies? -
Django static tag on css(style-bg-image)
so I am trying to make a webpage in django everything works well -> {% static 'website/img/core-img/s1.png' %} but when I try to do static style="background-image: url({% static 'website/img/bg-img/1.jpg'%}); it gives me those stupid errors althougt it seems to be fine according to my googling skills... so please help me static tag -
Getting Subtitles from ccextractor binary
How can I get subtitles of a video using ccextractor binary in our Django project? -
Django deploy to heroku: fatal: could not read Username for 'https://github.com': No such device or address
I am deploying a Django website to Heroku. The website project uses several standalone Django apps, which are in private Github repositories. This is what my requirements.txt file looks like for my website project: requirements.txt asgiref==3.5.0 Babel==2.9.1 certifi==2021.10.8 charset-normalizer==2.0.12 coverage==6.4.1 dj-database-url==0.5.0 Django==3.2 django-appconf==1.0.5 django-crispy-forms==1.14.0 django-js-asset==2.0.0 gunicorn==20.1.0 idna==3.3 psycopg2-binary==2.9.3 python-decouple==3.6 pytz==2022.1 requests==2.27.1 six==1.16.0 sqlparse==0.4.2 urllib3==1.26.9 webencodings==0.5.1 whitenoise==6.0.0 django-app1 @ git+https://github.com/MyUserName/django-app1.git@main django-app2 @ git+https://github.com/MyUserName/django-app2.git@main # #... truncated for brevity When I run git push heroku main this is the console output: remote: -----> Installing pip 22.1.2, setuptools 60.10.0 and wheel 0.37.1 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting django-app1@ git+https://github.com/MyUserName/django-app1.git@main remote: Cloning https://github.com/MyUserName/django-app1.git (to revision main) to /tmp/pip-install-l1stp7n7/django-app1_3d3e9f55670d48a6bf618c93771a0885 remote: Running command git clone --filter=blob:none --quiet https://github.com/MyUserName/django-app1.git /tmp/pip-install-l1stp7n7/django-app1_3d3e9f55670d48a6bf618c93771a0885 remote: fatal: could not read Username for 'https://github.com': No such device or address remote: error: subprocess-exited-with-error remote: I have configured GitHub integration in the Deploy tab of apps in the Heroku Dashboard - but I can't figure out how to add more than one app (i.e. repository). How do I resolve this error, so I can push to heroku? -
Django : Automatically add user to group with signals
I am currently try to add users automatically to a particular group using signals. It works when I edit the user fields but not when I add a group to it. @receiver(pre_save, sender=User) def addToPiloteGroup(sender, instance, *args, **kwargs): group = Group.objects.get(name='Pro') instance.groups.add(group) # => doesn't work instance.last_name = 'some name' # => works print('user has been group : ' + group.name) -
AttributeError: 'str' object has no attribute '_meta' when attempting to use Many to Many field on self with through model - Django
Django version - 4.0.4 I am making a recipe engine website and I am trying to create a table Ingredient where each ingredient may have substitutable ingredients. For example, ingredient "acorn squash" has the following substituable ingredients: ingredient title: butternut squash. Conversion: 1 cup acorn squash = 1 cup butternut squash ingredient title: pumpkin. Conversion: 1 cup acorn squash = 1 cup pumpkin To achieve this, I have a class Ingredient and a class SubstitutableIngredient in models.py. I use a many to many field in Ingredient which uses "through" to link to the SubstitutableIngredient table, as I have extra fields such as "conversion". I use 'self' as a substitutable ingredient is still an ingredient. When attempting to makemigrations or migrate, I get the following error: AttributeError: 'str' object has no attribute '_meta' when attempting to makemigrations or migrate. Stack trace shown further below. My code in Models.py is: from django.db import models # Create your models here. class Ingredient(models.Model): title = models.CharField(max_length=200, unique=True) # unique field. There may only be one ingredient in the database with the same title. # many to many field substitutableIngredients = models.ManyToManyField( 'self', through='SubstitutableIngredient', through_fields=('originalIngredient', 'newIngredient'), ) def __str__(self): return self.title class SubstitutableIngredient: originalIngredient = … -
Altering model after field validation
I'm implementing a tagging system. Currently, the models look like this: class Tag(models.Model): label = models.CharField(max_length=MAX_TAG_LENGTH) class TagManager(models.Model): tags = models.ManyToManyField(Tag, related_name="referrers") def associate_tag(self, tag_label: str): . . . And I have a custom field that cuts its input on commas so the user can enter tags as a comma-separated list: class TagsField(forms.CharField): def to_python(self, value): if not value: return [] return [tag.strip() for tag in value.split(',')] Finally, I have the model and form where these are used: class Thing(models.Model): tags = models.OneToOneField(TagManager, on_delete=models.SET_NULL, null=True) class ThingForm(forms.ModelForm): tags = TagsField(widget=forms.TextInput(attrs={"placeholder": "Tags", "required": False})) class Meta: model = Thing fields = ["tags"] Problem My issue is that if I populate and validate the form: form = ThingForm(data={"tags": ["One", "Two"]}) form.is_valid() I get errors: {'tags': ["“["One", "Two"]” value must be an integer."]} Which I'm guessing is because it's trying to place the stringified list in the OneToOneField, which isn't going to work. What I really need to do is after validating the field, I need to iterate the results of to_python, and call thing_instance.tags.associate_tag on each of the validated tag strings. Is there a "hook" method on forms that will allow me to do this cleanly? I've read over the docs and … -
Error with CMD ["gunicorn", "foodgram.wsgi:application", "--bind,", "0:8000"] comand
I'm using docker-compose to run containers. backend container keeps restarting with error: standard_init_linux.go:228: exec user process caused: exec format error dockerfile: FROM python:3.8-slim WORKDIR /app COPY requirements.txt . RUN pip install --upgrade pip RUN pip install -r requirements.txt --no-cache-dir COPY . /app CMD ["gunicorn", "foodgram.wsgi:application", "--bind,", "0:8000"] i have tryed CMD ["gunicorn", "foodgram.wsgi:application", "--bind,", "0:8000"], CMD gunicorn foodgram.wsgi:application --bind 0:8000 same error docker-compose.yml version: '3.3' volumes: postgres_data: static: media: static_value: media_value: frontend_data: services: db: image: postgres:12.4 volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ../backend/.env backend: image: mastermind777nest/foodgram:latest restart: always volumes: - static_value:/app/static/ - media_value:/app/media/ depends_on: - db env_file: - ../backend/.env frontend: build: context: ../frontend dockerfile: Dockerfile volumes: - ../frontend/:/app/result_build/ nginx: image: nginx:1.19.3 ports: - "10080:80" - "10443:443" volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf - ../frontend/build:/usr/share/nginx/html/ - ../docs/:/usr/share/nginx/html/api/docs/ - static:/app/static/ - media:/app/media/ - static_value:/var/html/static/ - media_value:/var/html/media/ restart: always depends_on: - backend - frontend -
Django : submitting Foriegn key field with or without form object to models
we can submit foriegnkey data to models through ModelForm class BooksForm(forms.ModelForm): class Meta: model = Books fields = "__all__" where in templates we can add {{form.author}} (author is foriegnkey field in books model) Im aware that we can submit foriegnkey data using forms like this but my question is.is there any way where we can submit a foriegnkey object which we have fetched using some other method (with or without form ) to a model(in my case its book) Let me explain it in detail lets say for instance there is a Search bar when users search for author, then the function fetches list of authors (choice field) to the user where user can select and submit which should get populated in the books model there isnt any proper info related to this on web all i could see is information on how to save data with Foriegnnkey using model form any kind of insights is appreciated -
Why is CSS not working even I use 'runserver' command in Docker?
I am trying to develop a web application using Django in Docker. I made a DockerFile and a docker-compose.yml file as below to check the code in the development environment. Even though I'm using the runserver command in the file, when I start the container and access the localhost, the CSS for the admin page isn't working. How should I change the codes to make it work? Here are the codes: Dockerfile FROM python:3.8.3-alpine WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY . . docker-compose.yml version: '3.7' services: web: build: ./django_project command: python manage.py runserver 0.0.0.0:8000 volumes: - ./django_project/:/usr/src/app/ ports: - 8000:8000 docker desktop: 4.1.1 Python: 3.8 Django: 3.0 -
Django Custom User Model - admin customization
So, I was making a custom user model, and to be able to change the password using the admin page I did this on the UserAdminChangeForm, is it wrong? I mean dealing with the security. password = ReadOnlyPasswordHashField( label=_("Password"), help_text=_( "Raw passwords are not stored, so there is no way to see this " "user’s password, but you can change the password using " '<a href="../password">this form</a>.' ), ) -
Pass variable in to template in django
Can anyone help me to solve my Problem, I'm trying to pass a variable from my view to my Template. But the variable does not show up when I load my the site. Model: class Artikl(models.Model): name = models.CharField(max_length=100) description = models.TextField() category = models.CharField(max_length=60) price = models.PositiveIntegerField() author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name Views: from django.shortcuts import render from .models import Artikl def home(request): context = { 'artikl': Artikl.objects.all() } return render(request, 'base/home2.html', context) Template: {% for artikl in Artikl %} <div class="row g-4"> <div class="col-md-6 col-lg-3"> <div class="card bg-light"> <div class="card-body text-center"> <img src="https://picsum.photos/300/200" class="mb-3 img-fluid" alt=""> <h3 class="card-title mb-3">{{ artikl.name }}</h3> <p class="card-text">{{ artikl.description }}</p> <button type="button" class="btn btn-primary">Kupi</button> </div> </div> </div> {%endfor%} -
Django - run flows
assist please with questions for beginner. Haven't managed to find someth simillar. I have some specific flow with 3 steps (scripts) are being performed on remote server via ssh. How to organize a view that will call the Flow and update its template accordingly to completting each step of the flow like: Step 1: Done Step 2: in process How can I screen ssh connection's output? Like i enter ip, command and by "Run" pressing receive realtime updated data (script's output) in template. -
Concurrent operations on django and database
I am developing on Django 3 system. I am using mysql at backend. I have a design question. I have a system of doctors and patients. The patient is registered in the system. Doctors see the patient on their page and push a button and take patient. When 3 doctors open their pages at the same time, all of them will see the patient named Jennifer. Well, if they press the get jenifer patient button at the same time, wouldn't there be a conflict? How do I prevent this? What can i do for this concurrent operation to prevent exceptions. -
Display form error in respective field form
Is possible to display form error in their respective field error form? And if not how can custom a field name on raise field error? E.g. i have a signup/login system where i use email field as a ìdentifier. This becouse i use a custom signup/login system, with BaseUserManager and AbstractBaseUser, like: models.py class User(AbstractBaseUser): username = models.CharField( verbose_name = u'Nome', max_length=33 ) #identifier email = models.EmailField( verbose_name = u'Email', max_length=255, unique=True, ) #.... forms.py class LoginForm(AuthenticationForm): username = forms.EmailField( label="Email", required=True, widget=forms.TextInput( attrs={'placeholder': 'Email'} )) password = forms.CharField( label=False, max_length=50, required=True, widget=forms.PasswordInput( attrs={'placeholder': 'Senha'} )) class Meta: model = User fields = ['email', 'password'] The problem is, when usernamefield form have an error, the message display : username...error, but i need show Email...error, preferably inside respective field. Even with verbose_name = u'Email' in model.field, the error message display username...errror... So: 1- How can i display error inside respective form.field as placeholder or value and 2 - How customize the form.field.name.error when reise error?