Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Is there a way to make sure that only a unique FK related object can be added/related to the PK object?
Say there is a poll app and I want a user to vote only once for a poll question. Assume models.py to be as follows, class PollUser(models.Model): username = models.CharField(max_length=120, unique=True) class PollQuestion(models.Model): question = models.CharField(max_length=250) issuing_user = models.ForeignKey(PollUser, on_delete=models.CASCADE) class PollChoice(models.Model): text = models.CharField(max_length=250) votes = models.PositiveIntegerField(default=0) Is there a way to implement this functionality, without making this check in the views? -
Django Rest Framework: How to properly test a ViewSet?
I'm new to testing in DRF. I have the following ViewSet where I'm only allowing the 'List' and 'Retrieve' actions: class RecipeViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): permission_classes = [permissions.AllowAny] queryset = Recipe.objects.filter(visible=True).order_by('-created') pagination_class = RecipeListPagination lookup_url_kwarg = 'recipe_id' def get_serializer_class(self): if self.action == 'list': return RecipeListSerializer elif self.action == 'retrieve': return RecipeDetailSerializer These are the tests I've written so far: class RecipeViewSetTestCase(test.APITestCase): def setUp(self): # Create objects self.category = RecipeCategory.objects.create(name="meals") Recipe.objects.create(name="Pepperoni Pizza", category=self.category, description="It's rounded") Recipe.objects.create(name="Beef Ragu", category=self.category, description="It's moo'") # Get urls self.recipe = Recipe.objects.first() self.list_url = reverse('recipes-list') self.detail_url = reverse('recipes-detail', kwargs={'recipe_id': self.recipe.id}) def test_recipe_list(self): response = self.client.get(self.list_url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['results']), 2) def test_recipe_detail(self): response = self.client.get(self.detail_url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['name'], self.recipe.name) def test_recipe_create_not_allowed(self): response = self.client.post(self.list_url) self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) def test_recipe_delete_not_allowed(self): response = self.client.delete(self.detail_url) self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) def test_recipe_update_not_allowed(self): response = self.client.put(self.detail_url) self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) def test_recipe_partial_update_not_allowed(self): response = self.client.patch(self.detail_url) self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) I'm not sure if it's necessary to write a test for each method that shouldn't be allowed, or if there is a better way. Also, I'm not sure of what else I should be testing inside this viewset. Does anyone with experience in testing DRF knows how to properly test viewsets? Many thanks! -
django-tenant: tenant-aware file handling issue
I have a django project working with django-tenant. I want to segregate the templates in a way that tenants have custom templates. I believe that the process to achieve this is describe there: https://django-tenants.readthedocs.io/en/latest/files.html#target-dir however, I cannot get it to work for me. Here is my project tree myapp ├── customers │ ├── __pycache__ │ ├── migrations │ │ └── __pycache__ │ └── templates │ ├── landpage │ │ ├── contactform │ │ │ └── img │ │ ├── css │ │ ├── fonts │ │ └── js │ └── registration ├── dashboard2 │ ├── __pycache__ │ ├── migrations │ │ └── __pycache__ │ ├── migrations2 │ │ └── __pycache__ │ ├── templates │ │ └── dashboard2 │ │ └── pdf │ └── tenants │ └── itoiz │ └── templates ├── inventory4 │ └── __pycache__ ├── locale │ └── fr │ └── LC_MESSAGES ├── logs ├── mediafiles │ └── tenants │ └── t5 │ └── api │ ├── historical │ └── preprocessing ├── static │ ├── admin │ │ ├── css │ │ │ └── vendor │ │ │ └── select2 │ │ ├── fonts │ │ ├── img │ │ │ └── gis │ │ └── js │ │ … -
Get all entries with price greater than given price in json filed
I have a model Van which van_slug field and a price field I am using MySQL. I have to save different price for all 12 months. I am using jsonfield. class Van(models.Model): slug = models.SlugField(max_length=200) price = JSONField(null=True) I am saving price like this and showing price of current month to visitor. {'January': 987.0, 'February': 567.0, 'March': 567.0, 'April': 456.0, 'May': 6.0, 'June': 654.0, 'July': 456.0, 'August': 456.0, 'September': 456.0, 'October': 546.0, 'November': 89.0, 'December': 456.0} Problem I have to add an filter for min and max price. I don't know how can I do this. I have tried this Van.objects.exclude(price__June__gte=340) but this is raising error Unsupported lookup 'June' for JSONField or join on the field not permitted. I searched the error and found this only work in postgres. I know this solution query = User.objects.filter(data__campaigns__contains=[{'key': 'value'}]) but i don't need exact matching.Is there any other method to filter vans by price? -
How to Get Items in a model connected to another model using a foreign key in detail view in django?
I am trying to create a cartoon streaming website in which when a user clicks on their cartoon of choice(Eg:Pokemon), they get to see the seasons as a list as well as the detail of the cartoons. from django.db import models # Create your models here. class Cartoon(models.Model): name = models.CharField(max_length=200) cover = models.ImageField() description = models.TextField() start_date = models.CharField(max_length=50) end_date = models.CharField(max_length=50) def __str__(self): return self.name class CartoonSeason(models.Model): cartoon = models.ForeignKey(Cartoon, null=True, on_delete=models.SET_NULL) number = models.IntegerField() season_cover = models.ImageField(blank=True, null=False) season_name = models.CharField(max_length=200, blank=True, null=True) season_description = models.TextField(blank=True, null=False) Here I have linked the Cartoon model with the CartoonSeason model using a Foreign Key so when a new season is to be added, it automatically gets linked with the corresponding Cartoon # Create your views here. from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView, DetailView from .models import CartoonSeason, Cartoon # Create your views here class CartoonListView(ListView): model = Cartoon template_name = "index.html" class CartoonSeasonView(DetailView): queryset = CartoonSeason.objects.filter() model = CartoonSeason template_name = "season.html" I am using a detail view to display the CartoonSeason model so that it displays the Cartoons details as well, but when I try to load the seasons, it only displays … -
ML and Django: using Conda and Pip depending on what I am doing... no?
So I am starting in Data Science and there are two things I am using quite a bit: Machine learning and Django. I have looked throughout the internet and the two worlds seems to be at different ends - ML going with Anaconda/miniconda and Django with PIP. To me, it makes sense, Anaconda has most of the packages needed for DS and feels a more solid option when using it for those purposes (i.e. data analysis, wrangling, ml modelling, etc). However, for Django, there seems to be everyone (by everyone I mean tutorials and articles on Django) uses PIP. And it makes sense, when deploying a quick app, all you want to do is to create a virtual env, install the needed packages, build the app, pip freeze it and upload to server. Boom. However, the more I look on the internet, everyone seems to be use either Anaconda/miniconda or PIP. Some stuff I read on Stackoverflow mentions using pip inside Anaconda/miniconda's environment... but for that I would have to create a PIP-virtual-environment inside Anaconda/miniconda's environment. As you can see, as a newbie, I feel slightly confused with this. As anyone got experience this? What did you do? -
How to Import User and UserProfile data from UserProfile Model Admin?
I have this custom User model- class User(AbstractUser): email = models.EmailField(unique=True) picture = models.ImageField(upload_to='profile_picture', null=True, blank=True) updated_on = models.DateTimeField(auto_now=True) date_activated = models.DateTimeField(null=True, blank=True) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Meta: verbose_name = 'User' and this UserProfile model- class UserProfile(models.Model): user = models.OneToOneField(User, related_name='userprofile', on_delete=models.PROTECT, primary_key=True) contact = models.CharField(max_length=20, blank=True, default='') about_me = models.TextField(null=True, blank=True) latitude = models.FloatField(validators=[MinValueValidator(-90), MaxValueValidator(90)], null=True, blank=True) longitude = models.FloatField(validators=[MinValueValidator(-180), MaxValueValidator(180)], null=True, blank=True ) age = models.IntegerField(validators=[MinValueValidator(18), MaxValueValidator(100)], null=True, blank=True ) dob = models.DateField(null=True, blank=True,) source_of_registration = models.ForeignKey('core.SourceOfRegistration', on_delete=models.PROTECT, null=True,blank=True ) interests = models.ManyToManyField('core.Interest') languages = models.ManyToManyField('core.SpokenLanguage') gender = models.ForeignKey('core.Gender', on_delete=models.PROTECT, null=True, blank=True ) country = models.ForeignKey( 'core.Country', on_delete=models.PROTECT, null=True, blank=True ) state = models.ForeignKey('core.State', on_delete=models.PROTECT, null=True, blank=True) city = models.ForeignKey('core.City', on_delete=models.PROTECT, null=True, blank=True) zip_code = models.CharField(max_length=12, null=True, blank=True) is_profile_completed = models.BooleanField(default=False) profile_completed_on = models.DateTimeField(null=True, blank=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'User Profile' def __str__(self): return self.user.email def clean(self): if self.dob: age_in_days = (datetime.date.today() - self.dob).days age_in_years = age_in_days / 365 if age_in_years < 18: raise ValidationError(gettext_lazy('Age should be more or equal to 18.')) else: self.age = age_in_years This is the UserProfileResource- class UserProfileResource(resources.ModelResource): class Meta: model = UserProfile import_id_fields = … -
How to create a tree view of a directory in a django website
I need to create a tree view of a directory in my Django website The folder structure is like Root Folder Folder 1 File(s) Folders and Files Folder 2 File(s) Folder(s) File(s) or in a similar fashion -
Getting error while defining request in signal receiver
I want a mail to be sent for activating the account.I am using signal concept in django.Created a UserConfirmation Model where I am storing user_id and token.While I am clicking on the user_registration button after populating all the fields I am getting this error TypeError: send_email() missing 1 required positional argument: 'request' If I am assigning a parameter in receiver decorator NameError: name 'request' is not defined @receiver(post_save,request,sender = UserConfirmation) My user table and user_confirmation table is getting populated with the data. @receiver(post_save,sender = UserConfirmation) def send_email(sender,request,instance,created,**kwargs): if created: current_site = get_current_site(request) send_mail( "Account Activation Link", f"Hi Plese click on below given link to activate your account.\n{instance.selector}\{instance.token}", "cj@teckzilla.net", [instance.email], Thanks In Advance -
Django ORM implementation of StdDev on DateTimeField
I'm trying to get the standard deviation of a time in Django. I keep running into django.db.utils.ProgrammingError. I tried it with various data types (DateTimeField, DurationField, IntegerField), also tried casting it first. Event.objects.annotate(StdDev(F('end_ts') - F('start_ts'), output_field=models.DurationField())) Event.objects.annotate(x=Cast(F('end_ts') - F('start_ts'), models.DurationField())).annote(y=StdDev(x, output_field=models.DuratinField)) Given the error, I think it's not yet implemented: django.db.utils.ProgrammingError: function stddev_pop(interval) does not exist LINE 1: SELECT "app_event"."task_id", STDDEV_POP((("app_event"."end_... However, it would save me quite some performance to do it with the ORM compared to manually in Python. If anybody knows a work-around with the ORM, that would be much appreciated! -
Django form data modification with jquery
I am trying to adapt an already working application in Django, but I am quite new to this environment and I am not the original developer so I may have some conceptual errors, but I have not found a way to solve the problem. I have a django model which references a client list: clients = models.ManyToManyField( Client, blank=True, verbose_name=_('Clients'), related_name='clients', ) It is being feed in the admin using the autocomplete feature, obtaining the client data from the other table. This is working perfectly. I want to preload some data based on a select dropbox I have included in the form. On change of the select box, I want to include some values on this manytomany field. I am using jquery to add values to the field, and as far as I have found, I need to add the client references in two places: Add the name and the Id in a Select <select name="clients" id="id_clients" class="admin-autocomplete select2-hidden-accessible" data-ajax--cache="true" data-ajax--type="GET" data-ajax--url="/en/admin/client/client/autocomplete/" data-theme="admin-autocomplete" data-allow-clear="true" data-placeholder="" multiple="" tabindex="-1" aria-hidden="true"> <option value="2355">Client1</option> </select> Add the name in the unordered list (ul) as a new li. <ul class="select2-selection__rendered"> <span class="select2-selection__clear">×</span> <li class="select2-selection__choice" title="Client1"> <span class="select2-selection__choice__remove" role="presentation">×</span>Client1</li> <li class="select2-search select2-search--inline"> <input class="select2-search__field" type="search" tabindex="0" … -
How to signal "ready to accept requests" to Gunicorn in Django application?
Some Context / my problem I develop a Django-appliaction, that is "served" using Gunicorn (configured to use 5 workers) I face the problem that when a new worker is booted after another worker is restarted (I've set max-requests to 1000 and max-requests-jitter to 50), then that new worker's handling of its first request is really slow (approximately ~5 seconds compared to a usual ~0.01 seconds). The extended time for handling the workers' first request coincide well with the time for booting the Django-application. Question Is there a way to signal to Gunicorn that the application is now fully initialized and ready to accept requests? Or alternatively: Can I supply Gunicorn an "I'm ready" HTTP-endpoint on my Django application? Thanks in advance :) Any input or feedback is appreciated -
Wagtail migration error with custom user models
I have a fresh install of wagtail. To make a user profile page, I want to extend the user data. I added an app with manage.py startapp and followed the official documentation: https://docs.wagtail.io/en/stable/advanced_topics/customisation/custom_user_models.html I added app profiel, and my model looks like this: from django.db import models from django.contrib.auth.models import AbstractUser class Profiel(AbstractUser): bedrijfsnaam = models.CharField(max_length=300,blank=True) omschrijving = models.TextField(max_length=500,blank=True) My settings like this: AUTH_USER_MODEL = 'profiel.Profiel' The error I get when I migrate is this: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency profiel.0001_initial on database 'default'. I found a topic online, advising to temporarely comment out django.contrib.admin in settings.py, but this leads to other errors. -
Django not let me create project in vs code
When I try to create a project in vs code for Django it not let me in I got exception object not find Django-admin not recognised as the name of the cmdlet, function I hAve 3.9.1 and django -
Django form not submitting to database
Hi guys i have checkout page that has some fields and two additional one for stripe authentication. When im submiting my form it's not getting added to database but stripe registers payment. Do i need to remove those two fields in order to use form(request.POST) my models class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) recipient = models.TextField(max_length=50, null=True) city = models.TextField(max_length=50, null=True) country = models.TextField(max_length=50, null=True) zip_code = models.TextField(max_length=15, null=True) phone = models.TextField(max_length=10, null=True) email = models.EmailField(max_length=30, null=True) adress = models.TextField(max_length=100, null=True) transaction_id= models.TextField(max_length=100,null=True) invoice = models.BooleanField(default=False, blank=True, null=True) invoiceRecipient = models.TextField(max_length=50, null=True, blank=True) invoiceAdress = models.TextField(max_length=50, null=True, blank=True) invoiceZip = models.TextField(max_length=15, null=True, blank=True) invoiceCity = models.TextField(max_length=50, null=True, blank=True) invoiceNip = models.TextField(max_length=15, null=True, blank=True) processed = models.BooleanField(default=False, blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.adress) forms.py class CustomerShipp(ModelForm): invoice = forms.BooleanField(widget=forms.CheckboxInput(attrs={'class':'checkboxInvoice',}),required=False) class Meta: model = ShippingAddress fields = [ 'city', 'country','zip_code','adress', 'phone','email','recipient','invoice','invoiceRecipient', 'invoiceAdress','invoiceZip','invoiceCity','invoiceNip','transaction_id','customer','order'] exclude =['processed', 'date_added'] widgets ={ 'city' :forms.TextInput(attrs={'class':'shippForm'}), 'country' :forms.TextInput(attrs={'class':'shippForm'}), 'zip_code' :forms.TextInput(attrs={'class':'shippForm'}), 'adress' :forms.TextInput(attrs={'class':'shippForm'}), 'email' :forms.TextInput(attrs={'class':'shippForm'}), 'recipient' :forms.TextInput(attrs={'class':'shippForm'}), 'phone' :forms.TextInput(attrs={'class':'shippForm'}), 'invoiceRecipient':forms.TextInput(attrs={'class':'shippForm'}), 'invoiceAdress' :forms.TextInput(attrs={'class':'shippForm'}), 'invoiceZip' :forms.TextInput(attrs={'class':'shippForm'}), 'invoiceCity' :forms.TextInput(attrs={'class':'shippForm'}), 'invoiceNip' :forms.TextInput(attrs={'class':'shippForm'}), 'transaction_id' :forms.TextInput(attrs={'type':'hidden'}), 'customer' :forms.TextInput(attrs={'type':'hidden'}), 'order' :forms.TextInput(attrs={'type':'hidden'}), } my views order, created = Order.objects.get_or_create(customer=customer, complete=False) order.complete = True order.transaction_id = transaction_id order.save() … -
Fielderror when deleting question in django
I just recently removed my db (sqlite) and migrate everything, so I dont have any data in my tables. I create a superuser and tried to make a question in admin panel, it was OK, then I tried to delete that question and it was Not OK! django gave me this error FieldError at /admin/question/question/1/delete/ Cannot resolve keyword 'object_p' into field. Choices are: content_object, content_type, content_type_id, hit, hit_count_generic_relation, hits, id, modified, object_pk I'm new to the django and I cant understand what is the problem here! because before it was just fine. this is the view for delete class QuestionDeletView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Question template_name = "question/question_confirm_delete.html" success_url = "/" def test_func(self): question = self.get_object() if self.request.user == question.author: return True return False I have the right template (contain the form to submit deletion) any insight would be helpful. -
after registering user unable to login with right credentials
please help i am new to django any help would be appreciated ! i was working on this project trying to create user registration it was working fine but i dont know what happend when ever i register a user after registration when i try to login in with same credential it gives error invalid username or password although i check the username in database it was same but i am not sure about password since i cant really check the password Views.py from django.shortcuts import render from django.contrib.auth import authenticate, login, logout,update_session_auth_hash from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render,redirect from django.urls import reverse from .models import User from .forms import UserChangeForm,EditProfileform from django.contrib.auth.forms import UserChangeForm,PasswordChangeForm # Create your views here. def index(request): return render(request,"store/index.html") def login_view(request): if request.method == "POST": # Attempt to sign user in username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) # Check if authentication successful if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "store/login.html", { "message": "Invalid username and/or password." }) else: return render(request, "store/login.html") def logout_view(request): logout(request) return HttpResponseRedirect(reverse("index")) def register(request): if request.method == "POST": first_name=request.POST["first_name"] last_name = request.POST["last_name"] username = … -
virtualenv gives Error While Create new porject django [closed]
While trying to Create a new virtualenvfor my project:enter image description here it gives this error , How Can I Solve it ? -
How do I render a template in Django in the while my application is written in Flask?
I am a Django newbie here. My application was developed in Flask and now the application is being migrated to Django. I have read about rendering in django through its official website. However I am still not sure how to get it done. To better understand the issue I would like to show some code. flask_leads_bp.py @leads_bp.route('/leads/<int:page>', methods=['GET', 'POST']) def leads(page): global application_inst #rest of code return render_template('leads.html', application=application_inst, Industry_sele=industry_sele, type_sele=type_sele, country_sele=country_sele, number_comp=number_comp, size_sele=size_sele, user_role=session['role'], companies_list=companies_flask_list, industry_list=industry_list, users=all_user, filters=filters) How do I write it in Django? Sincere apologies for asking a trivial question,I am just a beginner in Django. Please help,Thanks. -
Failing to submit to a link page
When i click on the submit button i am getting the 404 error, i want to submit to the "new_search" {% extends 'base.html' %} {% block content %} <form action="{ % url 'new_search' %}" method="post"> {% csrf_token %} <input type="text" name="search" value="search" placeholder="search"> <input type="submit" name="submit"> </form> {% endblock content %} page -
How to get the value selected in a select component to use it in another component using Vue
I Have the following template <div class="container"> <div class="row"> <div class="col-lg-5 filter big"> <select v-model="stc" @change="getData" name="new" title="country"> <option value="">all</option> <option v-for="country in data.countries_list" v-bind:key="country.id" v-bind:value="country.id"> {% verbatim %} {{ country.name }} {% endverbatim %} </option> </select> </div> <div class="col-lg-7"> travels <p> {% verbatim %} {{ data.travels }} {% endverbatim %} </p> </div> </div> </div> The vue part is new Vue({ el: `#${STSAppID}`, data: { data: {}, }, created() { this.getData() }, methods: { refreshSelects() { refreshSelects() }, getData() { const that = this const url = apiBase + "std/" axios.get(url).then(function(response) { that.data = response.data that.refreshSelects() }) }, }, computed: {}, }) What I want to do is check the selected value {{ country.name }} inside the other div <div class="col-lg-7"> so being able to write something like <div class="col-lg-7"> travels ***if country.name which is the selected option equals something then display the below p element*** <p> {% verbatim %} {{ data.travels }} {% endverbatim %} </p> </div> can I do this? -
Django admin data not saving
I try to modify data in the admin panel and save it. After saving changes I got success message but the data doesn't change. I can't figure out how to solve it. -
How can you reset data printed after each search?
I'm building a scrapper that prints out the results on the same page, but whenever I try to search for new results, the old ones still appear. Meaning that the HTML doesn't get deleted at all after each search. I guess the command should be in Javascript but don't know what should I put so that it resets the data. The code for printing emails: {% for email in email_list %} <p id="results"> {{ email }} </p> {% endfor %} -
How to place django form fields side by side
I have a UserCreationForm which I want the first_name and last_name to be side by side, When I try the whole fields are side to side, I want the other fields to have their own line. form.html: {% csrf_token %} {% for field in form %} <p> {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {{ field.label_tag }} {{ field }} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} forms.py: class AccountCreationForm(UserCreationForm): class Meta: model = Account fields = ('first_name','last_name', 'email') -
Exceeded soft memory limit on Google App Engine and Django
I'm currently involved in a Django project running on Google App Engine. We have run into a problem where we get critical errors in GAE with reference to Exceeded soft memory limit. The underlying URL:s that are causing it are not any heavy calls. I.E. we are talking about very simple get calls in many cases. So it seems that the underlying reason is some kind of memory leak. We are currently running GAE with F4 instances and the Django version is 2.2.17. Can anybody help? Regards, Sven