Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I write a Django custom save method that will get or create a foreign key before saving
I have following Django models for City and State set up like this: class State(models.Model): name = models.CharField(max_length=55) abbreviation = models.CharField(max_length=2) class City(models.Model): name = models.CharField(max_length=55) state = models.ForeignKey( State, on_delete=models.CASCADE, null=True, blank=True ) I'm importing json company data that includes NAME, CITY, and STATE. It looks like this: {'NAME': 'Company Name', 'ADDRESS': '123 Main St.', 'CITY': 'Bethel', 'STATE': 'Connecticut'} I'm trying to set up a custom save method to my Company object that would get or create the necessary City object upon creating or updating the company. Creation of a City object will, in turn, require the getting or creating of a State object. class Company(models.Model): name = models.CharField(max_length=55) address1 = models.CharField(max_length=200, blank=True) address2 = models.CharField(max_length=200, blank=True) city = models.ForeignKey( City, on_delete=models.CASCADE, null=True, blank=True ) zipcode = models.CharField(max_length=20, blank=True) def save(self, *args, **kwargs): self.city, created = City.objects.get_or_create(name=city) super(Company, self).save(*args, **kwargs) Since the state field in City is not required, I'm starting with just trying to create the city. But Django is returning this error: Cannot assign "'Bethel'": "Company.city" must be a "City" instance. -
Django DRF with React: How to obtain CSRF cookie?
I have a React frontend running at frontend.example.com and a Django backend with DRF running at backend.example.com. I am using Django Session Authentication and I want to properly implement CSRF protection. Taking the React login page frontend.example.com/login as an example. It's the first time for a user to visit the page. There is a form with a user and password and on submit a new POST request is created to the Django backend. To the best of my knowledge, the CSRF token cookie should already be included in this request, right? How to obtain that CSRF token from the Django backend? I am thinking of doing a GET request to the Django backend on loading the login-page to obtain that CSRF token cookie. Is that the way to do it or is there any other best practice? -
Why am I managing two versions of a Django static file?
I'm still confused by some Django static file management and have a suspicion I'm doing something wrong/stupid. I have a core css file - /app/static/base.css But for some reason, cannot recall why, I also have - /static/css/base.css Here's everything in my settings file that I think relates to static files: PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( BASE_DIR+'/other_app_1/static/', BASE_DIR+'/other_app_2/static/', BASE_DIR+'/app/static/', ) STATICFILES_LOCATION = 'static' # uncomment and run collect static before pushing to live - python manage.py collectstatic # remember to change back for when you continue to develop #STATICFILES_STORAGE = 'custom_storages.StaticStorage' I've pasted that as it might reveal why I originally started doing this, there has to be a reason. Am I correct in thinking I can stop updating /static/css/base.css and simply use the other one? I can't recall why I started, but I'm sorry to say that I still find Django static file management very confusing. -
very unexpected IndentationError: unexpected indent in django urls.py
first this is urls.py for django project here all things are fine from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), ] but when i add my app url from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('movie/', include('movie.urls')), ] it says File "/storage/emulated/0/netflix/movie/urls.py", line 5 urlpatterns = [ ^ IndentationError: unexpected indent -
Django redis cache crsf token dont change
I try to redis cache but csrf tokens dont work now they do not change. The same csrf token always appears as the cache. my form like this; <form action="{% url "set_language" %}" method="post" class="navbar-form navbar-right"> {% csrf_token %} <div class="form-group"> <select style="border-radius: 5px;padding: 5px;"name="language" class="form-control" onchange="this.form.submit()"> {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %}selected="selected"{% endif %}> {{ language.name_local }} </option> {% endfor %} </select> </div> </form> how can i disable cache only csrf tokens? thanks. -
Django template. I want to display one views query into two columns
I want to display one query into two coulmns for explain: I have 22 elements in my query and i want to display it as 11 on the left and 11 on the right. <div class="list-group container"> <div class="list-group-item"> {% for k in kategoria %} <div class="media align-items-center"> <div class="mr-3"> </div> <div class="media-body"> <a href="{% url 'katalog:kategoria' pk=k.pk %}"> <h5 class="text-md d-block text-limit mb-2 ml-5 text-left"><u>{{k.name}}</u></h5> </div> <div class="media-body"> <a href="{% url 'katalog:kategoria' pk=k.pk %}"> <h5 class="text-md d-block text-limit mb-2 ml-5 text-left"><u>{{k.name}}</u></h5> </div> </div> {% endfor %} </div> </div> This is my code, actually my website looks like :How looks now I just want to display half of the list on the left and the second half on the right. -
AngularJS $recource query from DjangoREST
I have a Django RESTful API that goes with a MySQL DB and an AngularJS frontend. For one of the included Django Apps I created an AngularJS Service with a GET method in order to make queries from within an AngularJS Controller. I works so far, that I can retrieve an Array of all the Resource objects within the corresponding DB table, so I can iterate through it when I look for a specific entry. But I fear, the iterations are a waste of computational resources, so I was wondering, whether I could change the AngularJS Service in a way that it only returns the Object I am looking for. The DB table has a field called id, which is the only one that I can manage to access directly, so to speak. But I'd like to make a query for the entry with a chosen value in the field owner_id The following code shows how I have managed to get the above-mentioned Array: The Service for the mentioned App: angular.module('MyAPI').factory('App1', function($resource){ return $resource('/api/App1/:id', {id: '@id'}, { query: { method: "GET", isArray: true, } }); }); And this is from the corresponding Controller: angular.module('MyAPI') .controller('MyApp1Controller', function(App1, $sce,$rootScope,$scope,$state,$stateParams,$filter){ ... App1.query().$promise.then(function(data) { … -
How can I get Argumants that start with specific parameter in URL Django?
I have a Django App. I want if URL send to Django include http://127.0.0.1:8000/flower/blue/mix/2/1 get value /blue/mix/2/1. I try this pattern but not work: urls.py: path('flower/<str:queryparams>',views.flower,name='flower'), re_path(r'^flower/(?:page-(?P<page_number>\d+)/)?$',views.flower,name='flower2'), views.py: def flower(self,request,response): path = request.get_full_path()# not work print(path)# not work print(self.kwargs['parameter']) # not work print(request.get['str']) # not work print('+++++++++++++++++++++++++++++++++++++++++') return response -
Django database admin cannot login
I've deploy a django to my own VPS, My DB is SQLite3, also I've set to 777. on homepage the data from database retrieve well,but I don't know why I can't login as admin here is my settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'NAME' : '/var/www/html/mysite.com/db.sqlite3' } } Also I've try to erroring the db path but the homepage still working fine (it's should error cause I've renamed my db) Anyone can help me out? -
Unable to deploy a Django project (python3) to linode server
this is my first time trying to deploy a Django project to production so I apologize if I am making any stupid errors. I spent all of yesterday trying to deploy to a Linode server. I can run the project fine using the standard manage.py runserver. The problem occurs when I try to configure Apache to run the WSGI file when requests are coming from port 80. So the Django project is in this directory: /home/jonny/estate/estate The permissions within the directory are these: drwxrwxr-x 3 jonny jonny 4096 May 1 18:19 . drwxrwxr-x 10 jonny www-data 4096 May 1 20:29 .. -rw-rw-r-- 1 jonny jonny 389 May 1 18:07 asgi.py -rw-rw-r-- 1 jonny jonny 0 May 1 18:07 __init__.py drwxrwxr-x 2 jonny jonny 4096 May 1 18:20 __pycache__ -rw-rw-r-- 1 jonny jonny 3797 May 1 18:07 settings.py -rw-rw-r-- 1 jonny jonny 830 May 1 18:07 urls.py -rw-rw-r-- 1 jonny jonny 389 May 1 18:07 wsgi.py The parent directory is this: drwxrwxr-x 10 jonny www-data 4096 May 1 20:29 . drwxr-xr-x 7 jonny jonny 4096 May 1 19:23 .. drwxrwxr-x 4 jonny jonny 4096 May 1 18:07 api -rw-rw-r-- 1 jonny www-data 249856 May 1 20:29 db.sqlite3 drwxrwxr-x 3 jonny jonny … -
Customizing Django password_reset and _change ,recieving wrong URL at sending email
im newbie to django and programming and i have this problem : i changed the (password change and reset views) and it works fine but when i finally click on reset password it sends wrong URL inside the email . Any suggestions? Thanks URL sent its obviously wrong , if i remove the one http and it works result My URLS -
Populate form data in CreateView with get_initial() from model
I want a create form where people can select "a template" which prepoulate the form. The template is another model with the same fields. For example i have an AbstractArticle and TemplateArticle and RealArticle with the same structure. I am trying to use get_initial() to polulate the form but it takes only a dict and it is odd, because the form is quite complex (I can't get it to work with dropdown). Is there a way to supply a model instance as initial data? -
Django FSM - get_available_FIELD_transitions
Using django_fsm I need to get the available transitions a list. When using the following code I do get a <generator object get_available_FIELD_transitions at 0x10b9ba660> obj = MyModel.objects.get(pk=object_id) transitions = obj.get_available_status_transitions() print(transitions) Instead I would like to get a list of transitions, like to get a list like ['PENDING', 'CLOSED'] -
I cant pass all vaues from django Rest framework for custom user model
I created Django custom user model and added restframework to it. Custom User fields are fname, lname, email,username,password,phone ,gender,acctype. when I register user through the Django restframework, it only takes username,email and password and other field are become empty. what is the problem my models.py file from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager,User # Create your models here. GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female') ) class AccountManager(BaseUserManager): def create_user(self, email, username, phone, gender, password=None, **extrafields): if not email: raise ValueError("email is needed") if not username: raise ValueError("username is needed") if not phone: raise ValueError("Phone is needed") if not gender: raise ValueError("gender is needed") user= self.model( email=self.normalize_email(email), username=username, phone=phone, gender=gender, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,username,phone,gender,password,**extrafields): user=self.create_user( email=self.normalize_email(email), password=password, username=username, phone=phone, gender=gender, ) user.is_admin=True user.is_staff=True user.is_superuser=True user.save(using=self._db) return user class Account(AbstractBaseUser): ACCTYPE = ( ('Student', 'Student'), ('Staff', 'Staff') ) fname=models.CharField(verbose_name='fname', max_length=30) lname=models.CharField(verbose_name='lname', max_length=30) email = models.EmailField(verbose_name='E-mail', max_length=30, unique=True) username = models.CharField(verbose_name='Username', max_length=30, unique=True) last_login = models.DateTimeField(verbose_name='Last Login', auto_now=True) phone = models.CharField(verbose_name='Phone', max_length=10) gender = models.CharField(choices=GENDER_CHOICES, max_length=128) acctype = models.CharField(max_length=16, choices=ACCTYPE) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS=['email', 'phone', 'gender'] objects=AccountManager() def __str__(self): return self.username def … -
Django. Save Model Method to different model
I have a data Model and I want to save the value of amount and the value of total_amount method into payment method to have a record of payment into database. ** data/models.py ** class Data(models.Model): """ Model of Data""" user = models.ForeignKey(User, on_delete=models.CASCADE) document = models.FileField(upload_to='documents/%Y/%m/%d') uploaded_at = models.DateTimeField(auto_now_add=True) amount = models.DecimalField(default=0, max_digits=6, decimal_places=2, blank=True, null=True) def total_amount(self): return Data.objects.filter(user=self.user).aggregate(Sum('amount'))['amount__sum'] payment/models.py class Payment(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() created = models.DateTimeField(auto_now=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) amount = models.DecimalField(default=0, max_digits=6, decimal_places=2, blank=True, null=True) -
How to save default data in other fields with a POST request on DJANGO?
There is a "goods" model with the fields: "name", "quantity", "expense", "balance". on the page of the filling form there is only a "name" and "quantity"". it is necessary that, together with the given "name" and "quantity" in the database, the values in the "expense" and "balance" fields are also saved (in the "expense" by default "0", in the "balance" the same value as in the "quantity") P.s sorry for my english -
Django - Form not valid before I even confirm it
I'm working on a question creation page on my website: I have two types of questions (classical ones and CQM). To decide which question I want to create, I created a dropdown list with the two types. When I hit confirm, the dropdown list disappears and the corresponding form appears. However, when the question creation form appears, Django considers that my form isn't valid and execute the else statement before I even send the form. My three models : from django.db import models from django.contrib.auth.models import User class Choix(models.Model): CHOIX = [ ('qcm', 'QCM'), ('question', 'Question') ] Type_de_question = models.CharField(choices=CHOIX, max_length=200, default='type') class Question_Num(models.Model): num_question = models.IntegerField(default=0) question = models.CharField(max_length=1000, unique=True) reponse = models.IntegerField(default=0) class Meta: verbose_name = 'Question' verbose_name_plural = 'Questions' def __str__(self): return f'Question n°{self.num_question}' class QCM(models.Model): num_question = models.IntegerField(default=0) question = models.CharField(max_length=1000, unique=True) choix_1 = models.CharField(max_length=200, unique=True, default='') choix_2 = models.CharField(max_length=200, unique=True, default='') choix_3 = models.CharField(max_length=200, unique=True, default='') choix_4 = models.CharField(max_length=200, unique=True, default='') class Meta: verbose_name = 'QCM' verbose_name_plural = 'QCM' def __str__(self): return f'QCM n°{self.num_question}' My three forms : from django import forms from django.contrib.auth.models import User from .models import Question_Num, QCM, Point, Choix class Form_Choix(forms.ModelForm): Type_de_question = forms.Select() class Meta: model = Choix fields = … -
Settings doesn't import in other file django
I have a file with pro project settings: from .settings import * DEBUG = True ADMINS = ( ('Abdullin Marsel', 'marsel.abdullin.00@mail.ru'), ) ALLOWED_HOSTS = ['caparolcenterspb.ru','localhost','127.0.0.1'] SECRET_KEY = "бла бла" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'data', 'USER': 'caparol_admin', 'PASSWORD': '***', } } I have a file with the pro settings project in it I import the main settings, but they are not recognized, the first was the absence SECRET_KEY I added it from the main settings file and an error about no ads apps django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Which proves that the basic settings won't go wrong. I don't know what the problem is -
How to do user register function with admin approval in django
Hi i have user register function on my blog app and i'd like to make it with admin approval, i tried to set new created users as inactive but it does not work at all and i'm not sure if i have to add something do signals.py this is my base function: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in.') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form, 'register': "active" }) form.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User User.is_active = False fields = ['username', 'email', 'password1', 'password2'] signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() -
Should I use Flutter Web for a website project that shall go into production not before summer?
TL;DR Is it smart to have a website that shall go into production ~July be developed with Flutter for Web considering Flutter-based mobile apps may follow 2021? Preface: I am planning website project and will start looking for a developer this week to build an MVP. I know I want Django for the backend, but frontend-wise I am not so sure. Its my first larger website project and I am not really familiar with different frontend technologies. I guess I need to trade off between cheaper implementation of an MVP that I need to check if the idea could finance itself and something that is more expensice upfront that could last longer. In the long run, if the MVP is successful, I could imagine having native web as well. Flutter seems to be a very interesting framework to minimize development cost. However, initially it will be web only and Flutter is only in beta phase there. The options I see are: Django backend and frontend (maybe with some Angular/React/Vue directly inside the Django Templates) Django backend + Django REST Framework + Angular/React/Vue frontend Django backend + Django REST Framework + Flutter Frontend (hoping it will be stable enough by summer) … -
Remote python debug on vscode got ETIMEDOUT
Hi I want to debug django on remote docker server. Here is my attempt: version: '3' services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver --noreload 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" - "9000:9000" environment: - DJANGO_DEBUG=1 depends_on: - db Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt # COPY . /code/ manage.py { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Remote Django App", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/code" } ], "port": 9000, "host": "192.168.2.153" } ] } launch.json { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Remote Django App", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/code" } ], "port": 9000, "host": "192.168.1.15" } ] } Expected: breakpoint hit. Actually happened: ETIMEDOUT 192.168.1.15 9000 I can actually telnet 192.168.1.15 9000 with result: Content-Length: 130 {"type": "event", "seq": … -
Django Admin add/change disable a field based on previews field choice
in my django admin project i have this model: class m_pcontent(models.Model): MY_CHOICES = ( ('T', 'Text'), ('I', 'Image'), ) p_id = models.ForeignKey(m_pages, on_delete=models.CASCADE) p_type = models.CharField(max_length=1, choices=MY_CHOICES) p_content = models.TextField(null=True, blank=True) p_images = models.ForeignKey(m_pimg, on_delete=models.CASCADE, null=True, blank=True) ... and in my admin.py class m_pcontentAdmin(admin.ModelAdmin): list_display = ('p_id', 'p_type', 'p_lang', 'p_dload', 'p_active') list_filter = ('p_id', 'p_type', 'p_lang') ordering = ('p_id', 'p_type') readonly_fields = [...] i would to dinamically make readonly the p_content field or the p_images field based on what user choice in p_type fiels in ADD/change area (if chose Text p_images have to become readonly, otherwise if choose Image p_content have to become Readonly) Someone can elp me? so many thanks in advance -
Auto incrementing field name in Django
I am trying to build an app where you can, among other things, make a meal plan. I'm working on the version where you make a plan for a month. I'm using Django, writing in python, and using SQLite as my database. The problem I have is regarding user input and databases. Instead of making a form with 30 fields, I want to make one with a single field that changes its name for each time the user has entered a response. An example of this would be something like this: The first time the user enters an input: Meal day 1:_______ The second time: Meal day 2:______ In simple terms, I want the integer in the field name to change. Here's some pseudo code, it might be a mix of C# and python atm: "Day " + x x=1 if x < 30 display add button x++ elif x == 30 display add button display the confirm button x++ elif x == 31 display only the confirm button else x > 31 x = 31 Can anyone give me a template for something like this, or point me in the right direction with a function/word I can search for … -
Deleting comments from a post: NoReverseMatch while trying to delete comment of a post
I am quite new to django and web development and trying to delete the comment from posts, and has provided a class based view, but I am getting this error while running the code. Reverse for 'delete_comment' with no arguments not found. 1 pattern(s) tried: ['posts/(?P<slug>[^/]+)/(?P<comment_id>[0-9]+)/delete/$'] I have provided the comment section below and you can find the delete section towards the last. comment-section.html {{ comments.count }} Comment{{ comments|pluralize }} {% for comment in comments %} <blockquote class="blockquote"> <img style="float:left; clear: left;" class="rounded-circle article-img" height="50" width="50" src="{{ comment.user.profile.profile_pic.url }}"><a href="" style="text-decoration: none; color: black;"><h6>{{ comment.user.first_name|capfirst }} {{ comment.user.last_name|capfirst }}</h6></a><br> <p style="font-size: 8px;">{{ comment.timestamp }}</p> <p style="font-size: 14px;" class="mb-3">{{ comment.content }}</p> <a type="button" name="button" class="reply-btn ml-4"><p style="font-size: 13px;"> Reply</p></a> {% if request.user == comment.user %} <a href="{% url 'posts:delete_comment' comment.id %}" style="font-size: 13px;text-decoration: none; color: #000;" hover="background-color:red">Delete</a></td> {% endif %} views.py class DeleteCommentView(BSModalDeleteView, LoginRequiredMixin, UserPassesTestMixin): model = Comment template_name = 'posts/comment_delete.html' success_message = 'Deleted' def get_success_url(self): return reverse_lazy('posts:detail_post') def test_func(self, comment_id): comment = self.get_object(self.comment_id) if self.request.user == comment.user: return True return False urls.py path('<slug>/<int:comment_id>/delete/', DeleteCommentView.as_view(), name='delete_comment'), Please do let me know how can I let users delete their comments from the post. It was easier to delete the whole post. Thanks … -
How to get the url before render it
I would like to build a system which need to detect which urls the user opened and count the opened times. I added a dic in the urls and hope it can return the correct url the user opened to the context1 in Waitviews. But I couldn't find a correct way to obtain the correct url, (I tried to use HttpRequest.get_full_path() but it continues error. "TypeError: get_full_path() missing 1 required positional argument: 'self'") Moreover, I hope the WaitView could received the correct url and count times and then show the times on the opened page.(need the correct url before render it) So I wander if you have some suggestions on this. Really appreciate for your kind help. # urls.py ''' urlpatterns = [ re_path('get_times/.+', WaitView.as_view(), {"url": ***CORRECT_URL***}) ] ''' # views.py ''' class WaitView(TemplateView): template_name = 'wait.html' def get_context_data(self, **kwargs): context1 = kwargs.items() print(context1) '''