Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I feel lost with Django in every possible way
I am new to stack overflow so feel free to criticise if this ain't the kind of post to put on here, but I really don't know where else to ask then here where population is so big. I don't know how to start django project of my own.Yes I watched tutorials, got myself cheat sheets for django and html and am currently doing guide which explains things step by step and am doing and trying to understand as much as possible. The problem is even with all this, I've got only as far as navigating and making new directory with command prompt, loading virtual environment, running server and opening shell. I get the idea behind all the code in the guide that was written and what each line does but if you asked me to make a basic website on my own I wouldn't be able to do anything besides setting up the environment. Is there like a pattern to follow when making shit from scratch and do beginners like me even do anything from scratch or what? I have some great ideas, and while I do love coding, I am learning django for purpose of making my own … -
Custom Form Field Naming Within Loop
I'm trying to specify field names within a loop on a form, so that the fields do not overwrite themselves. Right now I'm using this in my form: class TicketForm(forms.ModelForm): class Meta: model = Ticket exclude = ['products'] class ProductForm(forms.Form): product_id = forms.IntegerField() count = forms.IntegerField() class TicketProductForm(forms.ModelForm): class Meta: model = Ticket exclude = [] for Product in Product.objects.all(): product_id = forms.IntegerField(initial=Product.product_id) count = forms.IntegerField(initial=0) The for loop within TicketProductForm currently only displays one set of fields, as product_id and count overwrite the fields over and over, only displaying for the last entry in the set of Product. Is there a way to customize field names so that I can name them, preferably with a way I can set a specifier to allow easier lookup later? -
Django admin panel does not display correctly
Good evening, I taught the django framework at the rate. Before that, the admin panel was displayed correctly, now for some reason it is displayed as I understood without css styles Default django server, writing code in pycharm And before it was displayed like this settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*ky(o6p+iw1(8u4fx$^fwnpdqt337(yw3*uk%g02b3*8(x-av$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'news.apps.NewsConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] ROOT_URLCONF = 'mysite.urls' 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', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': … -
How to run Django and Celery in separated Docker container?
I want to have two containers - one for my Django app and one for the Celery that the Django app uses. Those two containers have the same code. In my tasks.py file I have: app = Celery('myapp', broker=settings.CELERY_BROKER, backend=settings.CELERY_BACKEND) Where broker is a URL to redis. The way I start my celery app: docker build -f Dockerfile.celery -t celery_app . docker run -d -p 80002:8000 celery_app The way I start my django app: docker build -f Dockerfile.django -t django_app . docker run -d -p 8000:8000 django_app What should be CELERY_BACKEND to make it work? -
Django - Show message only when form has changed
I have a form and every time the form is updated a message is displayed "Your profile has been updated". This message is shown even if no changes has been performed in the form. How can i prevent the form to show message only when changes has been performed? views.py @login_required(login_url='login') def profilePage(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'Your account {} has been updated'.format(request.user.username)) return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'members/profile.html', context) forms.py class ProfileUpdateForm(forms.ModelForm): phone_number = PhoneNumberField(label=False, widget=forms.TextInput(attrs={'placeholder': 'Phone Number'})) image = forms.ImageField(label=False) class Meta: model = Profile fields = ['phone_number', 'image', ] Thank you for help! -
How to include Selenium tests in Github Actions?
I have a basic test like this: When I locally do: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium.webdriver.chrome.webdriver import WebDriver from selenium import webdriver class TestKundeSeite(StaticLiveServerTestCase): @classmethod def setUp(cls): cls.browser = webdriver.Chrome(r'crm\tests\chromedriver.exe') @classmethod def tearDownClass(cls): cls.browser.quit() super().tearDownClass() def test_kunde_anlegen(self): self.browser.get('%s%s' % (self.live_server_url, '/crm/kunde_anlegen')) vorname_input = self.browser.find_element_by_name("vorname") vorname_input.send_keys('Max') nachname_input = self.browser.find_element_by_name("nachname") nachname_input.send_keys('Mustermann') email_input = self.browser.find_element_by_name("email") email_input.send_keys('max@hotmail.de') telefon_input = self.browser.find_element_by_name("telefon") telefon_input.send_keys('+4917666994073') web_input = self.browser.find_element_by_name("web") web_input.send_keys('max.de') notiz_input = self.browser.find_element_by_name("notiz") notiz_input.send_keys('Beispielnotiz') self.browser.find_element_by_xpath('//input[@value="Speichern"]').click() when I do: python manage.py test it works fine. But when I push it to Github, I get the following error in Github Actions selenium.common.exceptions.WebDriverException: Message: 'crm\tests\chromedriver.exe' executable needs to be in PATH. How can I overcome this problem? I don't know how to set up a environment for Selenium Tests in Github Actions -
How can I user Django ready LoginView view in my own view?
I mean I want to use LoginView, but inside my own view function. And I want to know that how to write code of that function, that user can Login. -
Django. Url cant find view
I need help with {% url (url to template) %} when i try to open another view i see a NoRewerseMatch error. here is my html file: {% load static %} <head> <link href='{% static "navbar_style.css" %}' rel="stylesheet", type="text/css"> </head> <header> <nav class="headlist"> ---> <a href='{% url "home" %}'><img id = "img1" src="{% static 'logo.png' %}" alt="logo"></a> <ul> <li><a href="#">O nas</a></li> <li><a href="#">Kontakt</a></li> <li><a>Zajęcia</a></li> </ul> </nav> </header> my app(pages)/urls.py from django.contrib import admin from django.urls import path from . import views app_name = 'pages' urlpatterns = [ path('', views.home_view, name='home_view'), path('index/', views.index_view, name='index_view'), ] views.py import... # Create your views here. def home_view(request): listoftexts = Text.objects.order_by('-pub_date') context = { 'listoftexts': listoftexts } return render(request, 'pages/home.html', context) def index_view(request): listoftexts = Text.objects.order_by('-pub_date') context = { 'listoftexts': listoftexts } return render(request, 'pages/index.html', context) -
How to create separate model(table) for Admin User and Normal User in Django
I just want separate table for Normal User and Admin User. -
ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools
Here is the complete error i am getting while uploading on Heroku. ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-xjv_7ys0/dbus-python/setup.py'"'"'; file='"'"'/tmp/pip-install-xjv_7ys0/dbus-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /tmp/pip-record-t7juccst/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.6m/dbus-python Check the logs for full command output. -
How can I fix? while (interp->next) ^~ error: command 'gcc' failed with exit status 1
I'm trying to deploy my Django app to Heroku. So I ran into the error like: while (interp->next) ^~ error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-l9i4zubq/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-l9i4zubq/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-vgdty8_x/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.8/psycopg2 Check the logs for full command output. I don't really understand, what the problem is. -
How best to implement the logic for determining the post rank in serializer?
Now I have the serializer like: class PostTopSerializator(serializers.ModelSerializer): id_post = serializers.IntegerField(source='id') comment_count = serializers.SerializerMethodField('get_count_comment') rank = serializers.SerializerMethodField('get_rank') class Meta: model = Movie fields = ['id_post', 'comment_count', 'rank'] def get_count_comment(self, object_id): total_comments = Comment.objects.filter(movie_id=object_id).count() return total_comments def get_rank(self, object_id): return object_id.id the Post with the most comments gets rank 1, second place rank 2, and so on... And I get answer like: [ { "id_movie": 2, "comment_count": 5, "rank": 2 }, { "id_movie": 1, "comment_count": 4, "rank": 1 }, { "id_movie": 3, "comment_count": 4, "rank": 3 } ] how to implement the logic of the methoв: def get_rank(self, object_id): return object_id.id to get the same rank with the same number of comments and the output will be: [ { "id_post": 2, "comment_count": 5, "rank": 1 }, { "id_movie": 1, "comment_count": 4, "rank": 2 }, { "id_post": 3, "comment_count": 4, "rank": 2 } ] -
django HttpResponse Location redirect
I am trying to redirect to another page when http response is True I have added response['Location'] = 'login.html' but it's not working, I am getting a page with True written but not the login page. Can you help me I am new to django. I have written this code if user_obj: response = HttpResponse(True) response['Location'] = 'login.html' return response else: return HttpResponse(False) -
Python Django giving me Forbidden (403) CSRF verification failed. Request aborted
I have added {% csrf_token %} inside all my form tags like this: {% extends 'base.html' %} {% block content %} <form method="post"> {% csrf_token %} #-------------> here it is {% for field in login_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} {field.help_text}} {% endif %} </p> {% endfor %} {% for field in login_form %} {% for error in field.errors %} <p>{{error}}</p> {% endfor %} {% endfor %} {% if login_form.non_field_errors %} <p>{{login_form.non_field_errors}}</p> {% endif %} <input type="submit" value="Login"> </form> {% endblock content %} But when I actually try to login using that form and click the submit button, it should then redirect me to the home page. However, instead it is giving me the below error message: *Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that … -
js saving data entered in forms to models
i'm using the following jquery calendar to add events https://codepen.io/charlie7587/pen/eWLKaZ and i'm wondering how can i add the data entered to my models class Event(models.Model): eventName = models.TextField() NumberofPeopleInvited = models.TextField() class Meta: verbose_name = u'Event' verbose_name_plural = u'Events' -
in Django, multiple select input just returns a single value?
I have a very simple form with a "select" field. For each user in the app it creates an option field, that works fine: <select name="users" id="users" multiple> <option value="{{admin.id}}" selected>{{ admin.username }}</option> <!-- can I delete the admin from this list? --> {% for user in users %} <option value="{{user.id}}">{{ user.username }}</option> {% endfor %} </select> Now when I try to retrieve the values of "users", even if they are all selected I always just get a single value...: if request.method == "POST": title = request.POST["title"] admin = request.user project_users = request.POST["users"] print(project_users) I just get "1" or "2" but not a list? How can I retrieve all of the values from this multiple select? -
Cannot filter a query once slice has been taken django
Follow up onto: AutoField should be present but it's not (django)? related to: "Cannot update a query once a slice has been taken". Best practices? I don't need to filter objects, only order by date and select the most recent one: def get_latest_currency(self): """ Return most up to date value """ up_to_date_currency = Currency.objects.order_by('-currency_value_in_dollars_date')[:1] if not up_to_date_currency.exists(): # No objects yet; fetch currencies update_coins_table() return Currency.objects.order_by('-currency_value_in_dollars_date')[:1] up_to_date_currency is initialized correctly; the last line gives: assert not self.query.is_sliced, \ AssertionError: Cannot filter a query once a slice has been taken. This code represents a view (I want to return a plain JSON object (this is a REST endpoint)). Why is django complaining about a filter when only a slice was used? -
How do i handle an OSError?
I am getting an OSError in my python code as soon as I run the command: "(env) C:\Users\AFFAN QADRI\PROJECT>python manage.py runserver" The error message I get is as follows: OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' -
How to solve autocomplete error "NoReverseMatch at /"? I am making django project can anybody help me
model.py class Mobile(models.Model): mobile_id = models.AutoField mobile_name = models.CharField(max_length=100) views.py def autosuggest(request): print(request.GET) query_original = request.GET.get('term') queryset = Mobile.objects.filter(mobile_name__icontains=query_original) mylist=[] mylist += [x.mobile_name for x in queryset] return JsonResponse(mylist,safe=False) urls.py path("autosuggest/", views.autosuggest, name="Autosuggest"), basic.html <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $( "#search" ).autocomplete({ source: '{% url 'autosuggest' %}' }); } ); </script> I am also doing source: '{% url 'my_app_name:autosuggest' %}' in basic.html and in urls.py app_name = 'my_app_name' but it is not work. I am trying to href and another code but not working it show me NoReverseMatch at /. Reverse for 'autosuggest' not found. 'autosuggest' is not a valid view function or pattern name. -
Django Serializer - How to know which parameters was input wrongly
I always put serializers in an try statement that returns false when have invalid format. Like this: Sample model: from rest_framework import serializers class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() Sample code: try: testSerializer(data = b).is_valid() except: return HttpResponse("Invalid data type input) Now, I want to return parameters was input incorrectly like this: Parameters: Name, Email was input in wrong type -
AutoField should be present but it's not (django)?
Looking at: https://docs.djangoproject.com/en/3.1/ref/models/instances/#django.db.models.Model.save For convenience, each model has an AutoField named id by default unless you explicitly specify primary_key=True on a field in your model. See the documentation for AutoField for more details. and https://docs.djangoproject.com/en/3.1/topics/db/models/ it seems clear that an object always has an id. I have a model: class Currency(models.Model): currency_name = models.CharField(max_length=100) currency_value_in_dollars = models.FloatField() currency_value_in_dollars_date = models.DateField() def __str__(self): return self.currency_name that I've migrated as: operations = [ migrations.CreateModel( name='Currency', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('currency_name', models.CharField(max_length=100)), ('currency_value_in_dollars', models.FloatField()), ('currency_value_in_dollars_date', models.DateField()), ], ), and when trying to add entries to the db like: def update_coins_table(): if not do_greeting(): print("Gecko crypto board not reachable. Db setup") return crypto_coins_prices = cg.get_price(ids=coins_ids_str, vs_currencies='usd') timezone_now = timezone.now() for coin_key in crypto_coins_prices: coin = Currency(coin_key, crypto_coins_prices[coin_key]['usd'], timezone_now) coin.save() the line: coin = Currency(coin_key, crypto_coins_prices[coin_key]['usd'], timezone_now) gives: unable to get repr for <class 'manage_crypto_currency.models.Transaction'> and coin.save() fails. If I replace the line in question with: coin = Currency(1, coin_key, crypto_coins_prices[coin_key]['usd'], timezone_now) it works. Shouldn't the id auto increment? The last line always overwrites the previous and only one entry gets stored in the end. -
How to authorize my API requests with django google-auth?
I have implemented google-auth in my Django project, using allauth, and it works perfectly. After successful verification, I get some key from this view. from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from rest_auth.registration.views import SocialLoginView class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter { "key": "12b6e1696cdd73ddede1334f683003f63426f423" } At this point how can I authorize my other API requests by this key to identify a user on my server? Or what else I need to do ? How to use this key in my other requests ? -
send a list of items in list in json
im trying to send a list of numbers in a json.. how can i do that? im using django serializer to serialize my db model and output is this : { "id": 9, "original_code": "1144", "factory_code": "4411", "length_m": "2", "width_cm": "2", "g_m2": "5", "shrinkage_length": "12", "shrinkage_width": "15", "group": 1, "color": [ 1, 2 ] } i want to use seralizer for my input too...but the issue is seralizer accept 1 value(and when i print the result value is saved in a list) for color but when im trying to add another one i receive error... can you hellp me please? -
Django | Generate Total Price from Price per Item and Amount?
im new to Django and im playing a bit around. So i want to create a Model Field that is dynamicly showing the total price generated from the Amount and Item Price given by the User. Is there a way to do this easy? I would love to find out how that works. -
my application running both django and react when i call api cors error is occure like here
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/accounts/update. (Reason: CORS request did not succeed). XHRGEThttp://localhost:8000/api/accounts/update my django settings is CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', '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', ] and installed 'corsheaders' also bt i getting this error please help