Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: '_Environ' object has no attribute 'Env'
i am trying to host a website in google cloud in settings.py file need to write some code after writing the code i am facing below error env = environ.Env(DEBUG=(bool, False)) AttributeError: '_Environ' object has no attribute 'Env' -
Follow Public/Private user validation for serializer
I have a User and UserFollow model. Author is the following user,Profile is the user that is followed. Now i am using Token authentication to validate users for unauthorized requests. Here is what i want to put into validation but i don't know how to do it: Pseudocode if profile.public_profile == true if attrs['author'].id != self.context['request'].user: raise ValidationError('Unauthorized Request') if profile.public_profile == false if attrs['profile'].id != self.context['request'].user: raise ValidationError('Unauthorized Request') I don't know how to put multiple IF conditions under a validation. How can i do it? Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username =models.CharField(max_length=40,unique=True,default='undefinedusername') public_profile = models.BooleanField(default=True) class UserFollow(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') profile = models.ForeignKey(User,on_delete=models.CASCADE,related_name='followers') Serializers.py class UserFollowSerializer(serializers.ModelSerializer): class Meta: model = UserFollow fields = ('id',"author","profile") def validate(self, attrs): attrs = super().validate(attrs) if attrs['author'].id != self.context['request'].user: raise ValidationError('Unauthorized Request') return attrs -
Cannot get data into my database using django model forms
The form I created is not inserting the data into my database table. As far as I can tell I've done everything correctly but it still refuses to do so instead it "post" in the console and clears the form fields without creating nothing in the database. None of the data that entered is saved anywhere? Here are the files below hopeful someone can see something I'm missing. ps. I've connected my database, ran migrations and created a superuser as well but still nothing. models.py from django.db import models Media_Choices = ( ("TV", "TV"), ("Radio", "Radio"), ("Youtube", "Youtube"), ("Podcast", "Podcast"), ) class Appear(models.Model): Show = models.CharField(max_length=100) Media = models.CharField(max_length=30, blank=True, null=True, choices=Media_Choices) Episode = models.IntegerField() Date = models.DateField(max_length=100) Time = models.TimeField(auto_now=False, auto_now_add=False) Producer = models.CharField(max_length=100) Producer_Email = models.EmailField(max_length=254) def __unicode__(self): return self.Show + ' ' + self.Producer_Email forms.py from django import forms from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Appear class AppsForm(ModelForm): class Meta: model = Appear fields = '__all__' def clean_Producer_Email(self): Producer_Email = self.cleaned_data.get('Producer_Email') if (Producer_Email == ""): raise forms.ValidationError('field cannot be left empty') for instance in Appear.objects.all(): if instance.Producer_Email == Producer_Email: raise forms.ValidationError('Please fill in correct email') return Producer_Email views.py from django.shortcuts import redirect, … -
How to simulate two parallel requests in django testing framework
I have a Django application (using uWSGI and nginx, and atomic views) with a view that creates new items of a model in the DB (postgres). Before creating anything the view checks if the record doesn't already exist in the DB, something like: ... try: newfile = DataFile.objects.get(md5=request.POST['md5']) except DataFile.DoesNotExist: newfile = DataFile.objects.create(md5=request.POST['md5'], filename=request.POST['filename']) return JsonResponse({'file_id': newfile.pk}) I noticed sometimes this doesn't work, and I get duplicates in the DB (which is easily solved with a unique constraint). I'm not sure why this happens, if there is caching or race conditions, but I'd like to at least cover the behaviour with a test in the Django test framework.However, I do not know how to simulate two parallel requests. Is there a way to fire the next request while not waiting for the first, built into the framework, or should one use multiprocessing or similar for this? -
How to send chat messages to other users
I want to send messages to other users so that I can have a discussion with them on the messenger. models.py class Message(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null = True, on_delete= models.CASCADE, related_name='user') receiver = models.ForeignKey(settings.AUTH_USER_MODEL, null = True, on_delete= models.CASCADE, related_name='receiver') message = models.CharField(max_length=300) time = models.DateTimeField(auto_now_add=True) time_seen = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['time'] def __str__(self): return self.message -
ImportError: No module named 'django' [closed]
I am using django to make my site on server. But, I get the error. from django.core.wsgi import get_wsgi_application ImportError: No module named 'django' I try to add some code in wsgi.py, but I still can't fix it. import os, sys sys.path.append('<PATH_TO_MY_DJANGO_PROJECT>/ueuuop8591_project') sys.path.append('<PATH_TO_VIRTUALENV>/Lib/site-packages') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ueuuop8591.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
Tabulator breaks after setData is being called first time
I have a weird bug in my application using Tabulator by @Oli Folkerd: After refreshing the table I always end up with having 20 rows instead of my preset 25 rows: I checked the response from my django ViewSet and the answer always contains the right amount of objects. js Code: var table = new Tabulator("#ptable", {height:"100%", layout: "fitData", pagination: "local", paginationSize: 25, paginationSizeSelector: [50, 100], ajaxURL: "api/products", columns: cols,}); setInterval( function () { table.setData(); }, 10000); becomes: I am happy to post code on the django part as well, but I do not think thats the problem here. Also interesting: When I click on a random page number in the footer I always get to see 20 items per page - except if I choose the last one. -
Django generate PDF css error and rendering is slow
I want to print my products in Django as PDF. But because the file size is very large, it takes minutes to load. My CSS styles are not applied either. If your need another codeblocks, I will share with you. If you give me the source, I can take a look at it. def render_pdf_view(request): .......my context codes....... template_path = 'catalogmakerpdf.html' context = { 'products': products, } response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="report.pdf"' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF( html, dest=response, link_callback=link_callback) if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response utils.py (imported views.py) from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result, link_callback=fetch_resources) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None def fetch_resources(uri, rel): path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, "")) return path -
Django Generate List of Opposite Models
I am trying to develop a program that will determine what plants are beneficial and harmful to other plants. I want it to be able to run through a list of plants and compare and see if one plant's deters_insects_and_animals species matches the other plant's pests then it adds it to the list in ally_deter_pests_for(self): I'm not really sure how to do that. class AnimalSpecies(models.Model): common_name = CharField(max_length = 200, null = True, blank = True) scientific_name = CharField(max_length = 200, null = True, blank = True) genus = Foreign Key(Genus, null = True, blank = True, on_delete = models.CASCADE) class Meta: verbose_name = "Animal Species" verbose_name_plural = "Animal Species" def __str__(self): return self.common_name #___________________________________________________________________________________Begin Species_______________________________________________ class PlantSpecies(models.Model): #________________________Name & Relationships________________________ common_name = CharField(max_length = 200, null = True, blank = True) species_name = CharField(max_length = 200, null = True, blank = True) genus = ForeignKey(Genus, blank = True, null =True, on_delete = models.CASCADE) rotation_family = ForeignKey(RotationFamily, blank = True, null = True, on_delete = models.CASCADE) #________________________Growth & Environment________________________ annual = BooleanField(null = True, blank = True) GROWTH_HABIT_LIST = [ ("H", "Herb"), ("S", "Shrub"), ("T", "Tree"), ("U", "Succulent"), ("G", "Grass"), ("F", "Fern"), ("V", "Vine") ] growth_habit = CharField(max_length = 20, … -
How to add multiple owners to the django filer folders?
I want to add multiple owners to the django filer user created folders. Is it possible if not what can be the alternative solutions to this ? I can see here https://github.com/django-cms/django-filer/blob/master/filer/models/foldermodels.py that owner has FK with the Folder but can we change it to ManyToMany so that I can add multiple owners to the folder. Anyone out there with experience on django-filer ? -
My friend request module for my app doesnt work
I am implementing a friend module into my app and it has errors with the friend request part. I want it so that when the someone puts a username into the form and clicks submit, it POSTs the username to the same page. Then my app does quick search thru the user table and if it find the username it adds the person who sent the request to the requestee's manytomany field. But when I tried it, it did in fact succeed add the request, but for some reason it also added a friend request to the requestors m2m with it saying its from the requestee. My view for the friend requesting: def friends(request): friendreqs = request.user.friendreq.all() friends = request.user.friends.all() if request.method == "POST": try: requestee = User.objects.get(username=request.POST["username"]) requester = request.user requestee.friendreq.add(requester) return render(request, "alumnas/friends.html", { 'requests': friendreqs, 'friends': friends }) except ObjectDoesNotExist: return render(request, "alumnas/friends.html", { 'message': "User not found :(", 'requests': friendreqs, 'friends': friends }) else: return render(request, "alumnas/friends.html", { 'requests': friendreqs, 'friends': friends }) The html: {% extends "alumnas/layout.html" %} {% block body %} <div class="contain"> <h1>Friends</h1> <div class="findfr"> <p>Know anyone already? Find out if they're here and connect!</p> <form action="{% url 'friends' %}" method="POST"> {% csrf_token … -
Django: Get the ManyToMany object of ManyToManyField
I know I can fetch all authors of literature like: paper.authors.all() This works fine, but just returns me a QuerySet of Authors. But I want the ManyToMany Object like (because I want to sort after the ID's) (id (BigAutoField), paper, author) Is there a faster way to do it then: Paper.authors.through.objects.all().filter(paper=paper) Because my Database is really Large ~200 million entries, the command above is not feasible -
How to apply one to many relationship in my situation?
I am new in Python Django.I have a question in one situation.As you see in the photos,I have an application.Firstly Users can login system and they can add new item to list.Problem is that when all users login,they are adding items to the same database.For example when 2 users login,they will see same items.I want apply specific list for each user.When each user login,they should see their own list.I know that I have to apply one to many relationship but I don't know how can I do this.I am adding screenshots of related codes. note: my item's model name is Student Application view after login Models.py file(Student model is for item views.py Item database registered user for authentication -
how to split post value based on key in django
how to split my post value based on key and i will save to table this values My post data [('include_product_id[x_98342]', '2'), ('product_name[x_98342]', 'item_one'), ('product_qty[x_98342]', '5'), ('product_price[x_98342]', '1'), ('total_amount[x_98342]', '5'), ('include_product_id[x_647057]', '14'), ('product_name[x_647057]', 'item_two'), ('product_qty[x_647057]', '61'), ('product_price[x_647057]', '1'), ('total_amount[x_647057]', '61')] -
Deploying Django on Apache
I want to deploy django with anaconda project on Apache I name myapp as for both my project and anacond environment. My conf file lis like this. When accessing with browser , it stuck and nothing returns. There is no log in api_myapp_error.log and api_myapp_access.log curl api.myapp.net also stuck I am not even sure where stuck happens. So where to start??? <VirtualHost *:80> ServerName api.myapp.net ServerAdmin webmaster@localhost DocumentRoot "/var/www/html/myapp/current/" ErrorLog ${APACHE_LOG_DIR}/api_myapp_error.log CustomLog ${APACHE_LOG_DIR}/api_myapp_access.log combined <Directory /var/www/html/myapp/current/> <Files wsgi.py> Order allow,deny Allow from all </Files> Order allow,deny Allow from all </Directory> <Directory /var/www/html/myapp/current/static> Order allow,deny Allow from all </Directory> WSGIScriptAlias / /var/www/html/myapp/current/myapp/wsgi.py Alias /static/ /var/www/html/myapp/current/static/ </VirtualHost> LoadModule wsgi_module /home/ubuntu/anaconda3/envs/myapp/lib/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so WSGIDaemonProcess myapp user=ubuntu group=ubuntu python-path=/home/ubuntu/anaconda3/envs/myapp/lib/python3.7/site-packages WSGIPythonHome /home/ubuntu/anaconda3/envs/myapp/ WSGIPythonPath /var/www/html/myapp/current/ -
ModelName matching query does not exist. Problem working with loaddata
I am trying to use loaddata in Django to load a json file in my database. But I receive the following traceback when doing the same Traceback (most recent call last): File "D:\env\lib\site-packages\django\db\models\fields\related_descriptors.py", line 173, in __get__ rel_obj = self.field.get_cached_value(instance) File "D:\env\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'loan_application' During handling of the above exception, another exception occurred: loan_tracker.models.DoesNotExist: Problem installing fixture 'C:\Users\Desktop\db_try2.json': LoanData matching query does not exist. There are similar problems that have been asked for the same but none of them work for my case loan_application is a foreign key to a different model here. I have used the following approach to address this problem . Checked the format of my json file that is accepted for loaddata. Checks out Used DISABLE TRIGGER ALL for any foreign key constraints that may cause this to happen. Used the loaddata --ignorenonexistent keyword to ignore fields and models that may have been removed. But nothing seems to work here. Would appreciate a new approach that could be applied to get this model to load in my DB. P.S : I cannot exclude this model as it will affect other models that are dependent on it. -
Django create model with relation using dynamic fields
I have a hard time coming up with a way to dynamically add fields to my form using jQuery. I have a Customer model which has a MtO relation with a Contacts model and a Reference model. After filling in the customer's info, there are 5 fields needed per contact. But the hard part is they can add up to 5 contacts, so I use Javascript to append the html needed to get more sets of 5 forms. But how do I actually make these fields work with Django? index.html: <div class="row g-1" id="contactRow"> <div class="col-md-5"> <select class="form-select mb-2" aria-label="Contact types"> <option style="font-weight:bold" value="" selected disabled>Type</option> {% for type in contact_types %} <option>{{ type.name }}</option> {% endfor %} </select> <div class="form-floating form-floating-group flex-grow-1 mb-2"> {{ form.contact_name }} <label for={{ form.contact_name.id_for_label }}> {{ form.contact_name.label }} </label> </div> <div class="form-floating form-floating-group flex-grow-1 mb-2"> {{ form.contact_funct }} <label for={{ form.contact_funct.id_for_label }}> {{ form.contact_funct.label }} </label> </div> <div class="form-floating form-floating-group flex-grow-1 mb-2"> {{ form.contact_email }} <label for={{ form.contact_email.id_for_label }}> {{ form.contact_email.label }} </label> </div> <div class="form-floating form-floating-group flex-grow-1 mb-2"> {{ form.contact_phone }} <label for={{ form.contact_phone.id_for_label }}> {{ form.contact_phone.label }} </label> </div> </div> main.js: $("#addContact").click(function () { let form_count = $('input[name*="extra_contact_*"]').length; let html = ''; … -
how the user model attach with the django request?
can anyone explain how the django User model getting attached with the request after the successful login. By the same can we attach some other models with django request. I know we can use cookies or sessions instead of this but i am curious about how this happening. Anyone know the answer please help. -
How to take only the 5 element of an array while using loop ijn Django? [closed]
I can not take the exact number of elements from an array while I am using a loop. Consider there are 10 elements in an array [1,2,3,4,5,6,7,8,9,10] and I need only the first five elements [1,2,3,4,5] I should reach them using for loop. These all are in Django. Please tell me if someone knows the answer. -
How to retrieve different type of data in django?
I created an attendance management system and I want to retrieve the different types of date from the table. Like, In my attendance table, there are different date but some date is repeated ex - for every date, there are number of users has attendance staff table. attendance table id = 1 id = 1 name = john staff_id = 1 date = 31.08.2021 id = 2 attendance = present name = harry id = 2 staff_id = 2 date = 31.08.2021 attendance = absent id = 3 staff_id = 1 date = 01.09.2021 attendance = present id = 4 staff_id = 2 date = 01.09.2021 attendance = present from the above table data I wanted to retrieve the only date without repetition so when we write code the answer will be 31.08.2021 01.09.2021 this is my template file {% for attendances in attendance %} <th>{{ attendances.date }}</th> // here i want to retrive 31.08.2021 and 01.09.2021 {% endfor %} This is my views file def index(request): staffs = staff.objects.all() attendances = attendance.objects.all() date = datetime.date.today() return render(request, "salary/index.html", {'staff': staffs, 'attendance': attendances, 'date': date}) -
Logging out on django web app redirects to django admin logout page. What's going on?
I'm following a tutorial in the Python Crash Course book on creating a simple web page using Django. I've just created an app to log a user in and out on my page, using Django's default user authentication system. When I logout, Django is not redirecting to the template I've created to show that the user is logged out. Instead it redirects to the Django admin logout page. Here is my base urls.py file. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), path('', include('learning_logs.urls')), ] Here is my 'users' app url.py file. from django.urls import path, include app_name = 'users' urlpatterns = [ # Include default auth URLs path('', include('django.contrib.auth.urls')), ] Here is my base.html template. <p> <a href="{% url 'learning_logs:index' %}">Learning Log</a> - <a href="{% url 'learning_logs:topics' %}">Topics</a> {% if user.is_authenticated %} Hello, {{ user.username }}. <a href="{% url 'users:logout' %}">Log out</a> {% else %} <a href="{% url 'users:login' %}">Log in</a> {% endif %} </p> Here is my logout.html template. {% extends "learning_logs/base.html" %} {% block content %} <p>You have been logged out. Thanks for stopping by!</p> {% endblock content %} Here are my installed apps in settings.py NSTALLED_APPS = [ … -
Dynamic particular field on a form in Django?
I have a form which has more than 10 fields. Now i want a particular field, lets say "requirements". This can be more than one requirement, i can deal with that using rich text editor as ask my user to input all the requirements as a ordered list. But for better user experience i am asking this ! I am gonna keep a button under "requirements" field, so that user can click on this button to get a new field. By this, i want all fields to be combined in a dict like requirements = {'field1','extrafield1'} and etc How to perform this ? I cant user formset ( as am just adding dynamic field not whole form ) How to deal this with django forms ? -
Value of select field from a django for loop in template and passing seledted field value via ajax to server side django
I have a static select option in my template within a customer orders for loop.. now i want to change status (select) via js and send the data back to django view. but how am i suposed to do that. i have tried in many ways but nothing seems to work -
Django create unique function index
With postgresql we can create unique function index: create unique index user_date_checkin on unique_user_date (user_id, (timezone('UTC'::text, create_time)::date)); But with Django 3.2: class UserCheckin(GeneralModel): id = models.BigAutoField(primary_key=True) user_id = models.BigIntegerField() create_time = models.DateTimeField() class Meta: indexes = [ models.Index("user_id", TruncDate("create_time"), name="user_date_checkin"), ] can only got such sql generation: create index user_date_checkin on test (user_id, (timezone('UTC'::text, create_time)::date)); And UniqueConstraint constraints = [ models.UniqueConstraint( fields=["user_id", TruncDate("create_time")], name="user_date"), ] got refers to the nonexistent field 'TruncDate(F(create_time)) error So how can I create unique index with function in Django 3.2? -
Git bash "Watching for file changes with StatReloader" stuck and never loads
I have setup a Django project on a virtual environment on my PC. When using the command python manage.py runserver 0.0.0.0:8000 Bit Bash stops doing anything and I have to end the program to start over. I have waited several minutes and when I end the session, a dialogue says: Processes are running in session: WPID PID COMMAND 14904 1534 c:\Users\mine\AppData\Loca Close anyway? I have looked at every related question to this and tried every solution but I cannot get this to work, on or off the virtual environment.