Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
if field.many_to_many and field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no attribute '_meta'
A source Django 3 by examples Chapter 14 When I try to run python manage.py migrate --settings=educa.settings.pro Another files are copies and pastes from the book The result is File "C:\Python\educa\manage.py", line 22, in <module> main() File "C:\Python\educa\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 487, in add_field if field.many_to_many and field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no attribute '_meta' Migration file: from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('account', '0005_contant'), ] operations = [ migrations.CreateModel( name='Contact', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=True, verbose_name='ID')), ('user_from', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rel_from_set', to=settings.AUTH_USER_MODEL)), … -
Is there any way to get the exact datatype of fields of csv file reading using pandas? [duplicate]
i have used dtypes of pandas to get the datatype of csv file, ``` with codecs.open(new_file_path_is, encoding="utf8") as csvfile: df = pd.read_csv(csvfile,nrows=100) print(df.dtypes) ``` Here the string fields are considered as object also the date field, I have appended field name and its datatype to a dictionary and the result is: {'First Name': 'object', 'Last Name': 'object', 'Date': 'object', 'Id': 'int64'} is there any method to get the exact datatype of fields?why its taken as object? -
How to get "HTTP_CF_IPCOUNTRY" with django python
I'm unable to get HTTP_CF_IPCOUNTRY from http meta data. I want to get country code. def register(request): country_code = request.META.get('HTTP_CF_IPCOUNTRY', 'N/A').strip() print("THIs is ",country_code) this prints --> N/A -
Django Please help me place a checkbox and a mail box with a send button on the html page
One of functionality in my training project: subscribe to the news by check-box and e-mail. Send newsletter daily. The user can unsubscribe from the mailing list in his profile by unchecking the checkbox. It so happened that first I set up a daily newsletter for users who have booleanfield = true. For it I marked the checkboxes in the admin panel. It works. Now it is necessary to add the checkbox and the mail field to the news page. I'm stuck on the simplest. Tired and confused. Please help me place a checkbox and a mail box with a send button on the news page models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) hr = models.BooleanField(default=False) subscribed_for_mailings = models.BooleanField(default=False) subscription_email = models.EmailField(default="") def __str__(self): return str(self.user) Forms.py class MailingForm(forms.ModelForm): class Meta: model = models.Profile fields = ('subscription_email', 'subscribed_for_mailings', ) widgets = { 'subscription_email': forms.EmailInput(attrs={"placeholder": "Your Email..."}), 'subscribed_for_mailings': forms.CheckboxInput, } views.py def all_news(request): today = date.today() today_news = models.TopNews.objects.filter(created__gte=today) return render(request, "news.html", {'today_news': today_news}) def mailing_news(request): if request.method == 'POST': mailing_form = forms.MailingForm(request.POST) if mailing_form.is_valid(): mailing_form.save() return HttpResponse('You will receive news by mail') else: mailing_form = forms.MailingForm() return render(request, "news.html", {'mailing_form': mailing_form}) urls.py ... path('news/', views.all_news, name='all_news'), ... news.html {% extends 'base.html' … -
Exe creation using pyinstaller for django rest app
I am trying to create an exe file using Pyinstaller for Django project having only REST api framework used. I am running manage.py runserver command by creating another file run.py and executing that file. run.py content: import os if name == 'main': os.system("python manage.py runserver 0.0.0.0:5000") I am trying to create exe file by giving command pyinstaller --onefile -w run.py manage.py (Giving two files by keeping in mind that it should analyze both the files but execute run.exe, I may be wrongly doing it) It is creating a run.exe file which is not giving any error or output. I tried --noreload option but still no error and no output at console while exe execution. I am running exe file as: run.exe --noreload (not giving runserver as it is already mentioned in run.py file) Could someone please help on how to create exe file in such scenario and as I am mentioning runserver inside another function? -
Django forms.PasswordInput() updated my application main password
On my Django app, I have a custom field rendered with the forms.PasswordInput() widget. This works as expected from a visual perspective. However, Chrome detects this as a password and then updates this field with the master password that a user might have set on his account on the app. Is there a way to get a forms.PasswordInput() field without Chrome messing passwords fields in it? -
How to put template into iframe?
The very similiar problem as mine I found here: Set URL to load iframe in a Django template but it doesn't help. Having a route in my urls.py written as (...) path('rejestracja/', views.rejestracja, name = 'rejestracja'),(...) where the view is to render page named rejestracja.html, I have to put the content of it into iframe. And I do it assigning src = "{% url 'rejestracja' %}". Unfortunatelly the iframe is showing me an error: "Page localhost is blocked" "Server localhost denied connection." ERR_BLOCKED_BY_RESPONSE The strange thing is, source of iframe shows me content of rejestracja.html. It means, I think, my code is ok, but somewhere I have any restrictions. But I have no idea which, how and where... Could someone tell me what is wrong, or at least, where to look for solution? -
Django creates a migration that seems already reflected in original postgresql schema
I've modified the foreign key calendar as nullable in my Django model CalendarAssign. \ # ---------------------------------------------------------------------------- # class Calendars(models.Model): id = models.CharField(primary_key=True, max_length=100) cms_id = models.CharField(max_length=100) default_program = models.ForeignKey(ControlPrograms, models.CASCADE, blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: managed = True db_table = 'calendars' # ---------------------------------------------------------------------------- # class CalendarAssign(models.Model): device_mac = models.ForeignKey(Device, models.CASCADE) calendar = models.ForeignKey(Calendars, models.CASCADE, null=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: managed = True db_table = 'calendar_assign' When applying the migration generated by Django it gives me an error. operations = [ migrations.AlterField( model_name='calendarassign', name='calendar', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='smartbridge.Calendars'), ) Generated sql code uses unsupported feature 'WITH ORDINALITY'. It's because Django doesn't support the Postrges version we are using. WITH ORDINALITY appears in psql 9.4 but we use version 9.1. Both Postgres and Django cannot be upgraded right now. So I need to write the migration manually (without 'WITH ORDINALITY' feature). migrations.RunSQL("DO $$DECLARE r record;\ BEGIN\ FOR r IN SELECT table_name,constraint_name \ FROM information_schema.constraint_table_usage \ WHERE table_name IN ('calendars') AND constraint_name like '%calendar_assign_calendar_id%'\ LOOP\ EXECUTE 'ALTER TABLE calendar_assign DROP CONSTRAINT '|| quote_ident(r.constraint_name) || ';';\ END LOOP;\ ALTER TABLE calendar_assign ALTER COLUMN calendar_id DROP NOT NULL; \ ALTER TABLE calendar_assign \ ADD CONSTRAINT calendar_assign_calendar_id_fk_calendars_id FOREIGN KEY (calendar_id) REFERENCES calendars(id);\ END$$;") Migration … -
Making any changes to inline css of the HTML file inside DJANGO project is not woking
I have to make changes in my code that if approverFlag is "Approved" then display the record as green and if the approverFlag is "Not Approved" then display the record as red. Folllowing are the changes I have made in my HTML file:- {% if awp.approveFlag == "Approved" %} <td style = "color:green;" id=displayrecord >{{ awp.approveFlag }} </td> {% elif awp.approveFlag == "Not Approved"%} <td style = "color:red;" id=displayrecord >{{ awp.approveFlag}} </td> {% endif %} But it is not working. I have also tried writing class here as follows:- <td class = "approved" id=displayrecord >{{ awp.approveFlag }} </td> And then making changes in tag of the HTML file:- <style> .approved{ color:red; } </style> But nothing is working. Can anyone suggest any solution to make it work? -
Invalid block tag on line 7: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I am beginner in html-templates and Django. author_list.html {% extends "base_generic.html" %} {% block content %} <h1>All authors</h1> <ul> {% for author in author_list %} <li><a href="">{{ author.last_name }}:</a> {% for book in author.book_set.all %} {{ book.title }} {% if not forloop.last %}, {% endif %}{% endfor %}</li> {% endfor %} </ul> {% endblock %} Error: Invalid block tag on line 7: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag? I have the block of code. It works without block if, but doesn't work with the conditional. How to fix it. Help! I should paste "," after each name of book. -
Can I change the django rate limiter timeout?
I'm building an API in Python and Django and have encountered the rate limits set by django. Now, I've adjusted the rate limits for users and anons accordingly but I was wondering if there was a way to change or reduce the time in the following error response. { "detail": "Request was throttled. Expected available in 7735 seconds." } Specifically I would like to reduce the 7735 seconds. Also, if I'm not mistaken, the timer counts down from 86400 seconds i.e. 1 day ? -
Better way of hiding entries not created by current user in Django?
Im pretty new to Django, and right now I have created a site that lets users register/login, make entries that are associated to that user via a "user" field in the entries database. Iv'e managed to get all the functionality of hiding other users entries by adding get_queryset() methods that only return the current users entries. But I feel like this is a bad way of doing this. I feel like im reusing a lot of code and that there could be backdoors to display other users entries. Is there a way to completely disable other users entries from the current user, not just not display it? views.py class EntryListView(LockedView, ListView): model = Entry def get_queryset(self): return super().get_queryset().filter(user=self.request.user).order_by("-date_created") class EntryDetailView(LockedView, DetailView): model = Entry def get_queryset(self): return super().get_queryset().filter(user=self.request.user) class EntryCreateView(LockedView, SuccessMessageMixin, CreateView): model = Entry fields = ["title", "content"] success_url = reverse_lazy("entry-list") success_message = "Your new entry was created!" def form_valid(self, form): user = self.request.user form.instance.user = user return super(EntryCreateView, self).form_valid(form) def get_queryset(self): return super().get_queryset().filter(user=self.request.user) class EntryUpdateView(LockedView, SuccessMessageMixin, UpdateView): model = Entry fields = ["title", "content"] success_message = "Your entry was updated!" def get_success_url(self): return reverse_lazy( "entry-detail", kwargs={"pk": self.object.pk} ) def get_queryset(self): return super().get_queryset().filter(user=self.request.user) -
Use of queryset inside Primarykeyfield of ModelSerializer in Django Rest
I am making a simple create api for a model which has almost all fields as foriegn key to other models. I am writing create logic inside the serializer. It is working fine. However if I define all the fields as pkrelated field in serializer, it asks for queryset attribute. Why it is asking that. And if I put queryset and import all the objects(queryset= Example.objects.all()) wouldnt it make the code and api slow since it is importing all the objects from Example model. Also, what its use to be honest? My model: class Example(TimeStampAbstractModel): abc = models.ForeignKey(User,.... xyz_info = models.ForeignKey(XYZ,... mnp = models.ForeignKey(MNP,...... status = models.CharField(....blank=True) My serializer: class AttendanceSerializer(serializers.ModelSerializer): xyz_info = serializers.PrimaryKeyRelatedField(required=True, queryset=XYZ.objects.all()) mnp= serializers.PrimaryKeyRelatedField(required=True, queryset=MNP.objects.all()) #mnp = serializers.IntegerField(required=True) status = serializers.CharField(required=True) class Meta: model = Attendance fields = ['xyz_info','mnp','status'] def create(self, validated_data): ............. In above serializer class, if I hadnt defined all those fileds in the serializer, it works fine. But if I define them as pkfield as above ( I am passing only ids in the body from frontend), it asks for queryset. Why it is asking queryset and what its use there? Also can I defined them as integarfield? When to define as pkfield and … -
How to mix multiple querysets into one and re order them by time created?
I am learning Django and still a beginner. For practising, i am trying to make a demo social media website. In my project, users can create groups, then they can post and comment there. In the home page, i am trying to add a section like 'recent activities' where a user can see recent activities in that website like "John created a group 'Javascript', Tim posted a comment in 'Python', Sarah posted in 'CSS'" Now i have made some queries like: groups = Group.objects.all().order_by('-created')[0:5] posts = Post.objects.all().order_by('-created')[0:5] comments = Comment.objects.all().order_by('-created')[0:5] I want to mix them all in a single queryset. Then order them all by the time they were created. I know it's a silly question and i have been stuck here since morning. Can you help me and show me the process please? -
How to hoste multiple Django websites on single sever using NGINX and uWSGI
i have a linux server running under Ubuntu server 20.04 LTS, i'm using NGINX as a web server and uWSGI as an application server, i have a Django website is already installed and running perfectly, and the exact way i did that is by following the instructions from this video https://www.youtube.com/watch?v=ZpR1W-NWnp4&t=2s, but the thing is that i have several websites that needs to be installed, so i tried to redo all of it for a second website on the same server, but that did not work at all. My question is: once i install a Django project exactly the way shown in the video using Nginx and uWSGI, how to install another Django project in a practical manner, in other words how to install multiple Django projects using Nginx and uWSGI. -
How to create database connection using REST API in Django?
Currently, I'm trying to make a Database Connection with Django REST API. The goal: To create an API for DB connection with any databases by inputting the properties (e.g., host, dbname, username, password, etc). I already tried using GET method to connect and retrieve the output. However, all the DB properties are written in the script. This is my result using GET: Now, I want to modify it into POST method to connect and retrieve the output. (It seems that user gives the input). My expected result is: The problem is: I don't know how to modify it into POST method (request JSON) and retrieve the desired output (response JSON) as I mentioned in the above picture. The MyApp\src\DBConn.py file: import psycopg2 class DbConnection: def __init__(self, host, port, dbname, user, password): self.host = host self.port = port self.dbname = dbname self.user = user self.password = password def create_conn(self): # connection string conn = 'host = {host} port = {port} dbname = {dbname} user = {user} password = {password}'.format( host = self.host, port = self.port, dbname = self.dbname, user = self.user, password = self.password ) # establish the connection self.db = psycopg2.connect(conn) self.cursor = self.db.cursor() def check_conn(self): sql = "SELECT VERSION()" … -
Why is the server not working when using django_prometheus?
There is a django application. It is necessary to collect metrics. I'm using django_prometheus. I added the django_prometheus app to my project. INSTALLED_APPS = [ ... 'django_prometheus', ... ] MIDDLEWARE = [ 'django_prometheus.middleware.PrometheusBeforeMiddleware', ... 'django_prometheus.middleware.PrometheusAfterMiddleware', ] I don't want to add the URL "/ metrics". I need to start the server on a separate port using prometheus_client.start_http_server. I added this code to wsgi.py: from django.conf import settings from django_prometheus.exports import SetupPrometheusEndpointOnPort SetupPrometheusEndpointOnPort(9090) This starts the server and it works. But the correct metrics are not displayed. If you add the url "/metrics": urlpatterns += [ path('', include('django_prometheus.urls')), ] Then localhost:8000/metrics will display the correct metrics. What could be the problem? P.S.: I started the server via start_http_server in parallel with the FastAPI application and everything worked correctly. -
how to get param in permission.py django
I want to work with 'start' param in permissions.py How I can take it ? My model class Quiz(models.Model) : title = models.CharField(max_length=50) start = models.DateTimeField(default="2021-10-10") end = models.DateTimeField(default="2021-10-11") description = models.CharField(max_length=250) permissions.py from rest_framework import permissions class IsTimeNotDefined(permissions.BasePermission) : def has_permission(self, request, view): if request.method in permissions.SAFE_METHODS: return False return False -
p y manage.py run server not working in vscode editor
recently started learning Django and not to run this command "p y manage.py run server" I am using windows 10 and vs code(power shell) as terminal it's showing me again and again that i have no such file in the directory -
Django-filters, q objects & searching "contains" in manytomany & textfields at the same time
does anyone know anything about q objects and searching many to many fields? class tags(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Item(models.Model): item_id = models.CharField(default = random_string,max_length=5) tags = models.ManyToManyField(tags, verbose_name="tags") description = models.TextField() topic = models.TextField() I am using django-filters to create a filter / search area, below if filters.py: class ItemFilter(django_filters.FilterSet): multi_name_fields = django_filters.CharFilter(method='filter_by_all_name_fields') class Meta: model = Item fields = ['description','topic','tags'] def filter_by_all_name_fields(self, queryset, name, value): return queryset.filter( Q(description__contains=value) | Q(topic__contains=value) | Q(tags__contains=value) ) When I render the form field "multi_name_fields" I get an error " Related Field got invalid lookup: contains " The search form functions perfectly without the manytomany field added in but when I add in the "tags" manytomany field it gives me the above error. Does anybody have any ideas where I am going wrong or what I am missing? -
Docker configuration for Django+Vuejs+Gunicorn+Nginx lead to 502 Bad Gateway
Context I'm developing an application that will have to be deployed once per customer (it's not a multi-tenant app that all my customers would use). Ultimately, it will be deployed on AWS with services like RDS (DB), S3 (storage) and ECS (container service). You can see how I imagined it with the image below if it can help to answer me: My application is working well locally without Docker. But I want to use a dockerized version of it locally before trying to deploy it on AWS, because I want to be able to run it locally with Docker before trying to do it on AWS (...). Since all my customers would have their own instance (and customer1 could have a different version than customer2 at some time), I thought about a single container with everything needed, as you can see on the image : the Django application, the Vue built files, gunicorn and nginx. Question 1 : Is it a good idea to do it like this ? Or should I use a docker-compose thing with multiple services (backend (django) & nginx). Would it lead to multiple containers ? To do so, I did the following configuration : Dockerfile: … -
Django switch database user
Assume I got different database users, and each of them have different permissions (already settled in db side). How can I switch between different db users? 'ENGINE': 'django.db.backends.postgresql', 'NAME': '****', 'USER': '****', # i got several users here and want to switch them 'PASSWORD': '****', 'HOST': '*****', 'PORT': '***', -
Video not playing on ios (safari)
Video Link This video is playable on windows as well as android. But not in ios. I am using Django (python framework) for backend. What should i do ? -
Can we use class create view to build multiple forms in django?
class formsView(CreateView): model= dummy fields= "__all__" template_name= "index/page1.html" success_url="page1" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['dummy'] = dummy.objects.all() context['tummy']= tummy.objects.all() return context Using this code, I am able to render a form based on the model 'dummy', and am able to get the context from another model 'tummy' to use in my html code. However, I was wondering if there was a way to include more than one form using the create view. -
How to run tests for specific django apps when you have a conftest in a root folder
I work on a Django project and we have dozens of different apps. We a have a global conftest in the root folder and conftests in each app's folders. Sometimes we need to run tests for separate apps and not wait for all tests to complete. How can I run tests for a specific app if they don't work without running the global conftest? So command pytest -v apps/app_one won't work because it loads only a conftest in the app_one folder and does not load a global conftest.