Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error when autocreating slug in django models
This is my model: class post (models.Model): title = models.CharField(max_length=200) post = models.CharField(max_length=75000) picture = models.URLField(max_length=200, default="https://i.ibb.co/0MZ5mFt/download.jpg") show_date = models.DateTimeField() slug = models.SlugField(editable=False) def save(self, *args, **kwargs): to_slug = f"{self.title} {self.show_date}" self.slug = slugify(to_slug) super(Job, self).save(*args, **kwargs) When I run my website and try to add an item from the admin portal, though, I get this: NameError at /admin/blog/post/add/ name 'Job' is not defined I got the autoslugging part from here, what is 'Job' that I have to define? -
Unknown field(s) (groups, user_permissions, date_joined, is_superuser) specified for Account
I just try add "is_saler = models.BooleanField(default=False)" into class Account and migrate. And now i got the error when trying to change the superuser data. The line "is_saler = models.BooleanField(default=False)" had been deleted but still got this error after migrate. from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, username, email, password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have an username') user = self.model( email = self.normalize_email(email), username = username, password = password, first_name = first_name, last_name = last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, email, username, password): user = self.create_user( email = self.normalize_email(email), username = username, password = password, first_name = first_name, last_name = last_name, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superadmin = True user.save(using=self._db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) data_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name', 'last_name', 'email'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def … -
Django Serialize a JsonField, Django Rest API
I have a class for example from django.forms import JSONField class Area(models.model): GeoJson = JSONField ... and a serializer for the class class AreaSerializer(serializers.ModelSerializer): model = Areas fields = ('GeoJson', ... ) but when I try to get the data from my rest frame work I get this error Object of type 'JSONField' is not JSON serializable What am I doing wrong? it is my first time using django and I need to store GeoJson in the database so im really stuck on how to fix this issue as I dont understand why it wont work, Any help or advice is greatly appreciated. -
How to run a Django's application server on a VPS server
I have an application that should run via VPS terminal-based so that the web app can be online permanently. The command: python manage.py runserver 173.249.8.237:8000 should be executed via the VPS terminal because when I use putty via my laptop, whenever I switch off my putty software via my laptop, the application won't be accessible. Please, suggest to me a way open a terminal in order to run the Django application server. Or, is there any method that can allow me to my Django web application on VPS? Thanks in advence -
form pot URL not defined in URLconf
I have a form that is on the URL: http://127.0.0.1:8000/disciplineReport/1/ where 1 is the primary key of the object I'm editing. detail.html: <form method="post" id="edit-form" action="{% url 'disciplineReport:saveDiscipline' doctor.id %}}"> urls.py: urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/saveDiscipline/', views.SaveDiscipline, name='saveDiscipline'), ] Error: Using the URLconf defined in program_history_reports.urls, Django tried these URL patterns, in this order: disciplineReport/ [name='index'] disciplineReport/ int:pk/ [name='detail'] disciplineReport/ int:pk/saveDiscipline/ [name='saveDiscipline'] admin/ The current path, disciplineReport/1/saveDiscipline/}, didn't match any of these. What am I missing here? it seems like the URL matches the 3rd pattern... -
TypeError : Field 'id' expected a number but got '<django.db.models.query_utils.DeferredAttribute object at 0x00000000044871C0>'
Good time of day. I am an aspiring Django developer. When working on a project, I ran into a problem, and I don't have any older comrades. Could you help me with her? I am developing a small store and when adding a product to the cart I get this error. I've already tried everything and I'm just desperate Field 'id' expected a number but got '<django.db.models.query_utils.DeferredAttribute object at 0x00000000044871C0>'. models.py # Категория продукта class Category(models.Model): name = models.CharField('Категория', max_length=100) url = models.SlugField(max_length=100, unique=True, db_index=True) def __str__(self): return f'{self.name}' def save(self, *args, **kwargs): if not self.url: self.url = slugify(self.name) super(Category, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('product_list_by_category', args=[self.url]) class Meta: verbose_name = "Категория" verbose_name_plural = "Категории" # Папка продуктов для каждой организации def products_image_path(instance, filename): return f'organisations_{instance.organisations.name}/products/{filename}' # Продукт class Products(models.Model): name = models.TextField(max_length=100, blank=False) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to=products_image_path, blank=True) number = models.PositiveIntegerField('Количество') price = models.DecimalField('Цена', max_digits=10, decimal_places=2) category = models.ForeignKey(Category, verbose_name='Категория', blank=False, on_delete=models.SET_NULL, null=True) organisations = models.ForeignKey(Organisations, related_name="org_info", on_delete=models.CASCADE) def __str__(self): return f'{self.name}' def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super(Products, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('product_detail', args=[self.id, self.slug]) class Meta: verbose_name = "Продукт" verbose_name_plural = "Продукты" ordering = ('name',) index_together = (('id', 'slug'),) … -
Can't call / pass data from django database onto website using built in auth model and a model I created, which is the one I cant query
Any help would be appreciated, basically I am a beginner and I'm struggling to pull data from my database. I used the built in auth method from django, which seemingly works ok as I can pull user data. However as soon as I want to use my Member class I made in models nothing seems to work. Can't output all its data. When looking at the admin page I see authentication and authorisation table and my Members table created in models.py. When I try pass into the context however nothing is displayed. My index.html {% block content %} {% if user.is_authenticated %} Hi {{ user.username }}! Hi {{ user.email }}! <p><a href="{% url 'logout' %}">Log Out</a></p> {% else %} <p>You are not logged in</p> Hi {{ all }}! <a href="{% url 'login' %}">Log In</a> {% endif %} {% endblock %} {% block title %}Home{% endblock %} My Views.py from django.shortcuts import render from .models import Member # Create your views here. def index(request): all_members = Member.objects.all return render(request, 'index.html', context = {'all':all_members}) def ethos(request): return render(request, 'ethos.html', {}) Models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class Member(models.Model): phoneNumber = PhoneNumberField() firstName = models.CharField(max_length=50) … -
How can I solve the issue: psql cannot connect to the server in Ubuntu?
In hosting my Django web application on VPS using PostgreSQl. However, the configuration seems to be fine but whenever I want to access the Postgres Shell, I ma getting the error bellow. root@vmi851374:~# sudo su -l postgres postgres@vmi851374:~$ psql psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? postgres@vmi851374:~$ I have checked the Postgres service status and everything seems fine but I don't know where this error comes from. Notice that in my localhost (laptop), I am not facing this issue. Only in the VPS server, I am getting this issue. Please assist me to solve this issue. -
Saving encrypted file using python django
How can we save an encrypted file using python django.. In models field i used FileField to save encrypted file.. but it is not correct.. instead of file field which field can i use.. and How can we save an encrypted file using python django? -
Uploaded file type check in django
I want to design a form in django that takes a text file as input and does some processing using it. I have written the following HTML file. <!DOCTYPE html> <html> <body> <h1>Transcript To Voiceover Convertor</h1><br/> <form action="" enctype="multipart/form-data" method="POST"> {% csrf_token %} <label for="document"> <b> Select a text file: </b> </label> <br/> <input type="file" name="document"> <br/><br/><br/> <!--<input type="file" accept="text/*" name="document"> <br/><br/><br/>--> <b> Select a gender for the voiceover </b> <br/> {{ form }} <br/><br/><br/><br/> <input type="submit" value="Submit" /> </form> </body> </html> As you can see, one of the input line is uncommented and the other one is commented. So basically, in the commented line I tried to use the accept attribute with text MIME but the problem I am facing is that in this case the browser only detects files with .txt extension but in Operating system like Ubuntu/Linux it is not necessary for text files to have .txt extension. So when I am using the commented line for input it is not able to detect those files. So, can someone please suggest me what should I do? My second problem is related to the first one. So, as you must be knowing that having a check on the … -
What python packages am I missing?
I'm trying to get my local windows 10 pc up and running with my django application. I'm a novice at python and django. My app was written by another developer who's been very helpful and has limited availability. I also want to sort it out myself for learning purposes. I'm including as much information as I can. I can add more if needed. I'm at my wit's end. I downloaded my code from bitbucket and loaded all of the packages in the base.txt and development.txt files onto my windows 10 pc. I keep getting several errors when trying to run the server. App is using in the following: python 3.61 django 1.11.3 base.txt file: boto3==1.4.7 celery==4.1.0 click==6.7 dateutils==0.6.6 Django==1.11.3 django-anymail==0.11.1 django-cors-headers==2.1.0 django-countries==5.0 django-filter==1.0.4 django-solo==1.1.3 django-storages==1.6.5 djangorestframework==3.6.3 djoser==0.6.0 kombu==4.1.0 mysqlclient==1.3.10 Pillow==4.3.0 python-dotenv==0.6.4 python-magic==0.4.13 pytz==2017.2 redis==2.10.6 uWSGI==2.0.15 xlrd==1.2.0 I don't get any errors loading the packages; however, when I run the server I get this screenful of error msg vomit: (venv) C:\Users\romph\dev\EWO-DEV\backend>python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors..wrapper at 0x000002A64687E0D0> Traceback (most recent call last): File "C:\Users\romph\.pyenv\pyenv-win\versions\3.6.1\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\romph\.pyenv\pyenv-win\versions\3.6.1\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Users\romph\.pyenv\pyenv-win\versions\3.6.1\lib\site-packages\django\core\management\base.py", line 359, in … -
update field based on another table django
hello I have to models I want to run a query every day to update a total field in a weekly table in some conditions first user ids should be equal then start_date in weekly table and date in daily table should be in the same week please help class Daily(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE,) total = models.FloatField(default=0) date = models.DateField(blank=True, null=True,) class Weekly(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE,) total = models.FloatField(default=0) start_date = models.DateField(blank=True, null=True,) -
Unable to runserver due to the error mentioned below
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/Desktop/cookiecutter/venv/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 0x0002): symbol not found in flat namespace '_PQbackendPID' -
web socket in django showing error 10048
Listen failure: Couldn't listen on 127.0.0.1:8000: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted. -
Difference between urls.py and Response(routes)
In django, what is the difference between putting your urls in urls.py and using this: def getRoutes(requests): routes = [ # urls ] return Response(routes) -
Why does MQTT not connect to the server?
My purpose is to achieve MQTT message publish upon postsave signal sent my DJango models. I have registered on_connect, on disconnect, on_publish callbacks to check when the relevant process is executed. However, none of callbacks I registered works. Here is my post_save signal code. Can someone please give me a hint where I do mistake? import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print("connecting") print("client:"+str(client)) print("userdata:"+str(userdata)) print("flags:"+str(flags)) print("result:"+str(rc)) global flag_connected flag_connected=1 def on_publish(client, userdata, mid): print("message published") def on_connect_fail(client, userdata, flags, rc): print("failed to connect") print("client:"+str(client)) print("userdata:"+str(userdata)) print("flags:"+str(flags)) print("result:"+str(rc)) global flag_connected flag_connected=0 def on_disconnect(client, userdata, rc): global flag_connected flag_connected = 0 def notify_windowsApp(sender,instance, **kwargs): new_truck_registered={ "identity":str(instance.truck_identity), "doorName":str(instance.registered_door.door_name), "doorNumber":str(instance.registered_door.door_number), "entryTag":str(instance.entry_tag), #"depatureTag":str(instance.departure_tag), "entrytime":instance.entry_time.strftime('%Y-%m-%d::%H-%M'), } sendToClient(new_truck_registered) def sendToClient(payloadTobeSent): client=mqtt.Client(client_id="django_post_save_signal", clean_session=True, ) mqttBroker="broker.hivemq.com" client.on_connect=on_connect client.on_publish=on_publish client.on_connect_fail=on_connect_fail client.on_disconnect=on_disconnect client.connect(mqttBroker) client.publish('baydoor/truckentrance',payload=str(payloadTobeSent),qos=1, retain=True) -
Django routing/pathing to multiply apps
Hi i know there is many of these asking about routing from a veiw to a new app in django. I have looked at a lot of them. And figured out to use app_name = 'name' and to use named routes for my html templates makes everything easier for sure. When i try to use a app_name:named-route i get this : ValueError at /recipedashboard The view recipeApp.views.dashboard didn't return an HttpResponse object. It returned None instead. I have gotten the name_app:named-route to send me to the second app, but how do i pass the session to the new app? userApp veiws: from django.shortcuts import render, redirect from django.contrib import messages from .models import User as LoggedUser # Create your views here. def index(request): return render(request, 'index.html') def register(request): if request.method == "GET": return redirect('/') errors = LoggedUser.objects.validate(request.POST) if len(errors) > 0: for er in errors.values(): messages.error(request, er) return redirect('/') else: new_user = LoggedUser.objects.register(request.POST) request.session['user_id'] = new_user.id messages.success(request, "You have successfully registered") return redirect('/success') def login(request): if request.method == "GET": return redirect('/') if not LoggedUser.objects.authenticate(request.POST['email'], request.POST['password']): messages.error(request, "Invalid Email/Password") return redirect('/') user = LoggedUser.objects.get(email=request.POST['email']) request.session['user_id'] = user.id messages.success(request, "You have successfully logged in!") return redirect('/success') def logout(request): request.session.clear() return redirect('/') def … -
DictQuery + Django + AJAX
My problem is simple, I had developed an application in DJANGO. I turn a CSV into JSON files but I have a format problem. <QueryDict: {'data': ['[{data }]']}> On the left, the ]} is not correct. The AJAX script is correct. The data send to JavaScript is properly. The format in JSON is ok on the JavaScript side but the Django side, there are this error in the format. How shoud I do to remove that ? Thanks a lot! -
'ManyToManyDescriptor' object has no attribute 'all' while accessing related_name
models.py 'ManyToManyDescriptor' object has no attribute 'all' when accessing related_name class Category(BaseModel): name = models.CharField(max_length=255, unique=True) class Record(BaseModel): categories = models.ManyToManyField(Category, related_name='records') query used Category.records.all() -
how to find top performing category in django without foreign key
models.py class Line_items(models.Model): id = models.AutoField(primary_key=True) product = models.ForeignKey('Products' , on_delete=models.DO_NOTHING ) class Products(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=400 , blank=True) class Categories(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100 , blank=True) slug = models.CharField(max_length=200 , blank=True) class Product_Categories(models.Model): id = models.AutoField(primary_key=True) product_id = models.ForeignKey(Products, on_delete=models.DO_NOTHING) category_id = models.ForeignKey(Categories, on_delete=models.DO_NOTHING) here are my models. where line_items contains number of orders done till now. in line_items we have connect product id with product table. but we don't have any connetion from product table to category table. ( category table contains every category and their id ). to connect product table with category table we have created new table 'product_categories' which connects each category with their respective product. here what we want is top performing category. category which have highest number of products. thanks -
How to auto print in django
Hi I'm currently trying to build resturent pos app. So I want to know how can I print from printer when new order in placed from waiter site. There will be 3 user admin, kitchen, waiters Waiter can place order and kitchen will get the order and have the order print automatically. They both will be different devices. If so how can I set to auto print in kitchen site when waiter site place an order. Thank you in advance -
Django Query duplicated 2 times
I have a Project model class Project(models.Model) name = models.CharField(max_length=255) members = models.ManyToManyField(User, related_name="members") and I am using a classbased Update view to restrict only those users who are members of the project. class ProjectUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Project fields = ["name"] def test_func(self): members = self.get_object().members.all() if members.contains(self.request.user): return True return False After looking at the SQL queries through Djang Debug Toolbar, I see the query is duplicated 2 times. the 1st instance is from this test_func and the other instance is from django generic views, how can I resolve the duplicated query issue -
Store html in database in django
Hello I'm trying to store HTML code in the database with Django but facing a problem with escape characters. here's an object that I'm trying to store but { "data": "<div class=\"read\" id=\"search\">Google</div>" } here's what I'm getting in database. <div class="read" id="search">Google</div> I tried to store with Model.objects.create() this becomes a problem to parse too much HTML in javascript then. JSON object gets confused with the double-quotes. the solution is I want to store data in database with backslashes \ as well so it can be parsed correctly as a JSON object. -
Conditional rendering in radio button saves both vales in the state
I'm new to react, I have conditional rendering in radio button, lets say a ratio button has 2 options option1 and option2 on selection option1 the page shows up 2 text fields ( say first and last name ) on selection option2 the page shows up 2 buttons(saybtn1andbtn2`) if i select option1 and fill up first & last name and hit save, it saved and if i come back to this page, it shows last filled first & last name But later if I comeback and select option2, click on btn1 and hit save the state will hold first name, last name and option2 with btn1 pressed. after saving option2 if i click option1, i can still see the first & last name filled I have attached the sample code, all the fields are picked up from Django application - the issue is, every ratio button options has its on number of components nested. how do toggle all the nested values of non selected options to null or default when the alternative option of the radio button is selected. // Radio_button_field.js import React from "react"; import {Col, FormGroup, Input, Label, Row} from "reactstrap"; export default class RadioButtonField extends React.Component { … -
How can I get top 5 inventory items from a django model which has lowest quantity?
#This is my inventory model. I want to get the inventory items that have the lowest quantity in the model. class Inventory(models.Model): name = models.CharField(max_length=100) purchase_date = models.DateTimeField() category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.CharField(max_length=50) purchase_price = models.FloatField(max_length=50) selling_price = models.FloatField(max_length=50) description = models.CharField(max_length=100) location = models.ForeignKey(Locations, on_delete=models.CASCADE) created_date = models.DateField(auto_now_add=True)