Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error during creating Django custom user model
I am creating a new user model called Customer. I have added my app to installed apps. But when i set AUTH_USER_MODEL = appname.Customer It displays an error that my appname is not defined -
Django key word filter sentance
I have a keyword class that links to something, I am trying to filter it so you can do the following: tags-keywords/?description=these young people are annoying The TagTrigger would look like this: trigger = young people (CharField) I wondered if there was any way to do this in the Django ORM. def get_queryset(self): qs = super().get_queryset() description = self.request.GET.get('description') if description: qs = qs.filter(keyword__whatever=description) return qs Thanks -
Configuring nginx to listen to specific IP address
I have two machines on the network running the same application. I want to assign one as master and other as secondary backup server i.e. If master fails, secondary server should start responding. Two IP addresses: 192.168.1.16 (master), 192.168.1.17 (slave) Nginx is configured as follows: upstream abc_server { server 192.168.1.16:8000 fail_timeout=0; server 192.168.1.17:8000 backup; } server { listen 80; server_name 192.168.1.16; client_max_body_size 4G; access_log /home/Desktop/DevEnv/Webserver/logs/nginx-access.log; error_log /home/Desktop/DevEnv/Webserver/logs/nginx-error.log; location /media/ { alias /home/Desktop/DevEnv/Webserver/media/; } location /static/ { alias /home/Desktop/DevEnv/Webserver/static/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://abc_server; break; } } } The above code is running successfully as per the order mentioned in the upstream function for both the servers. But both configuration files listens to their respective IP addresses only. I want both the servers to listen to 192.168.1.16 only so that secondary can respond when master fails. PS: I tried to change the listen portion of master as well as secondary server's configuration file as: listen 192.168.1.16:80; This command works on the master server but gives following error on secondary server: nginx: [emerg] bind() to 192.168.1.16:80 failed (99: Cannot assign requested address) Kindly help me on this. Thanks in … -
Django: Image Field not showing up
So my image is not displaying, here is my code: models.py: from django.contrib.auth.models import User from django.db import models from django.conf import settings from django.utils.translation import gettext_lazy as _ class ProfileImage(models.Model): """ Profile model """ user = models.OneToOneField( verbose_name=_('User'), to=settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE ) avatar = models.ImageField(upload_to='profile_image') settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mifamiliaesundesastre/media') urls.py: from django.contrib import admin from django.urls import path, include from Home.views import home_view from accounts.views import login_view, register_view, logout_view, user_home from chat.views import Messages from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='home'), path('login/', login_view), path('signup/', register_view), path('logout/', logout_view), path('home/', user_home), path('messages/', include('chat.urls')), path('messages/', Messages), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) user_home.html: <img src="{{ user.profileimage.avatar.url }}" alt="profile image"> I did all correct, also I can see my images in my media folders but in my template does not show up, does anybody know what is wrong with my code? -
Django multiple databases — read from "readonly" connection; Commit transaction and have all following queries use "default" connection
I have 2 databases: # Config DATABASES = { 'default': {}, 'readonly': {}, } In a background task, I would like to pull data from the "readonly" database, then save using the "default" database: # Tasks things = Thing.objects.using('readonly').all() util.do_stuff_with_things(things) # ideally I don't want to make `using` a required parameter of all my utilities I could manually specify save(using='default') on all of the utilites, but it's difficult to hunt them down. I would rather commit the transaction, then start a new transaction on the default connection. What I have attempted: set_autocommit transaction.set_autocommit(False, using='readonly') thing = Thing.objects.using('readonly').first() transaction.commit(using='readonly') transaction.set_autocommit(True, using='default') thing.save() # `save` still requires `using='default'`, "InternalError: cannot execute UPDATE in a read-only transaction" pulled within atomic block with transaction.atomic(using='readonly'): thing = Thing.objects.using('readonly').first() thing.save() # `save` still requires `using='default'`, "InternalError: cannot execute UPDATE in a read-only transaction" overwriting _state.db This works -- but I don't like it :( thing = Thing.objects.using('readonly').first() thing._state.db = 'default' thing.save() For now, I will probably go with #3, as it's least intrusive to the utilities I am using. But interested to know if there's a better way! -
How and where create some custom permissions exactly for an app, not for models only?
In admin panel we can see a list of permissions look like this auth | user | add user which are suit to template <app> | <model> | <event> <model> What if i don't have models and i just want to have two permissions on whole app change and view? So i can write some custom instructions on what users with the appropriate permission can do. -
IntegrityError at * UNIQUE constraint failed
I am trying to create a django application to keep track of a product(product stock application).whenever I try to add new product ,I cannot add more than one product in the same category. It gives UNIQUE constraint failed error . I want to add multiple products in same category. models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100) slug = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.IntegerField(null=True, blank=True) category = models.ForeignKey( Category, on_delete=models.CASCADE) def __str__(self): return self.name class Stock(models.Model): sold_quantity = models.IntegerField(null=True, blank=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) def __str__(self): return self.product.name Edit: Error Message -
Django rest API Authentication
I have created a REST API using Django rest framework to save details of 'Contact-Me' form which contains name, mobile no, email and message in UI. How should I authenticate my API to save the details with out having username and password from my website? Appreciate your help!!! Thanks, Venkat. -
Django - Copying Old Site to Localhost Isn’t Working
I've inherited a Django development project and am having A LOT of trouble getting it to work on my local Ubuntu 18.04 machine. The project was started in 2013 and has gone through bursts of development by various people. I need to pull it down before I start cleaning it up, upgrading and deleting all the old sql dumps that seem to be scattered everywhere amongst other obvious clutter. I need the working site as a reference so i don't want to start messing around with it on the current server. I am pretty new to Django and only recently completed one of those 4 hour YouTube tutorials. I think I could probably start coding a fresh site and would have some idea about deploying it onto a web server but getting an existing site with out of date software to run on my local machine is a whole other story. I am trying to decide on the best way forward... Do I keep trying to get it working on my local machine by installing old software and then upgrade it (a large amount of learning about old systems and the result might just be an old and out of … -
storing HTML in Django data models
is there a type of field for django data models that's for html? I want to have youtube embed links, which is a bunch of html fo putting a youtube video on your site. Itlooks like this: "". I stored it in a charfield, but it gets shown on the website as text. What should I do? Thanks! -
Django - How to move file between models with different storages?
I have a model "Local" that uses the django default_storage and contains the FileField for a locally stored file: class Local(Model): file = models.FileField(upload_to=..., storage=LOCAL_STORAGE) I have another model that uses a different storage class, for remote storage, equally with a FileField. class Remote(Model): file = models.FileField(upload_to=..., storage=REMOTE_STORAGE) When processing of a file locally is complete, I want to be able to move it from the Local Storage to the Remote storage. I don't want to have to read the local file, and then create a new one in the remote model as this can take too much time. Is there any way to move across storages, or even reference the file in the Remote model and when save is called have it saved into the new REMOTE_STORAGE from the LOCAL_STORAGE. Thanks! -
Django: cannot unpack non-iterable Posts object (TypeError)
I'm trying to filter the elements present in the "Posts" model by one of their attributes. This is my Class Based View: class FilteredPostListView(ListView): model = Posts template_name = "blog/post-category.html" context_object_name = "posts" paginate_by = 6 #the actual fuction that should filter the element by their category attribute: def get_queryset(self): category = get_object_or_404(Posts, category=self.kwargs.get("category")) return Posts.objects.filter(category) This is the related snippet in my urls.py: path('category/<category>/', FilteredPostListView.as_view(), name='category') When I type the URL localhost:8000/category/example/ where "example" is the value of the "category" attribute I am trying to filter by, I get the following errors: If multiple Posts objects have the attribute category with value "example": MultipleObjectsReturned at /category/example/ get() returned more than one Posts -- it returned 2! If only one Posts object has the attribute category with the value "example": TypeError at /category/example/ cannot unpack non-iterable Posts object Why is it returning non-iterable objects? -
Display 404 page if user is not authenticated django
I'm using django in my page. It's awesome. But I've little bit different requirements. I want to display 404 for restricted page instead for redirecting user to login page. If user is not authenticated. -
Can I split a single Django model field into multiple Django Rest Framework serializer fields?
Is it possible to split a single m2m Django model field into multiple DRF serializer fields? Consider the following code: models.py: class Author(models.Model): name = models.CharField() class BookQuerySet(models.QuerySet): def good(self): return self.filter(is_good=True) def bad(self): return self.filter(is_good=False) class Book(models.Model): objects = BookQuerySet.as_manager() title = models.CharField() author = models.ForeignKey(Author, related_name="books") is_good = models.BooleanField(default=False) serializers.py: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ["title"] class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ["name", "books"] books = BookSerializer(many=True) Is there any way for me to actually serialize "books" as good_books and bad_books, but still have them map to the single books fields on the Author model? Bear in mind, that these need to be writeable nested serializers. -
python: random question generator in a browser without an underlying database?
I want to develop a tool that generates random maths questions for students to solve in a browser. My idea is that I write a function like: def expression_generator(): x = random.randint(1,10) y = random.randint(1,10) questions = ('2x','3y^2','3(x+y)') answer1 = 2*x answer2 = (3*y)**2 answer3 = 3*(x+y) answers = (answer1,answer2,answer3) return(questions, answers) exam_questions = expression_generator() for x,y in zip(exam_questions[0],exam_questions[1]): print(x) print(y) print('*') ...the next step is I want to put this into a browser, to create an online question generator. My idea is that on the app there is a landing page there is a choice of which type of question they want to answer (which will be multiple functions similar to this), when that button is clicked, the function is called, 10 questions are printed, and for each question 4 multiple choice answers are printed, the student clicks one, and then they are told if the answer is right and there's a percentage calculated at the end of the page for how well they did this. My question is can I build a django app for this? I've never used django, but I was under the impression that django is a database library, where I just want to call … -
Django: How can I access the pk of a table row that has been submitted through a ModelForm?
I am aware that this may not be the right question, but I know this problem is caused by either the way the POST data is handled in my view or how I am working with the form. I'm still a beginner with Django. This is a very simple task I want this page to perform to then move on to other things; this is why I have no styles or anything else. I have a Note model to enable a user to add and modify text notes about some project in the site. Each row in the Note table is related to a row in the Project table through a ForeignKey. The Note model has several fields, but I only want to edit the text field for now. I also want to be able to edit one, two, or more at once and them submit them, as well as—in the future—adding a button to add a new form for a new note. This is my form from django import forms from .models import Note class NoteForm(forms.ModelForm): class Meta: model = Note fields = ('note_text',) # Only want to edit this field labels = {'note_text': (''),} # Don't want the … -
How to log in as postgresql superuser on DigitalOcean? (django)
I have successfully managed to put my Docker container on a DigitalOcean droplet and create a postgresql database and connect it to my app. I want to create a superuser. Typically (locally) to create a superuser I would just do python3 manage.py createsuperuser but since I am using a Docker image this is not possible. However, I can't seem to create or log in as a superuser at all. I login to the database using: root@vb:~# psql -U doadmin -h vb-db-do-user-XXXXXXX-0.a.db.ondigitalocean.com -p (PORT-NO) -d defaultdb --set=sslmode=require When I try to check what roles are within the database by using: defaultdb=> \du I am given the following: List of roles Role name | Attributes | Member of -----------+------------------------------------------------------------+----------- _dodb | Superuser, Replication | {} doadmin | Create role, Create DB, Replication, Bypass RLS | {} postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {} As you can see, the role I logged in with (doadmin) is not a superuser but _dodb and postgres are. I have never created the _dodb or postgres accounts, they were created automatically. I try to log into both of these superuser accounts using the same password but the password is not accepted: root@vb:~# … -
Apache2 and WSGI (django) too many redirects error
I've got the following apache conf: <VirtualHost *:80> ServerName ex4d4.danielmoessner.de Redirect 301 / "https://ex4d4.danielmoessner.de/" </VirtualHost> <IfModule mod_ssl.c> <VirtualHost *:443> ServerName ex4d4.danielmoessner.de ServerAdmin projekte@tortuga-webdesign.de # logs ErrorLog ${APACHE_LOG_DIR}/ex4d4.danielmoessner.de.error.log CustomLog ${APACHE_LOG_DIR}/ex4d4.danielmoessner.de.access.log combined # process WSGIDaemonProcess ex4d4 python-path=/home/ex4d4_project/ex4d4 python-home=/home/ex4d4_project/venv display-name=%{GROUP} WSGIProcessGroup ex4d4 WSGIScriptAlias / /home/ex4d4_project/ex4d4/config/wsgi.py # alias Alias /static /home/ex4d4_project/static Alias /media /home/ex4d4_project/media # dirs <Directory /home/ex4d4_project/static> Require all granted </Directory> <Directory /home/ex4d4_project/media> Require all granted </Directory> <Directory /home/ex4d4_project/ex4d4/config> <Files wsgi.py> Require all granted </Files> </Directory> # certbot Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateFile /etc/letsencrypt/live/ex4d4.danielmoessner.de/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/ex4d4.danielmoessner.de/privkey.pem </VirtualHost> </IfModule> Now I restarted the apache server with systemctl restart apache2. However when I vistit: ex4d4.danielmoessner.de I get an Error that says this page redirected you too many times. I don't know where the error comes from as I do not redirect in my config. It always redirects back to / Why is this happening? My django project that lives there is set up correctly and does not redirect in a loop. I know that because I didn't change the code and before it was connected with ex4d4.dmoe.tech and everything worked properly. -
Putting a value from a function into context
Adding pagination to my program has caused an existing feature to no longer work properly. I have tried this cart_obj, new_obj = Cart.objects.new_or_get(self.request) return cart_obj and this context['cart'] = cart_obj return context Both times I got the error message name 'cart_obj' is not defined views.py class ProductListView(ListView): model = Product template_name = "products/list.html" # added for pagination context_object_name='object_list' #Default: object_list # print(context_object_name) # paginate_by = 3 def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data(*args, **kwargs) cart_obj, new_obj = Cart.objects.new_or_get(self.request) context['cart'] = cart_obj return context print("context") print(context) def get_queryset(self, *args, **kwargs): request = self.request return Product.objects.all() def get(self, request): paginate_by = request.GET.get('paginate_by',6) or 4 data = self.model.objects.all() paginator = Paginator(data, paginate_by) page = request.GET.get('page') try: paginated = paginator.page(page) except PageNotAnInteger: paginated = paginator.page(1) except EmptyPage: paginated = paginator.page(paginator.num_pages) return render(request, self.template_name, {'DataPaginated':paginated, 'paginate_by':paginate_by, 'cart':cart_obj}) I am trying to find a way of putting the value of cart_obj in cart. -
How to make interactive HTML form with Django?
I am beginner with django, trying to make an interactive html form that can save all data to the database with django. Here is one of my attempts. But it shows csrf error(I also add csrf_token in html page). in views.py ("TableA" is my model's name): def input_view(request): input_obj = input_table() table_data = TableA.objects.order_by('id') input_dict = {'insert_me' : "Hello this is from views.py", 'dynamic_table' : table_data} if request.method == "POST": name = request.POST.get('name') roll = request.POST.get('roll') email = request.POST.get('email') password = request.POST.get('password') address = request.POST.get('address') if input_obj.is_valid(): #input_obj.save(commit=True) TableA.objects.create(name=name, roll=roll, email=email, password=password, address=address) return index(request) else: print("sorry cannot process") return render(request, 'app28/formpage.html', context=input_dict) in formpage.html: <div class="container"> <div class="jumbotron"> <h1>Welcome in django's table</h1> <form action="" method="post">{% csrf_token %} <input type="text" name="name" value="name"> <input type="text" name="roll" value="roll"> <input type="email" name="email" value="email"> <input type="text" name="password" value="password"> <input type="text" name="address" value="address"> <input type="submit" class="btn btn-primary" name="" value="submit"> </form> </div> </div> Please help to solve this problem. And what is the standard method to make html form interactive? -
I can not save one field in my Django REST API by PUT method
I can not edit/update field members. It is ArrayField, which i want edit by JSON { ... "members": [2,3], ... } All fields are editable except for the members field. The field stopped updating after adding search filters to it. What could be the problem? I have this code in module Company admin.py class ArrayFieldListFilter(admin.SimpleListFilter): title = 'Members' parameter_name = 'members' def lookups(self, request, model_admin): members = Company.objects.values_list("members", flat=True) members = [(kw, kw) for sublist in members for kw in sublist if kw] members = sorted(set(members)) return members def queryset(self, request, queryset): lookup_value = self.value() if lookup_value: queryset = queryset.filter(members__contains=[lookup_value]) return queryset # Register your models here. class CompanyAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'user', 'members', 'theme', 'date_created', 'description', 'status') list_display_links = ('id', 'name') list_filter = (ArrayFieldListFilter, 'name', 'user', 'members', 'date_created') admin.site.register(Company, CompanyAdmin) models.py # Create your models here. class Company(models.Model): members = ArrayField(models.IntegerField(blank=True), blank=True) ... serializers.py class AccountSerializer(serializers.ModelSerializer): user=serializers.StringRelatedField(read_only=True) class Meta: model=Account fields='__all__' class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class CompanySerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) members = serializers.SerializerMethodField() class Meta: model = Company fields = '__all__' #('id', 'name', 'description', 'date_created', 'user', 'status', 'theme', 'members') def get_members(self, obj): accounts = Account.objects.filter(id__in=obj.members) return AccountSerializer(accounts, many=True).data ... -
How to use Django rest api token in another app not connected to rest framework?
I have two apps, the first one use rest framework and tokens and the second one is the new app what i want to open for users who registered token in the first. -
How to check the status field in models django and send mail to the user
I wrote a fullstack django ticketing system for a company. Everything works, login, register, posting a ticket, database, send mail to admin. Only thing that is left is to check the status field of the ticket and if its true send an email to the user who posted it. Please help I have no clue how to do this. in the bellow code I have to figure out how to check status for being true and IF true send mail that the ticket was fixed Here it looks like this. ] 2 -
Access objects from another model - Django
Hi I have two models as below class IndexMaster(models.Model): index_id = models.IntegerField(primary_key=True) index_name = models.CharField(max_length=100) index_on = models.CharField(max_length=10) index_type = models.CharField(max_length=20) def __str__(self): return self.index_id class Meta: managed = True db_table = 'index_master' class IndexData(models.Model): index = models.ForeignKey(IndexMaster, on_delete=models.CASCADE) lifetime_high = models.FloatField() lifetime_low = models.FloatField() yearly_high = models.FloatField() yearly_low = models.FloatField() yesterdays_close = models.FloatField() day_high = models.FloatField() day_low = models.FloatField() todays_open = models.FloatField() lastvalue = models.FloatField() change = models.FloatField() percentchange = models.FloatField() class Meta: managed = True db_table = 'index_data' My serialiser.py looks like this from rest_framework import serializers from .models import IndexData class IndexSerializer(serializers.ModelSerializer): class Meta: model = IndexData fields = ['index' ,'day_high', 'day_low', 'lastvalue', 'change', 'percentchange'] def to_representation(self, instance): ret = super(IndexSerializer, self).to_representation(instance) return ret and views.py is like class IndexList(generics.ListAPIView): queryset = IndexData.objects.all() serializer_class = IndexSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get_queryset(self): query_params = self.request.query_params indexID = query_params.get('index_id', None) Q1 = Q(index_id = indexID) return IndexData.objects.filter(Q1) the issue is when I hit the url to get the JSON I get the following response HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "count": 1, "next": null, "previous": null, "results": [ { "index": 3.0, "day_high": 8867.2, "day_low": 8725.25, "lastvalue": 8746.85, "change": -97.95, "percentchange": -1.1 } ] … -
Create a django project in atom
I want to create a django project in atom but I don't know how ?? what packages I need for both atom and python and what I need to do ? OS:ubuntu 20.04