Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best Django model field to store frequency (from Hz to 10 GHz)
What is the best model field to store a frequency, from 1 Hz to 10 GHz? IMHO could be a PositiveBigIntegerField but I'm not completely convinced... Thank you -
How to save a pop up form (modal form) (field) having many-to-many relationship in Django?
I have got two models as shown in models.py. How well can it be done so that when creating a new object in the parent model it allows the data entry user to create one or more objects in the child model and link it to the parent model object using one form? models.py class ChildModel(models.Model): field = models.CharField() class ParentModel(models.Model): child = ManyToManyField(ChildModel) Case Example Let's have a parent and Children belonging to a parent. That is when creating a new parent you can attach his or her children's details. What I have tried I have joined both models using the many-to-many Django relationship. To attach the children to a parent, the first thing you need to do is create the children first, in a separate form, then select them from a list while creating the parent. Complains Is tiresome and not good when handling large data, for example, if there are 1000 children and you need to attach them to their respective parents. Project Screenshots parent creation form child creation form My Expectations The following image illustrates how a pop-up is generated when the green plus sign is clicked, a pop-up window appears having a child creation form … -
Django NoReverseMatch Reverse for 'conversation' not found
Hi I am currently facing a problem in redirecting the user to my directs-app. The NewConversation in directs/views.py starts a new conversation. It can be clicked in the profile-page user-profile.html of the users-app. Now I wanna do the same in my single-project.html in my projects-app. But I am getting the error above. Thanks for your help! directs/views.py def NewConversation(request, username): from_user = request.user body = '' try: to_user = User.objects.get(username=username) except Exception as e: return redirect('search-users') if from_user != to_user: Message.sender_message(from_user, to_user, body) return redirect('message') directs/urls.py urlpatterns = [ path('new/<username>', views.NewConversation, name="conversation"), ] users/models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True, null=True) username = models.CharField(max_length=200, blank=True) users/views.py def userProfile(request, pk): profile = Profile.objects.get(id=pk) context = {'profile':profile} return render(request, 'users/user-profile.html', context) users/user-profile.html <h2 class="dev__name">{{profile.name}}</h2> <img class="avatar avatar--xl dev__avatar" src="{{profile.profile_image.url}}" /> <a href="{% url 'conversation' profile.user %}" class="btn profile-edit-btn">Message</a> projects/views.py def project(request, pk): projectObj = Project.objects.get(id=pk) context = {'project':projectObj} return render(request, 'projects/single-project.html', context) projects/models.py class Project(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE) title = models.CharField(max_length=200) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) projects/single-project.html <div class="project__tags" style="margin-top: 20px;"> <a href="{% url 'conversation' project.owner.user %}">Send message</a> </div> -
How do I skip a test_utility file when running Python unittest?
I have a utilities package, and am including tests for some of the utilities. However, one of the directories has a bunch of django TestCase specific reusable classes, and it keeps running and failing when I run: python -m unittest The file's name is testutils.py and is for other Django apps to import and use, not to be tested itself. Is there a settings or skip file where I can tell my package not to look at that file when running tests? -
Django query (select, count where)
I'm trying to recreate the following sql query in the django ORM CASE WHEN (SELECT COUNT(id) FROM offer WHERE offer.product_id = p.id) < 1 THEN '[]'::JSONB ELSE ( SELECT JSON_AGG(JSON_BUILD_OBJECT('name', o_sub.name, 'status', o_sub.status)) FROM offer o_sub WHERE o_sub.product_id = p.id LIMIT 2 -- TWO IN PREVIEW LIST. )::JSONB END AS _offers But I haven't been hable to do it so far I had something like this: merchant_offers=Case( When( number_of_offers__lt=1 , then=JSONObject( offer_name="offers__name", offer_value="offers__merchant_group_fees__value" ) ), ) But i dont really know how to do the second query the one with the JSON_AGG -
django request.user always returns AnonymousUser despite a token being sent with the request
i have a class that beehives differently depending on if the user is authenticated or not: class SomeClass(APIView): authentication_classes = () permission_classes = () def get(self, request): if request.user.is_authenticated: # do something... else: # do something else... it used to work perfectly with django 3.2.5 and JSONWebTokenAuthentication. however i had to upgrade to django 4.x and TokenAuthentication... with: authentication_classes = (TokenAuthentication, ) the user is available but the request returns 401 to anonymous users... with: authentication_classes = () anonymous requests are accepted, but i can't see the data of authenticated users. -
Django Autocomplete Light not working with Django update from Django 3.1 to 4.1
The application I inherited was at Django 2.2. I have gradually updated to 4.1 and everything works except the Django Autocomplete Light fields. For some forms.ModelForm, I have a box with a correct list that can be selected but it does not have the ability to type the first few letters and select from that filtered list. Most of the autocomplete fields are on forms.Form and either display a dropdown box where the only choice is '-----', a scroll bar only with no list, or a box that is 2 x 47 pixels. I have gone through the DAL documentation but could not find a solution. I have searched here plus other Google searches but I have not found a solution. I do realize that parts of the code use the older URL pattern that includes ^, $, and ?P< items. I have tried to change these for one of the apps but it did not solve the issue. forms.py # Forms from django import forms from django.forms import ModelForm # Models from login.models import User from .models import Suggestion, SuggestionDecision, Implementation # Autocomplete from dal import autocomplete class ReviewForm(forms.ModelForm): class Meta: model = Suggestion fields = ['suggestion', 'supervisors', 'managers'] … -
Moving Django models between "apps" - easy and fast
In my company's Django project, our models are currently spread across about 20 "app" folders with little rhyme or reason. We'd like to consolidate them into a single new app (along with the rest of our code) so that in the future, we can refactor all parts of our system at-will without worrying about violating an "app" boundary. Due to how Django works, simply moving the model breaks everything. I've spent hours reading everything I can about the various proposed solutions to this problem, with the best article being: https://realpython.com/move-django-model/ So far, I'm not happy with any of the solutions I've come across. They're all just too onerous. If I do the following: Move all models to the new app. (Let's call it "newapp".) Update all references in the code to the previous locations. (Including migration files.) Take down the site for a minute. Run a script to rename all database tables from someprevapp_model to newapp_model. Run a script to update app_label for all rows in the django_content_type table. Deploy latest codebase version, with updated model locations and references. Turn site back on. Have I succeeded, or am I missing something? UPDATE Just remembered - I'd also have to: 5.5) … -
Annotating without using Exists or SubQuery
I have a client who is using Django 1.8. While they will be moved to the latest version, we need to run some queries before their migration, but obviously we can't use Exists or OuterRef. In our case we want to annotate a queryset. eg recordset = Question.objects.annotate( has_answers=Exists(Answers.objects.filter(question=OuterRef('pk'))) ) Is there a workaround to do the equivalent of the above annotation. What did people use in 'the olden days'? -
Errors only happen when running django server with pipenv
I have a django project which runs with no errors when run without any virtual enviroments. But when i run my server inside a after writing the command python -m pipenv shell then python manage.py runserver I encounter a few errors such as syntax errors when the syntax is perfectly normal and module import errors which would never occur without using pipenv errors: url = f"https://resources.premierleague.com/premierleague/photos/players/110x140/p{photo_id}.png" - invalid syntax ImportError: No module named 'PIL' (import worked outside of pipenv) -
set user foreign key default value as superuser or admin on on_delete=models.SET_DEFAULT
As I was using on_delete=models.CASCADE with currentOwner in the asset model, whenever I deleted any user, all the assets owned by that user were getting deleted. I want the asset to be transferred to the superuser/admin. So I tried # MY SOLUTION but it is throwing me an error: ValueError: Field 'id' expected a number but got 'admin'. I think deleting previous migrations and running makemigrations and migrate commands might help, but that will probably erase all the data in the database, which I do not want to happen. Here are my User and asset models: class User(PermissionsMixin, AbstractBaseUser): username = models.CharField(max_length=32, unique=True, ) email = models.EmailField(max_length=32) gender_choices = [("M", "Male"), ("F", "Female"), ("O", "Others")] gender = models.CharField(choices=gender_choices, default="M", max_length=1) nickname = models.CharField(max_length=32, blank=True, null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) REQUIRED_FIELDS = ["email", "gender"] USERNAME_FIELD = "username" objects = User_manager() def __str__(self): return self.username class asset(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, null=False) asset_type = models.ForeignKey('assetType', on_delete=models.CASCADE, null=True) asset_name = models.CharField(max_length=30, null=True) #unique=True location = models.CharField(max_length=30, null=True) brand = models.CharField(max_length=30, null=True) purchase_year = models.PositiveIntegerField(blank=True, null=True) isActive = models.BooleanField(default=True, null=True) currentOwner = models.ForeignKey(User, default=User.objects.get(is_superuser=True).id, null=False, on_delete=models.SET_DEFAULT) # MY SOLUTION Is there any way this can be solved? -
Elegantly spread single Django model across multiple tables?
There's plenty of document and discussion for having multiple models share fields in a parent class/table using "concrete" or "multi-table" inheritance: class Place(models.Model): ... class Restaurant(Place): ... However, I can't find much on the inverse use-case: splitting the fields of a single model across multiple tables to save the cost of loading wide columns except when you actually need them. Consider the following scenario: class Person_Profile(models.Model): ...lots of fields... class Person_Preferences(models.Model): ...lots of fields... class Person(Person_Profile, Person_Preferences): ...small set of core fields... What works: When you create a Person, the other two objects are automatically created and linked for you. You can access profile and preference fields directly on Person. (person.some_field) The only thing I'm missing is how to elegantly control when Django loads the fields from the parent table, since currently, loading a Person with p = Person.objects.first() results in all three tables being joined and selected by default. -
How to separate the image model from the other models and create relation between it and others and create more than one image for a object
I want to make an image model and some other models that may have several photos for each object. How can I implement it in Django and Rest Framework? -
I receive an error while migrating my models to a database
I get such an error while migrating to a database: return Database.Cursor.execute(self, query) django.db.utils.OperationalError: foreign key mismatch - "user_auth_customer" referencing "user_auth_profile" I have checked Foreign_Keys of my models and they look good. I have no idea why I receive that error :( Please, help me out here. class Customer(AbstractUser): USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) profile = models.OneToOneField("Profile", related_name="user_profile", on_delete=models.CASCADE, null=True) first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) username = models.CharField(max_length=30, null=True, blank=True) phone = models.CharField(max_length=10, default='', null=True, blank=True) email = models.EmailField(validators=[validators.EmailValidator()], unique=True) password = models.CharField(max_length=100, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) @staticmethod def get_customer_by_email(email): try: return Customer.objects.get(email=email) except: return False def isExists(self): if Customer.objects.filter(email=self.email): return True return False class Meta: verbose_name = 'Customer' verbose_name_plural = 'Customers' class Profile(models.Model): first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) phone = models.CharField(max_length=10, default='', null=True, blank=True) email = models.EmailField(primary_key=True, unique=True, validators=[validators.EmailValidator()]) password = models.CharField(max_length=100, null=True, blank=True) # Add a photo field owner = models.OneToOneField(Customer, related_name='profile_owner', on_delete=models.SET_NULL, null=True) username = models.CharField(max_length=30, null=True, blank=True, validators=[UnicodeUsernameValidator()]) date_created = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Profile' verbose_name_plural = 'Profiles' if you need any else details, I can provide you with those in the comments. -
Django hidden input being rendered as <td> in html
I'm using a modelformset to allow the user to add/edit/delete food item's on their restaurant's menu. FoodItemFormset = modelformset_factory(FoodItem, fields = '__all__', can_delete = True) I'm then iterating over all of the forms in my template and displaying them in a table: <table> <tr> <th>Food Item</th> <th></th> <!-- empty <th> lines up with hidden input field --> <th>Delete</th> </tr> {% for form in food_formset %} <tr> {% for field in form %} <td>{{ field }}</td> {% endfor %} </tr> {% endfor %} </table> <input type="submit" name="" value="Submit"> However, that can_delete attribute does not only lead to a checkbox being rendered, it also renders the hidden field containing the object's id as an actual table element, leading to an empty gutter between the tables contents. <td><input type="text" name="form-0-name" value="Mozzarella Sticks" maxlength="200" id="id_form-0-name"></td> <td><input type="hidden" name="form-0-id" value="2" id="id_form-0-id"></td> <!-- this just looks like an empty gutter --> <td><input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE"></td> Is there a way to get around this? Thanks for any help. -
In Django Debug request url shown as http instead of https
sorry if the message reads weird: it was originally intended for django support. Let me give a little bit of context to the issue. Recently, my team has upgraded the packages of our app, one of those packages being Django, from 2.2 to 3.2.13. The only thing in this commit are the changes of packages. There is an endpoint on our app that has been tested on a local host and deployed to a dev server and a QA/Test server, and has worked as intended. However, this endpoint fails on our prod deployment, with the ssl issue that you are seeing before you. I was wondering if this has anything to do with the request URL being shown as an http rather than an https. As you can see, the page that we are on shows it’s an https, differing from the Django debug which is showing as an http. Question 1: Am I correct to assume the request being made is an http even though the URL shows as an https? My hypothesis is that this issue is only manifesting itself in production because our prod environment wont allow traffic over http. If this is the case, I am … -
Django keeps replacing content on the view
I have multiple text files in a folder, which all of them created dynamically from Cisco Switches. I want to read each file and display on the web. So I have this code: def idf(request): context = {} all_files = os.listdir("devices/") for i in all_files: with open(i, 'r') as readFile: switch_ports = readFile.readlines() print(switch_ports) readFile.close() context.update({'switch_ports': switch_ports}) return render(request, 'idf.html', context) The problem is, it loops through the function, and only renders the last file. So it is basically replacing the content. How can I keep all of them? So they just keep appending to the last file? Here is the template: {% block everyDevice %} {% block switch_ports %} <h1>{{ everyDevice }}</h1> {% for result in switch_ports %} <p>{{ result }}</p> {% endfor %} {% endblock %} {% endblock %} </main> -
Open an image in python and upload it to S3
I was trying to open a file/image in python/django and upload it to s3 but I get different errors depending on what I try. I can get it to work when I send the image using the front end html form but not when opening the file on the back end. I get errors such as "'bytes' object has no attribute 'file'" Any ideas how to open an image and upload it to s3? I wasn't sure if I was using the correct upload function, but it worked when I received the file from an html form instead of opening it directly. image = open(fileURL, encoding="utf-8") S3_BUCKET = settings.AWS_BUCKET session = boto3.Session( aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, ) s3 = session.resource('s3') s3.Bucket(S3_BUCKET).put_object(Key='folder/%s' % fileName, Body=image) Thanks. -
Django: How to make a simple editable text? [closed]
I have a a simple information page, but I need to change the information a lot. I want to do this from the admin side. I can do this with a model, but I don't need to add or remove items. How can I do this? -
Django image cropping in ilineformset
I'm trying to make inline formset which one field gets chopped image as one of parameters. I have already done cropping with help of some tutorials but it works only with single model, when I tried to transform it to inline formset, new image is being saved in raw form - cropping isn't getting applied. models look like that: class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) availability = models.IntegerField() price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.name def get_image_url(self): return Image.objects.get(product=self).file.url class Photo(models.Model): file = models.ImageField(upload_to=getImageURL2, default="static/default.png") uploaded = models.DateTimeField(auto_now_add=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return str(self.pk) forms: class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = ('file',) ProductPhotoInlineFormset = inlineformset_factory( Product, Photo, fields=('file',), form=PhotoForm, extra=1, can_delete=False, ) views: def ProductCreateView(request): context = {} created_product = None form = ProductForm() if request.method == 'POST': print(request.POST) form = ProductForm(request.POST) if form.is_valid(): created_product = form.save() print("Successfully created new product: {}".format(created_product)) else: print("form is not valid") print(form.errors) print(form.non_field_errors()) context['form'] = form created_images = [] formset = ProductPhotoInlineFormset() if request.method=='POST': formset = ProductPhotoInlineFormset(request.POST or None, request.FILES or None, instance=created_product) if formset.is_valid(): for f in formset: image = f.save() created_images.append(image) print("Successfully created new imagest: {}".format(image)) return JsonResponse({'message': 'works'}) else: print(formset.errors) … -
Dropdown filtering objects in django template using javascript
I have a table that shows details about all the assets. I want the records in the table to be filtered on the basis of different attributes of the table. For now I have tried to create a filter on currentOwner field using JavaScript, but it is not working. Here is the html file: {% extends "assets/base.html" %} {% block content %} <div class="container"> <legend class="border-bottom mb-4">Hello {{ request.user }}</legend> </br> <table class="table" id="admin-asset-table"> <tr> <th>Asset ID</th> <th>Asset Type</th> <th>Asset Name</th> <th>Brand</th> <th>Is Active</th> <th> <select id="searchddl" onclick="searchOwner();"> <option disabled="true" selected>-- Current Owner --</option> {% for user in users %} <option value="{{asset.currentOwner}}"> {{user.username}} </option> {% endfor %} </select> </th> <!-- <th>Current Owner</th> --> </tr> {% for asset in assets %} <tr> <td><a href="{% url 'asset-update' id=asset.id%}">{{ asset.id }}</a></td> <td>{{ asset.asset_type }}</td> <td>{{ asset.asset_name }}</td> <td>{{ asset.brand }}</td> <td>{{ asset.isActive }}</td> <td>{{ asset.currentOwner }}</td> </tr> {% endfor %} </table> </div> <script type="text/javascript"> function searchOwner() { var input,table,tr,td,filter,i; input=document.getElementById("searchddl"); filter=input.value.toUpperCase(); table=document.getElementById("admin-asset-table"); tr=table.getElementsByTagName("tr"); for(i=0; i<tr.length; i++) { td=tr[i].getElementsByTagName("td")[3]; if(td) { displaydata=td.innerText; if(displaydata.toUpperCase().indexOf(filter)>-1) { tr[i].style.display=""; } else { tr[i].style.display="none"; } } } } </script> {% endblock content%} Please let me know what is wrong with this. Also let me know if there is any … -
Count number of times object appears in Foreign Key with filter
My models are as so: class TeamMember(models.Model): name = models.CharField(max_length=500) class Opportunity(models.Model): name = models.CharField(max_length=500) date_created = models.DateTimeField( auto_now=True) team_lead = models.ForeignKey('TeamMember', blank = False, related_name = 'lead_opps') I need to create a list of team member names with the number of opportunities they have taken part of ordered by the count. This is straightforward using the method below, however- I also need to limit the opportunities by date range. So to summarize, I need to create a list of team members with the number of opportunities they have taken lead on within a time range. How do I add a filter to the opps being counted within the annotation? Here is what I have so far: TeamMember.objects.annotate(num_opps = Count('lead_opps')).order_by('-num_opps')[0].num_opps -
OperationalError at /register no such table: class_profile
I am getting this error when creating new users. Any help would be appreciated, thank you. I haven't added anything in my settings.py like AUTH_USER_MODEL = 'class.User' My models.py: from pyexpat import model from django.contrib.auth.models import User from django.core.checks.messages import CheckMessage from django.db import models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) institution = models.CharField(max_length = 100) bio = models.TextField(max_length=300) def __str__(self): return f'{self.user.username} Profile' My views.py: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) profile_form = ProfileForm(request.POST, request.FILES) if form.is_valid() and profile_form.is_valid(): user = form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() profile_form = ProfileForm() return render(request, 'class/register.html', {'form': form, 'profile_form': profile_form}) -
What is causing this error when i try to deploy my django project to heroku
ERROR: Ignored the following versions that require a different python version: 1.9.5 Requires-Python >=2.7, !=3.0., !=3.1., !=3.2., !=3.3., <3.7 remote: ERROR: Could not find a version that satisfies the requirement pywin32==304 (from versions: none) remote: ERROR: No matching distribution found for pywin32==304 remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to *************. -
Validation error message isn't showing in django
The validation error Password not matched isn't showing if I separately access the fields like {{form.psrd}} (password field) and {{form.rpsrd}} (Re-Type password field). But error message shows if I use {{form.as_p}}. This is my forms.py: from django import forms class formdata(forms.Form): name = forms.CharField( max_length=20, widget=forms.TextInput(attrs={'class': 'input'})) email = forms.EmailField(widget=forms.TextInput(attrs={'class': 'input'})) psrd = forms.CharField(min_length=8, widget=forms.PasswordInput( attrs={'class': 'input'}), label='Password') rpsrd = forms.CharField(min_length=8, widget=forms.PasswordInput(attrs={'class': 'input'}), label='Re-Type Password') def clean(self): cleaned_data = super().clean() p = self.cleaned_data['psrd'] rp = self.cleaned_data['rpsrd'] if p != rp: raise forms.ValidationError('Password not matched') Body of regi.html : <body> <form method="post">{% csrf_token %} <label> <p class="label-txt">ENTER YOUR NAME</p> {{form.name}} <div class="line-box"> <div class="line"></div> </div> </label> <label> <p class="label-txt">ENTER YOUR EMAIL</p> {{form.email}} <div class="line-box"> <div class="line"></div> </div> </label> <label> <p class="label-txt">ENTER YOUR PASSWORD</p> {{form.psrd}} <div class="line-box"> <div class="line"></div> </div> </label> <label> <p class="label-txt">RE-ENTER YOUR PASSWORD</p> {{form.rpsrd}} <div class="line-box"> <div class="line"></div> </div> </label> <button type="submit">submit</button> </form> </body>