Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to debug Request body or attributes from spyne
from spyne import ComplexModel, String, Integer, Date, Boolean, Decimal, DateTime, ByteArray, Array country_code = String(max_len=2).customize( max_occurs=1, min_occurs=0, pattern='[A-Z]') guid = String(max_len=36).customize(min_occurs=0, max_occurs=1, pattern='[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}') send_date_time = DateTime.customize(min_occurs=0, max_occurs=1) status = String.customize(max_occurs=1, min_occurs=0) status_code = Integer.customize(max_occurs=1, min_occurs=0) inspector = String(max_len=255).customize(max_occurs=1, min_occurs=0) class Transport(ComplexModel): __namespace__ = '' name = String(max_len=255).customize(max_occurs=1, min_occurs=0) number = String(max_len=1024).customize(max_occurs=1, min_occurs=0) country_code = country_code declared_type = String(max_len=100).customize(max_occurs=1, min_occurs=0) declared_type_code = Integer arrival_date_time = DateTime() arrival_place = String(max_len=512).customize(max_occurs=1, min_occurs=0) document = String(max_len=255).customize(max_occurs=1, min_occurs=0) document_date = Date() document_number = String(max_len=255).customize(max_occurs=1, min_occurs=0) class Disinfection(ComplexModel): __namespace__ = '' date = DateTime(nillable=True) method = String(max_len=100).customize(max_occurs=1, min_occurs=0) chemical = String(max_len=100).customize(max_occurs=1, min_occurs=0) temperature_times = String(max_len=100).customize( max_occurs=1, min_occurs=0) concentration = String(max_len=100).customize(max_occurs=1, min_occurs=0) additional_info = String(max_len=2000).customize( max_occurs=1, min_occurs=0) class ProductDescription(ComplexModel): __namespace__ = '' name_rus = String(max_len=1024).customize(max_occurs=1, min_occurs=0) name_eng = String(max_len=1024).customize(max_occurs=1, min_occurs=0) name_botanic = String(max_len=1024).customize(max_occurs=1, min_occurs=0) code = String(max_len=1024).customize(max_occurs=1, min_occurs=0) hs = String(max_len=512).customize(max_occurs=1, min_occurs=0) hs_code = String(min_len=4, max_len=10).customize( max_occurs=1, min_occurs=0, pattern='[0-9]') origin_place = String(max_len=512).customize(max_occurs=1, min_occurs=0) origin_country = String(max_len=100).customize(max_occurs=1, min_occurs=0) origin_country_code = String(max_len=2).customize( max_occurs=1, min_occurs=0, pattern='[A-Z]') packages = Integer.customize(max_occurs=1, min_occurs=0) packages_unit = String(max_len=100).customize(max_occurs=1, min_occurs=0) packages_unit_code = String(max_len=3).customize( max_occurs=1, min_occurs=0) marking = String(max_len=255).customize(max_occurs=1, min_occurs=0) expert_opinion_date = Date() expert_opinion_number = String( max_len=255).customize(max_occurs=1, min_occurs=0) expert_samples = String(max_len=4096).customize(max_occurs=1, min_occurs=0) additional_info = String(max_len=1024).customize( max_occurs=1, min_occurs=0) class CertificateMinimumType(ComplexModel): __namespace__ = '' id = Integer.customize(min_occurs=0, max_occurs=1) guid … -
How to make different database settings for local development and using a docker
There is a django project that uses dockerisation to run in a production environment. The settings are as follows docker-compose.yaml version: "3.9" services: web: build: . ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/gpanel depends_on: - db db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data environment: - POSTGRES_USER=${DATABASE_USER} - POSTGRES_PASSWORD=${DATABASE_PASS} - POSTGRES_DB=${DATABASE_NAME} volumes: postgres_data: settings.py DATABASES = { "default": { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env('DATABASE_NAME'), 'USER': env('DATABASE_USER'), 'PASSWORD': env('DATABASE_PASS'), 'HOST': env('HOST'), "PORT": env('PORT'), } } .env DATABASE_NAME=pg_db DATABASE_USER=db_root DATABASE_PASS=12345 PORT=5432 HOST=db So in settings.py the host parameter is passed as services name 'db' in the docker-compose.yaml file. This all works when running via docker, but I need to be able to run the project locally without docker. In the standard way for Django using a virtual environment. For this I created locally new database and user. The problem is that when running the command python manage.py runserver I'm getting error django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution -
How to fix Django Messages Attribute Error
I'm using django messages for handling messages on my django project site. I'm developing cryptography project, whenever I try to run my project while going on decrypt function I get following error enter image description here my Decryption function of views.py is def textDecode(request): form = DecryptForm() if request.method == "POST": form = DecryptForm(request.POST) if form.is_valid(): try: encText = str(request.POST.get("encText")) encText = encText.replace(" ", "") encText = encText.replace("\n", "") q = AllData.objects.filter(finder = request.POST.get("finder"), encText=encText).first() d = ast.literal_eval(q.keys) finderLen = len(request.POST.get("finder")) encTextLen = len(encText) i = 0 data = "" while i <= encTextLen: encText_parts = encText[i : i + finderLen] for key,val in d.items(): if val == encText_parts: data += chr(key) i += finderLen messages.success(request, "Your decrypted text:") messages.success(request, "----------xxx----------") messages.success(request, data) messages.success(request, "----------xxx----------") return redirect('/textDecoded') except: messages.warning(request, 'Incorrect password or text.') return redirect('/textDecode') else: messages.success(request, "Incorrect password or text") return redirect('/textDecode') return render(request, 'home/textDecode.html', {'form': form}) and textDecoded.html, <div class="container"> {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %}class="{{message.tags}}"{% endif %}>{{message}}</li> {% endfor %} </ul> {% endif %} </div> I've been trying to fixed this but yet no success. How can I get rid of these error? -
How do i use the ForeignKey in Choices?
Here is my models.py class Devtool(models.Model): name = models.CharField(max_length=50, verbose_name='이름') kind = models.CharField(max_length=50, verbose_name='종류') content = models.TextField(verbose_name="개발툴 설명") class Post(models.Model): # devtool_CHOICES = ( # ('django', 'django'), # ('react', 'react'), # ('spring', 'spring'), # ('node.js', 'node.js'), # ('java', 'java'), # ('C++', 'C++'), devtool = models.ForeignKey(choices=Devtool.name, verbose_name="예상 개발툴", null = True) I want to replace devtool_CHOICES to "Devtool.name" How can I do? -
Nginx static not found 404
I am making an application in django. I added docker today, but I have a problem with static files. After using collectstatic, the files are copied to app_static, but in the console it appears: 2: No such file or directory, and a 404 error pops up in the browser. I can only access to /static/admin/css, but my css file is in /static/css, which also shows 404. nginx.conf: worker_processes 4; events { worker_connections 1024; multi_accept on; use epoll; } http { ## # Basic Settings ## charset utf-8; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 0; types_hash_max_size 2048; server_tokens off; client_body_timeout 300; client_header_timeout 300; client_max_body_size 64m; send_timeout 300; fastcgi_buffer_size 128k; fastcgi_buffers 256 128k; fastcgi_send_timeout 900s; fastcgi_read_timeout 900s; proxy_read_timeout 900; proxy_ignore_client_abort on; uwsgi_buffer_size 32k; uwsgi_buffers 8 32k; uwsgi_busy_buffers_size 32k; uwsgi_read_timeout 900; uwsgi_send_timeout 900; uwsgi_connect_timeout 60; client_header_buffer_size 10k; large_client_header_buffers 16 10k; ignore_invalid_headers on; underscores_in_headers on; include /etc/nginx/mime.types; default_type application/octet-stream; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 7; gzip_buffers 64 8k; #gzip_min_length 1024; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml; upstream localhost { server web:8000; } server { listen 80; location / … -
The virtual environment is not activated in the pycharm terminal
I use pycharm, but my power shell does not recognize the virtual environment? What do you think I should do so that he can recognize the virtual environment? And that this happened after I moved my django project folder to another folder terminal setting : And that my virtual environment is recognized by pycharm and the application runs, but when testing the terminal, it does not recognize my virtual environment. -
using selenium I get some errors: TypeError: expected str, bytes or os.PathLike object, not NoneType
When I run a test case python3.9 manage.py test in django webapp I get some errors. System check identified no issues (0 silenced). test_login (pygiustizia.tests.test_views_topics.ViewsTopicsTestCase) ... nel costruttore model Users Traceback (most recent call last): Traceback (most recent call last): Traceback (most recent call last): File "/usr/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1662, in __call__ return super().__call__(environ, start_response) Traceback (most recent call last): File "/usr/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/usr/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1662, in __call__ return super().__call__(environ, start_response) File "/home/nicola/.local/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 132, in __call__ response = self.get_response(request) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1662, in __call__ return super().__call__(environ, start_response) File "/home/nicola/.local/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 132, in __call__ response = self.get_response(request) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1645, in get_response return self.serve(request) File "/usr/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/home/nicola/.local/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 132, in __call__ response = self.get_response(request) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1645, in get_response return self.serve(request) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1657, in serve return serve(request, final_rel_path, document_root=self.get_base_dir()) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1657, in serve return serve(request, final_rel_path, document_root=self.get_base_dir()) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1645, in get_response return self.serve(request) File "/home/nicola/.local/lib/python3.9/site-packages/django/test/testcases.py", line 1657, in serve return serve(request, final_rel_path, document_root=self.get_base_dir()) File "/home/nicola/.local/lib/python3.9/site-packages/django/views/static.py", … -
NameError: name '_mysql' is not defined on Mac A1 Monterey
I am trying to include mysql into my django and face the error of in <module> version_info, _mysql.version_info, _mysql.__file__ NameError: name '_mysql' is not defined I think this might be an error due to the new M1 chip and mac OS system, but I can't figure out how to fix it. (I am using mac Monterey with M1 chip.) Here is the package version: mysql-connector-python 8.0.29 mysqlclient 2.1.1 mysql Ver 8.0.29 for macos12.2 on x86_64 (Homebrew) Python 3.8.9 I've read it somewhere about my python needs to be at the homebrew directory, but not sure how to do it. which python3 /usr/bin/python3 I've also seen other solution of using arch -x86_64 brew install mysql It didnt work for me. here is my .zshrc file now export PATH="/usr/local/opt/python/libexec/bin:$PATH" export PATH="/usr/local/opt/mysql-client/bin:$PATH" export DYLD_LIBRARY_PATH="/usr/local/mysql/lib:$PATH" export PATH="/usr/local/opt/python@3.8/bin:$PATH" and here is my bash_profile export PATH="/usr/local/opt/python/libexec/bin:$PATH" export PATH="/Applications/Sublime Text.app/Contents/SharedSupport/bin:$PATH" export PATH="/usr/local/opt/mysql-client/bin:$PATH" -
How to send email list over django using model's ArrayField
I habe a Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) email_list = ArrayField( models.CharField(max_length=255, blank=True), blank=True, default=list, ) When Users join or leave Groups, I have their email either added or removed from the email_list via this view: def join_group(request, pk): id_user = request.user.id group = Group.objects.get(id=request.POST.get('group_id')) account = Account.objects.get(user_id=id_user) if group.joined.filter(id=request.user.id).exists(): group.joined.remove(request.user) account.joined_groups.remove(group) group.email_list.remove(account.user.email) else: group.joined.add(request.user) account.joined_groups.add(group) group.email_list.append(account.user.email) return HttpResponseRedirect(reverse('group_detail', args=[str(pk)])) And this works to the best of my knowledge. The issue comes when I want to send a mass email out to everyone in the mailing list. I have a url path('group/<int:pk>/notifications/', notifications, name='send_notifications'), that I access from my GroupDetail view: <a href="{% url 'send_notifications' group.pk %}">SEND NOTIFICATIONS</a> But I get this error when trying to render my notifications view: Group matching query does not exist. The reason I didn't ask about this error is because I believe I know where the issue is coming from -- the first line in my notifications view: def notifications(request, pk): group = Group.objects.get(id=request.POST.get('group_id')) if request.method == 'POST': subject = request.POST['subject'] message = request.POST['message'] recipients = group.email_list for recipient in recipients: send_mail ( subject, message, NOTIFICATION_EMAIL, [recipient], fail_silently=False ) return render(request, … -
Test a data migration ManyToMany in Django
I tried to add a field to my ManyToMany relationship models in Django. So step by step, I created the new model and apply makemigrations and migrate. I checked I have the new table in my postgresql database. Now before I will add the through keyword in the ManyToMany field I want to write a function in the migration file that will copy the old data of the previous ManyToMany table to the new one with the additional field. I followed a solution explained here: Django migration error :you cannot alter to or from M2M fields, or add or remove through= on M2M fields I want to test the function that will migrate the data in a test function but I don't understand to do. here my code: survey/models: class Survey(BaseModel): name = models.CharField(max_length=256, help_text='Survey name') user = models.ManyToManyField(User, blank=True, help_text='patient') survey/models: class SurveyStatus(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) survey = models.ForeignKey(Survey, on_delete=models.CASCADE) survey_status = models.CharField(max_length=10, blank=True, null=True, choices=STATUS_SURVEY_CHOICES, ) The function I wrote that need to copy the data from the previous M2M to the new one is the following one: def create_through_relations(apps, schema_editor): Survey = apps.get_model('survey', 'Survey') SurveyStatus = apps.get_model('survey', 'SurveyStatus') for survey in Survey.objects.all(): for user in survey.user.all(): … -
How do I get all the commented TV and movie scores in descending order?
What we want to achieve I want to display stars (SCORE) in descending order on my Movie and TV models. Current state I have been retrieving data from TMDB to get movie and TV data. Then when the user puts in comments and scores, that movie or TV gets its own Model created. Questions to ask I choose the opition score in the html select Then when the score is chosen, data = requests.get (f "https://api.themoviedb.org/3/tv/{tv_id}?api_key={TMDB_API_KEY}&language=en-US") or data = requests.get (f "https://api.themoviedb.org/3/movie/{movie_id}?api_key={TMDB_API_KEY}&language=en-US") for IDs stored in your own Movie and TV models Search. How can I sort those movies and TVs in descending order of stars (score) and display them in html? important point If you choose another option in select, movies and TV will be displayed as described in javascirt. current code def index(request): # Render the template query = request.POST.get('media_type') print(query) return render(request, 'Movie/index.html') class Movie(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_movie.objects.filter(movie_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars class TV(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length … -
Celery configuration on uwsgi not working
I have a Django project that I'm trying to move on my production VM. I'm using uWSGI and nginx and I succeeded in configuring it so that my website is available. Now I'm trying to start my Celery worker which is also needed. I saw on uWSGI docs that in order to configure Celery, the following should be added to the configuration file : [uwsgi] master = true socket = :3031 smart-attach-daemon = /tmp/celery.pid celery -A tasks worker --pidfile=/tmp/celery.pid I then ended up with this : [uwsgi] chdir = /home/xxx/ScriptsApp/src/ module = main.wsgi home = /home/xxx/ScriptsApp/venv master = true processes = 10 socket = /home/xxx/ScriptsApp/src/scriptsApp.sock chmod-socket = 666 vacuum = true daemonize = /home/xxx/uwsgi-emperor.log # Celery smart-attach-daemon = %(chdir)tmp/celery.pid celery -A main worker --pidfile=%(chdir)tmp/celery.pid However, when running it, Celery isn't running, while if I run celery -A main worker in my virtual environment, Celery is correctly running. I've just started using linux/uwsgi so I may have messed up somewhere in the process but I'm unable to find where, even though I've tried every possible solutions that I found. Thanks in advance for your help ! -
Way to deploy django with webpack loader with vue.js
while I was working on a project in django integrated with vue js via webpack. https://github.com/django-webpack/django-webpack-loader I had a doubt about the deployment. Are there any services that allow this? For django I have always used pythonanywhere as hosting but in this case is it possible? Are there any hosting services that allow django to easily deploy with the webpack loader with vuejs? -
ERROR: No matching distribution found for whitenoise-6.2.0
While trying to push to heroku I get this error: ERROR: No matching distribution found for whitenoise-6.2.0 Heroku is currently on Python 3.10. Locally I have 3.9, but this is within the scope mentioned in the whitenoise docs. http://whitenoise.evans.io/en/stable/index.html#compatibility When this error says no 'matching distribution' - matching what? Python? Django? Some other dependency? Heroku? Please advise. Thx. -
Which Django field should I use for longitude and latitude?
I am saving longitude and latitude as FloatField. But when I tried to use them on JS in the array I figured out that FloatField separates with a comma instead of a dot as should be on latitude or longitude. So it acts like four different elements in js. js: map.on('load', () => { 'coordinates': [ [{{tour.departure.city.longitude}},{{tour.departure.city.latitude}}], [{{tour.arrival.city.longitude}},{{tour.arrival.city.latitude}}], // it will be like [ 23, 0534 , 42, 1534] // but should be like [ 23.0534 , 42.1534] ] }); models.py class Tour(models.Model): latitude = models.FloatField(blank=True, null=True, verbose_name=_("Latitude")) longitude= models.FloatField(blank=True, null=True, verbose_name=_("Longitude")) I tried to save with dot but Django converted it to the comma. -
Not rendering the Messahe in Django
I am trying to create message before submitting the page, but i do not know why the message not rendering , can anyone help me to correct it. form.py class NameForm(forms.ModelForm): translated_names = TranslationField() class Meta: fields = "__all__" model = models.Name admin.py class NameAdmin(MasterDataBaseAdmin): form = forms.NameForm inlines = [AddressInline, RegistrationTypeInline] queryset = models.Name.objects.prefetch_related( "names", "name__id", "registrationstype") views.py class NameViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Name.objects.supported().prefetch_related("names", "registrationstype") serializer_class = serializers.NameSerializer def nametype(request): form = Form(request.POST) if form.is_valid(): return render(request, 'templates\ view2.html', form) view2.html {% extends "admin/base_site.html" %} -
Show all comments from a specific user in django
I am trying to consolidate all the comments, on various products, from the logged in user in an "Account" page. My initial plan was to request all comments from the user id. Because I created a Profile model, I thought the right way to approach this was to link it to the profile id, and not directly to the use id. Obviously, it's not working. Am I close to it? or should I think of it completely differently? (new to programming, as you can see on the code) Starting with my models.py class ReviewRating(models.Model): user = models.ForeignKey(User,blank=True, on_delete=models.CASCADE) product=models.ForeignKey(Product,related_name="comments", on_delete=models.CASCADE) review=models.TextField(max_length=250) def __str__(self): return '%s - %s - %s'%(self.user, self.product, self.date_added) class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) general_reviews = models.ForeignKey(ReviewRating,null=True, on_delete=models.CASCADE) def str(self): return str(self.user) Views.py def account(response, profile_id): generalreviews_list = Profile.general_reviews.objects.all(pk=profile_id) return render(response,"main/account.html", {'generalreviews_list':generalreviews_list}) URLS path("account/<profile_id>/", views.account, name="account"), -
Django Post method not showing form to fill fields
The post method does not bring a form to enter the field details. I am able to enter data using json format. I followed the Django documentation to create the API This is my serializer code: from rest_framework import serializers from .models import Tasks # converting objects into datatypes understandable by javaScript and frontend frameworks class TasksSerializers(serializers.ModelSerializer): class Meta: model = Tasks fields = "__all__" views.py @api_view(['GET', 'POST']) def task_list(request, format=None): serializer_class = TasksSerializers if request.method == 'GET': tasks = Tasks.objects.all() serializer = TasksSerializers(tasks, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = TasksSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) print(request.method) return Response(serializer.data, status=status.HTTP_201_CREATED) models.py class Tasks(models.Model): task_id = models.AutoField(db_column="task_id", primary_key=True, unique="true") task_description = models.TextField(db_column="task_description", null=True) task_status= models.CharField(max_length=399, db_column="task_status", default="Not started" ) task_priority = models.CharField(max_length=399, db_column="task_priority", default="Low priority") asignee_name = models.TextField(db_column="asignee_name", blank=False, null=False) deadline = models.DateField(db_column="deadline", blank=False, null=False) emp = models.ForeignKey(Employee,on_delete=models.CASCADE,default='') # metadata for the table class Meta: db_table = "Tasks" What have I done wrong? -
Django admin login redirects to admin login with a 302
I have a new django 4 app, and when I try to login to the admin, I am redirected to the login page. This is in development, so localhost, with no SSL. I have checked the following: Allowed hosts is ["*"] Authentication definitely succeeds, user is returned from auth backend Django sessions app and middleware are in settings.py Django sets 2 browser cookies, one for csrf and one for session id django_sessions table contains sessions Session id on browser cookie matches session id in database table. I'm a bit lost, it's a very opaque error, just an infinite loop of 302s back to login. -
Why Django form didn check unique of form field?
Method is_valid didnt check unique of form and when i try to create new item its just do nothing. models.py from django.db import models from django.contrib.auth.models import User class Links(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Пользователь') long_url = models.CharField('Длинная ссылка', max_length=300) short_url = models.SlugField('Сокращенная ссылка', max_length=50, unique=True) title = models.CharField('Название для ссылки', max_length=80) def __str__(self): return self.title field short_url have unique=True views.py from django.shortcuts import render, redirect from django.views.generic import ListView from .models import Links from .forms import AddLinkForm def links(request): return render(request, 'main/main_page.html') class LinksList(ListView): model = Links template_name = 'links/links.html' ordering = ['-id'] def get_context_data(self, *, object_list=None, **kwargs): ctx = super(LinksList, self).get_context_data(**kwargs) user = self.request.user links = Links.objects.filter(user=user) form = AddLinkForm ctx['form'] = form ctx['links'] = links return ctx def post(self, request, *agrs, **kwargs): post = request.POST.copy() post['user'] = request.user request.POST = post form = AddLinkForm(request.POST) if form.is_valid(): form.save() return redirect('links') i try to use is_valid but when im testing it form let me entry not unic word, i press add it but page reload.It shoud work but i cant understand what is wrong forms.py from django import forms from .models import Links class AddLinkForm(forms.ModelForm): long_url = forms.CharField( required=True, label='Длинная ссылка', widget=forms.TextInput(attrs={'placeholder': 'Введите длинную ссылку'}) ) short_url = forms.SlugField( … -
django access same attribute on different model dynamically
I have different models which has following format. class Company(models.Model): pass class ModelA(models.Model): company = models.ForeignKey(Company, models.CASCADE) class ModelB(models.Model): company = models.ForeignKey(Company, models.CASCADE) class ModelC(models.Model): modelb = models.ForeginKey(ModelC) I want to write generic display field by the use of mixin in django admin for ModelA, ModelC as: class FieldMixin: @display(description='field') def my_field(self, obj): # normal solution would be this if object is ModelA and object.company.is_active: return 'active' if object is ModelC and object.modelb.company.is_active return 'active' # i wanted something like this instead of above. It will be easier if object has immediate attribute but object can have same field in nested object as well. object._meta.get_fields('company').is_active -
Changing a ForeignKey to a be the parent class/model
I have a situation where there are various entities, with ForeignKeys to models that are subclasses of another model. I need to update these FKs to point to the parent, so that any of the various subclasses could be linked. For example, the code might be: class School(Model): ... class University(School): ... class Student(Model): university = ForeignKey(University) ... and I need to change that FK from Student to University, to be an FK to School. I think that all Universities will have the same ID as the School that is in the database for that university. So is it safe/reliable to define the Student: class Student(Model): university = ForeignKey(University) school = ForeignKey(School) Then make a migration that creates the new school attribute, and uses RunPython to copy the id from university into school, then delete the university attribute and makemigrations for that? Is it ever possible that this method would break, or produce bad data? -
Why cleaned_data is None in BaseInlineFormSet?
Why when I want to get cleaned data in my custom forms, I get cleaned data is None? class AbstractRangeForm(BaseInlineFormSet): def __init__(self, *args, **kwargs): super(AbstractRangeForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(AbstractRangeForm, self).clean() #cleaned_data = None -
I want to know about the exact need of using @tracer.wrap() decorator in django
@tracer.wrap() - I have seen this decorator, above various methods in classes. I want to know about its use case. It is imported from ddtrace like "from ddtrace import tracer" -
Django: How to get the first time a user logged in within 24 hours in django
In Django, we can get the time a user last logged in by using Auth.User.last_login. That is only updated when the user logs in using his username/password. This would be useful for queries such as getting the number of new records since the last visit. Users can log out and also login multiple times in a day, now I want to get the first time a user logged in, in a day and store it in a model in the db. How do I achieve this functionality?