Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Auto genrate a value for a model Field form another Django app model field
//App ITEMS APP(1) class ItemsDetail(models.Model): name = models.CharField(max_length=100,unique=True) sellPrice = models.FloatField() costPrice = models.FloatField() quantity = models.IntegerField() //App ORDERS (APP 2) class Order(models.Model): name = models.CharField(max_length=100) item = models.ForeignKey( ItemsDetail, on_delete=models.CASCADE, to_field='name', blank=True, ) price = models.FloatField() Now when user selects Order.item form a drop down list in admin interface, I want Order.price to have a value of ItemsDetail.sellPrice admin interface of Orders. Want to generate value for price according to item selected -
ImportError: cannot import name 'password_reset'
I am trying to do a password reset in django (2.1.1) but i keep getting the following error when i import password reset: ImportError: cannot import name 'password_reset' Thsis is my import: from django.contrib.auth import ( authenticate, get_user_model, login, logout, password_reset, password_reset_done ) -
Django Tastypie - Resource on Model Subclasses
I have the following structure in my django models (django version 1.7) models.py class Contact(models.Model): email = models.CharField(verbose_name='Email', max_len=50) class Person(Contact): first_name = models.CharField(verbose_name='First Name', max_len=50) last_name = models.CharField(verbose_name='Last Name', max_len=50) class Company(Contact): company_name = models.CharField(verbose_name='Company Name', max_len=50) department = models.CharField(verbose_name='Department Name', max_len=50) class Service(models.Model): service_name = models.CharField(verbose_name='Service Name', max_len=50) contact = models.ManyToManyField(Contact, verbose_name='Contact') api/resources.py class PersonResource(ModelResource): class Meta: queryset=Person.objects.all() class CompanyResource(ModelResource): class Meta: queryset=Company.objects.all() class ContactResource(ModelResource): class Meta: queryset=Contact.objects.all() class ServiceResource(ModelResource): class Meta: queryset=Service.objects.all() # fields contact = fields.ToManyField(ContactResource, attribute='contact', full=True) Based on the above structure, I need to fully serialize a Service, where the contact field resolves to the correct resource based on the subclass of the contact. I tried to do it in the dehydrate method, but it did not work. Is there any other way to achieve this, preferably, without using additional packages? Output Example { 'service_name': 'Helpdesk', 'contact': [ { 'first_name': 'John', 'last_name': 'Doe', 'email': 'jd@company.com' }, { 'company_name': 'C.O.M.P.' 'department': 'technical', 'email': 'tech@comp.com' } ] } Thank you -
set_language not changing language in certain cases (django)
I have the following menu to change languages in my site: <div class="btn-group navbar-right language menu"> <button class="btn btn-secondary btn-sm dropdown-toggle language-btn" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {% get_language_info for LANGUAGE_CODE as lang %} {{ lang.name_local }} ({{ lang.code }}) </button> <div class="dropdown-menu" aria-labelledby="dropdownMenu2"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <ul class="language-item"> <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ request.get_full_path }}" /> <input name="language" type="hidden" value="{{ language.code }}" /> <input type="submit" value="{{ language.name_local }} ({{ language.code }})" /> <span>{% if language.code == LANGUAGE_CODE %}✓{% endif %}</span> </form> </ul> {% endfor %} </div> </div> Being shown like This works the same than the form suggested by Django docs but avoiding the "Go" button to switch languages. It usually switches languages properly, except in certain cases, as I found out after a user reported the problem. If the user gets to my site via www.mydomain.com, it will be redirected to www.mydomain.com/en/ (or /es/ or /de/) and as far as I know, changing languages works as expected. However, if the user gets to my site via www.mydomain.com/es/, then when trying to … -
Long polling in Django - can't get page to update
I'm new to Django so apologies if this is a really stupid question but I'm trying to get a table to reload database values and when I open the page in a browser it loads ok initially but when it tries to reload nothing appears to happen. When I look in the network section of inspect element I can see repeated 404 page not found errors. I've been searching stack exchange etc. for a few days and I've tried various types of quotes etc. round the url tag but no joy. I'd really appreciate any help anyone can give me on this. I'm using python 3 and django2. Project level urls.py project level urls App Level urls.py App level urls App views App views HTML html Thanks in advance -
Django Pillow, save image as jpeg does not seem to work
Goodmorning, I'm using Pillow to resize and save an image within a Django model called Post. The image is retrieved from the imagefield, get's a check to see if it is RGB or not, if not the image is converted to RGB. Finally, I'm creating a thumbnail from the original image and try to save this in the MEDIA_ROOT. Even though the image get's uploaded, it doesn't seem to convert the image to jpeg. I followed the tutorial here Django 2+ edit images with Pillow and I'm trying to fit it to my needs. What am I missing here? models.py import os from django.core.validators import RegexValidator from django.db import models from django.utils import timezone from PIL import Image from django.conf import settings from django.db.models.signals import post_save class Post(models.Model): # Custom validators title_validator_specialchar = RegexValidator(regex=r'^[\s*\d*a-zA-Z]{5,60}$', message="The title can't contain any special characters") category = models.ForeignKey('Category',default=1, on_delete=models.SET_NULL, null=True) type = models.CharField(max_length=20) title = models.CharField(max_length=200, validators=[title_validator_specialchar]) content = models.TextField(max_length=2000) image = models.ImageField(upload_to='%Y/%m/%d/', blank=True) created_at = models.DateTimeField(editable=False) updated_at = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): #On save, update timestamp date created if not self.id: self.created_at = timezone.now() self.updated_at = timezone.now() return super(Post, self).save(*args, **kwargs) def __str__(self): return self.title def resize_image(instance, **kwargs): if instance.image: # we … -
Attempting websocket communication with multiple browsers using Channels (Django) cannot be connected (message cannot be received)
Using the Django (Python) library channels, We have created a web service with a chat function. Among them, using the function of consumer, We have created a room to chat and a room list acquisition process. When doing the acquisition of the room list (websocket communication) on the front end side, we can connect on one browser window, but we cannot get the room list with start up another browser or another account for chrome When trying to acquire the room list on the browser used, the connection of websocket (or receive after connection) is not processed properly. I would like to acquire the room list from another browser as well, Please teach the solution method. consumer.py class RoomListConsumer(AsyncWebsocketConsumer): groups = ['broadcast'] async def connect(self): self.scope["session"].save() self.room = [] self.room_group_name = "room_list" + self.scope['url_route']['kwargs']['id'] await self.channel_layer.group_add( 'room_list', self.channel_name ) await self.accept() async def disconnect(self, close_code): self.scope["session"].save() await self.channel_layer.group_discard( 'room_list', self.channel_name ) await self.close() async def receive(self, text_data): self.scope["session"].save() await self.setRoomList() await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'list': self.room } ) async def chat_message(self, event): await self.send(text_data=json.dumps({ 'type': 'chat_message', 'list': self.room })) @database_sync_to_async def setRoomList(self): # Set Room List routing.py websocket_urlpatterns = [ url(r'^chat/list/(?P<id>[^/]+)/$', RoomListConsumer), url(r'^chat/(?P<id>[^/]+)/(?P<room_name>[^/]+)/$', ChatConsumer) ] application = ProtocolTypeRouter({ … -
Django passing parameters to views and templates
I got a navigation tree that tells me where i am on my website to build that navigation tree i always need to pass all variables from template to the view as <input type="hidden">. Then i need to pass it from the view to the next template and it goes on and on feels like a bad solution to pass the variables from every template to every view. so my question is if there is a better solution to my problem here is a screen of the navigation tree. template: <form action="{% url 'aktentabelle' %}" method="post" style="display:inline-block"> {% csrf_token %} <input type="hidden" name="mitglied" value="{{Container.containernr}}" /> <input type="hidden" name="contpk" value="{{Container.pk}}" /> <input type="hidden" name="projectnr" value="{{projectnr}}" /> <input type="hidden" name="status" value="{{Container.status}}" /> <input type="hidden" name="chargepk" value="{{chargepk}}" /> <input type="hidden" name="chargenr" value="{{chargenr}}" /> <input class="btn btn-primary" type="submit" value="anzeigen" /> </form> so in my templates i always need to pass alot of variables as hidden and in my view i need to convert them back to read them: views.py: def aktentabelle(request): assert isinstance(request, HttpRequest) container = request.POST['mitglied'] z = AkteForm projectnr = request.POST['projectnr'] chargepk = request.POST['chargepk'] chargenr = request.POST['chargenr'] contpk = request.POST['contpk'] closecontainerform = CloseContainerForm akte_list = Akte.objects.filter(container__containernr=container) Anzahl_Akten =Akte.objects.filter(container__containernr=container).count status = request.POST['status'] return … -
Django model reference and manipulation
I have the following models in Django that have a structure as follows: class Office_Accounts(models.Model): accountid = models.EmailField(max_length=200, unique=True) validtill = models.DateField(default=datetime.now) limit = models.CharField(max_length=2) class Device(models.Model): device_type = models.ForeignKey(DeviceType,to_field='device_type') serial_number = models.CharField(max_length=200,unique=True) in_use_by = models.ForeignKey(User,to_field='username') brand = models.CharField(max_length=200,default="-", null=False) model = models.CharField(max_length=200,default="-", null=False) type_number = models.CharField(max_length=200,blank=True,null=True, default = None) mac_address = models.CharField(max_length=200,blank=True,null=True, default = None) invoice = models.FileField(upload_to='Device_Invoice', null=True, blank = True) msofficeaccount = models.ForeignKey(Office_Accounts, to_field="accountid") class Meta: verbose_name_plural = "Devices" def full_name(self): return self.device_type + self.serial_number + self.brand I will display both of the models in admin.py. Now, I want to display the count of each accountid present in the field "msofficeaccount" (present in Device Models) in my admin page of Office_Accounts model. For an example if xyz@abc.com appears in 10 rows of msofficeaccount field then, the count should be displayed as 10 in Office_Accounts admin page. Can anyone please guide me how should I approach this problem to solve it? -
Django channels vs Firebase cloud messaging for notifications?
I have 2 apps where 1 side is for scanning a QR and the other generates the QR code and when there is a successful QR code scan it a notification appears on both devices letting both users that the interaction was successful. I was debating implementing this feature using either Firebase's cloud messaging or Django channels(because the backend is done in Django). Which is better for scalability and more robust/less error prone? -
Django 2.1 creates autotable
im pretty new at django 2.1 framework. and i am a week trying to setup the tables for my app. Settings are fine i listed my app in INSTALLED_APPS, but when i try to run manage.py migrate code it gaves me one auto_tabble instead of the ones that was written on model file. Those are my models. from django.db import models class Nome (models.Model): titulo = models.CharField(max_length=100), objetivo = models.CharField(max_length=100), class Sobrenome (models.Model): lets = models.ForeignKey(Nome, on_delete=models.CASCADE), make = models.CharField(max_length=100), Thats what migrate code gave to me: from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Dreams', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.CreateModel( name='Wich', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), ] please help me!!. Thanks for your time -
How to make Min/MaxValidator work with Django's DecimalField?
A strange failure seems to occur in Django 2.1.2 (Python 3.7.0): from django.db.models import DecimalField from django.core.validators import MaxValueValidator, MinValueValidator f = DecimalField(max_digits=4, decimal_places=2, validators=[MinValueValidator(10), MaxValueValidator(20)]) This is the expected behavior: >>> f.clean(15, model_instance=None) Decimal('15') >>> f.clean('15', model_instance=None) Decimal('15') But this doesn't work: >>> f.clean(5, model_instance=None) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/.../anaconda3/envs/django/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 632, in clean self.run_validators(value) File "/Users/.../anaconda3/envs/django/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 591, in run_validators raise exceptions.ValidationError(errors) django.core.exceptions.ValidationError: <exception str() failed> Same error for: >>> f.clean('5', model_instance=None) >>> f.clean(25, model_instance=None) What am I doing wrong? NB: I know how to validate this field manually in the ModelForm, but I would prefer to avoid the workaround. I have checked some related answers with no success: DecimalField Validation in Django MinValueValidator not working on DecimalField in Django Django strange DecimalField validation -
AWS InvalidParameterValueError - Environment named ... is in an invalid state for this operation. Must be pending deployment
I did django deployment using AWS Elastic Beanstalk with Loadbalancer Server everything working fine initially I am getting this error when I am trying to deploy my django app on EC2 using eb deploy ERROR: InvalidParameterValueError - Environment named ... is in an invalid state for this operation. Must be pending deployment. I am not sure about this please help me anyone. Thanks in advance ... -
Django: Can I perform two pre-save signal for same operation?
Can I peform two pre-save signal in django for same operation just the sender will be diffrent in both cases... This is my models: class ledger1(models.Model): Creation_Date = models.DateField() name = models.CharField(max_length=32) group1_Name = models.ForeignKey(group1,on_delete=models.CASCADE,blank=True,null=True) Opening_Balance = models.DecimalField(max_digits=19,decimal_places=2,blank=True) Closing_balance = models.DecimalField(max_digits=10,decimal_places=2,blank=True,null=True) class journal(models.Model): Date = models.DateField() By = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') To = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2) Credit = models.DecimalField(max_digits=10,decimal_places=2) And this I have done previously: @receiver(pre_save, sender=ledger1) def update_user_closing_balance(sender,instance,*args,**kwargs): debit = instance.Debitledgers.aggregate(debit=Sum('Debit'))['debit'] credit = instance.Creditledgers.aggregate(credit=Sum('Credit'))['credit'] instance.Closing_balance = instance.Opening_Balance + debit - credit I want to do a similar pre-save signal but the sender will be journal...And Can I have two signal for same functionality in django? I mean to say when the ledger is updated the closing balance will be updated automatically that I have done already... But I also want to do something like when journal is updated then also the closing balance will be updated... Do anyone know this? Thank you -
Django user get logout if more than one user login
If i login with user1 & in another system login with user2 then user1 automatically get logout. the reason is django_session entry get deleted from database of first user i.e. user1. I am using Django 2.0.5. -
How to integrate Electron JS and Django Rest Framework?
I want to make a simple desktop Login System. I have no idea how to integrate Electron with Django. Any leads will be helpful. -
Django - force default language for sessions, different from MODELTRANSLATION_DEFAULT_LANGUAGE
I use Django with Mezzanine. I set languages like that: LANGUAGE_CODE = "en" MODELTRANSLATION_DEFAULT_LANGUAGE = 'cs' LANGUAGES = ( ('cs', _('Čeština')), ('en', _('Angličtina')), ) I do NOT use language in URLs. The problem is, that default language for new session is selected according browser preferences, however it should be EN allways. How to achieve that? I can imagine that it is possible to replace https://docs.djangoproject.com/en/2.1/_modules/django/middleware/locale/ with my custom middleware. I guess I should change the function: def process_request(self, request): urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF) i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf) language = translation.get_language_from_request(request, check_path=i18n_patterns_used) language_from_path = translation.get_language_from_path(request.path_info) if not language_from_path and i18n_patterns_used and not prefixed_default_language: language = settings.LANGUAGE_CODE translation.activate(language) request.LANGUAGE_CODE = translation.get_language() Is there a simpler option? What I should change in the mentioned function to achieve desired behavior? -
Is Ubuntu Crontabe Have Memory Limit?
I tried to use crontab to handle my django commands. ../virtualenv/env/bin/python manage.py my_commands But there are usually show django.db.utils.InterfaceError: connection already closed Error!! SSL SYSCALL error: EOF detected When I use "Screen" to open a terminal to execute that script, The commands will be fine and also done the job. That's what I am doubting crontab have memory limit. -
How to change the way username validates in Django admin interface change form?
I cant override or edit the way the username validates in de admin interface change form. I need my users to be able to have usernames with spaces and special characters. I managed to edit the way the sign up form validates the username so on the client side the problem is solved. The thing is that when I try to edit a user in the admin interface, I get de following error: Enter a valid username. This value may contain only letters, numbers, and @/./+/-/_ characters. I cant find a way around this! Thanks! -
Set ManyToMany field in model save method
I have a problem, I try to save the model and only adds to 'members' the users that belong to the company set in the field 'company'. This is my code: class GroupFolderAccess(BaseModel): name = models.CharField(max_length=128) members = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='belongs') company = models.ForeignKey('Company', on_delete=models.CASCADE, related_name='folders') folder = models.ForeignKey('recourse.Folder', null=True, blank=True, on_delete=models.CASCADE, related_name='get_group') def save(self, *args, **kwargs): for member in self.members.all(): if self.company != member.company: print(member) self.members.remove(member) return super(GroupFolderAccess, self).save(*args, **kwargs) When I save, it displays users correctly, but does not remove them from the relationship. -
Passing of dates from jquery to html
I created a button linked with a jquery so that when I click on the edit button in my form, the data from the entry will be populated into the form as well. The rest of the values do get populated into the form via jquery, however, my problem is with the dates value. Somehow, the dates are not being rendered into the form when passed back from jquery. html ... <button type="button" class="edit-current-policy-term float-right" data-toggle="modal" data-target="#edit-term-policy-modal" data-term="{{ policy_period.term }}" data-start_term="{{ policy_period.start_term }}" data-end_term="{{ policy_period.end_term }}" data-pk="{{ policy_period.pk }}"> <i class="fas fa-edit"></i> </button> jquery $(document).ready(function () { $(document).on('show.bs.modal', '#edit-term-policy-modal', function (event) { const button = $(event.relatedTarget); let term = button.data('term'); let start_term = button.data('start_term'); let end_term = button.data('end_term'); const pk = button.data('pk'); const modal = $(this); modal.find('.modal-body #id_term_number').val(term); modal.find('.modal-body #id_start_term').val(start_term); modal.find('.modal-body #id_end_term').val(end_term); }); }); forms class NewTermPolicyPeriodForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(NewTermPolicyPeriodForm, self).__init__(*args, **kwargs) self.fields['term'].widget = forms.TextInput( attrs={'class': 'form-control', 'id': 'id_term_number', 'name': 'term_number', 'type': 'number', 'placeholder': 'Term number'}) self.fields['term'].required = True self.fields['start_term'].widget = forms.DateInput( attrs={'class': 'form-control', 'id': 'id_start_term', 'name': 'start_term', 'type': 'date', 'placeholder': 'Term start date'}) self.fields['start_term'].required = True self.fields['end_term'].widget = forms.DateInput( attrs={'class': 'form-control', 'id': 'id_end_term', 'name': 'end_term', 'type': 'date', 'placeholder': 'Term end date'}) self.fields['end_term'].required = True self.fields['term_end'].widget = forms.CheckboxInput( … -
I want to get value is selected in ChoiceField
I wrote forms.py like # -*- coding: utf-8 -*- from django import forms class InputForm(forms.Form): name = forms.CharField(max_length=100) select1 = forms.ChoiceField(widget=forms.RadioSelect,required=False) select2 = forms.ChoiceField(widget=forms.RadioSelect,required=False) in html <div> {{ f.select1 }} <label for="select1" dataGoTo="7">select1</label> {{ f.select2 }} <label for="select2">select2</label> </div> in views.py def get_data(request): if request.method == "POST": form = InputForm(data=request.POST) if form.is_valid(): name = form.cleaned_data['name'] I want to get value which select1 or select2 is selected. How should I write in views.py? -
Django Error: Model class app.models.Model doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I've been experiencing the above error in Django. Before you yell at me, I have extensively read through this post on the same error.. However, None of the solutions provided there have helped resolve this. Essentially, I'm trying to create an instance of each of my models so that I can populate my web-page. However, I can't even run my models.py without the above error, which looks like this: from django.db import models class HomePage(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Section(models.Model): name = models.CharField(max_length=200) home_page = models.ForeignKey('mainpage.HomePage', on_delete=models.CASCADE) def __str__(self): return self.name class NavBar(Section): logo = models.ImageField() class Entry(models.Model): primary = models.BooleanField() text = models.CharField(max_length=15) class Landing(Section): tagline = models.TextField() button_text = models.CharField(max_length=25) class About(Section): title = models.CharField(max_length=200) class Blurb(models.Model): "Blurb for an about section" title = models.CharField(max_length=200) body = models.TextField() section = models.ForeignKey('mainpage.About', on_delete=models.CASCADE) class Capabilities(Section): title = models.CharField(max_length=200) description = models.TextField() button_text = models.CharField(max_length=40) class Capability(models.Model): """Capability entry""" image = models.ImageField() description = models.TextField() section = models.ForeignKey('mainpage.Capabilities', on_delete=models.CASCADE) class Testimonials(Section): title = models.CharField(max_length=200) class Testimonial(models.Model): """Testimonial card""" name = models.CharField(max_length=200) role = models.CharField(max_length=200) description = models.TextField() class Contact(Section): logo = models.ImageField() description = models.TextField() address = models.ForeignKey('mainpage.Address', on_delete=models.CASCADE) info = models.ForeignKey('mainpage.ContactInfo', on_delete=models.CASCADE) class Address(models.Model): title … -
django rest muitiple profiles Serializer
In my project, I have two profiles which are student profile and company profile. These two profiles are hooked with user using one-to-one relationship and I use custom user which define a new field user_type to decide whether it is a student or company. Here is the code: class CustomUser(AbstractUser): USER_TYPE = ( (1, "student"), (2, "company") ) user_type = models.IntegerField(choices=USER_TYPE,default=1) class StudentProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE,related_name = 'student_profile') class CompanyProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, related_name = 'company_profile') But when I try to Serialize the user with HyperlinkedModelSerializer I find an issue that I can not decide which URL should the API pointed. For example: If user_type == student, then it should be student profile URL in the user, otherwise the company profile URL in the user.I try to implement the logic by this: class UserSerializer(serializers.HyperlinkedModelSerializer): profile_url = serializers.HyperlinkedIdentityField(view_name='studentprofile-detail') def student_or_company(self, data): user_type = data.get('user_type') if user_type == 1: profile_url = serializers.HyperlinkedIdentityField(view_name='studentprofile-detail') else: profile_url = serializers.HyperlinkedIdentityField(view_name='companyprofile-detail') return profile_url class Meta: model = get_user_model() depth = 1 fields = ('url', 'id', 'username', 'first_name', 'last_name', 'email','user_type', 'is_superuser', 'is_staff', 'profile_url') But it looks like the def method not work.. Is there someone who can help me to implement this … -
bootstrap4 CDN, submit button not working
when I am giving the link manually, it working but when I am using the submit button its not working in Django. Here is the code: <form method="get" action="/some/location/folder/" > <input type= "submit" class= "btn btn-info" style="float:right" value="New Folder" /> </form> what am i missing ?