Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid import errors in django within same app
I have a django app where I want MyModel instances to be saved using an Enum choice, which I process in the save() method, such as: # app/models.py from django.db import models from app.utils import translate_choice from enum import Enum class MyEnum(Enum): CHOICE_A = 'Choice A' CHOICE_B = 'Choice B' class MyModel(models.Model): ... choice = models.CharField( max_length=10, choices=[(tag.name, tag.value) for tag in MyEnum], ) ... def save(self, *args, **kwargs): self.choice = translate_choice(self.choice) super().save(*args, **kwargs) Whereas on the app/utils.py I have: from app.models import MyEnum def translate_choice(value): ... return MyEnum.CHOICE_A # For example I keep getting ImportError: cannot import name 'MyEnum' errors on the app/utils.py file when running the application. Is this due to a python circular import error, or am I missing something else? When moving the translate_choice() method to app/models.py it stops happening, but I would like to use this same method in other modules and it is kind of weird having a transforming feature within the models when used in another app. Thank you in advance -
Python Django - Pass initial value into bound form
I'm new to Python Django and I'm trying to set up a bound form with three fields where one field (which will be read only) takes an initial value and displays it on the form; the other two fields will be populated by the user when they completes the form. But when I try to submit the form, the form.is_valid returns false, and I'm not sure what I did wrong. Can anyone please help? Thanks Here's the code: views.py class AddKeyAccompView(TemplateView): template_name = 'AddKeyAccomp.html' def get(self, request, Program): username = request.user.username form = AddKeyAccompForm(request, Program=Program) return render(request, self.template_name, {'form': form ,'title':'Add New Key Accomplishment' ,'User': username }) def post(self, request, Program): username = request.user.username form = AddKeyAccompForm(request.POST, Program=Program) if form.is_valid(): Name = form.cleaned_data['Name'] Description = form.cleaned_data['Description'] form.save() form = AddKeyAccompForm(request, Program=Program) return HttpResponseRedirect(reverse('ModInit', args=[Program])) else: return HttpResponse('invalid form') args = {'form': form ,'title':'Add New Key Accomplishment' ,'User': username ,'Name': Name ,'Desc': Description ,'Program': Program } return render(request, self.template_name, args) forms.py class AddKeyAccompForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): self.program = kwargs.pop('Program') super(AddKeyAccompForm, self).__init__(*args, **kwargs) self.fields['Program'].initial = self.program class Meta: model = Key_Accomplishments fields = ('Name', 'Description', 'Program',) widgets = { 'Name': forms.TextInput(attrs={'required':True, 'class':'form-control'}) ,'Description': forms.Textarea(attrs={'required': True, 'class':'form-control'}) ,'Program': forms.TextInput(attrs={'readonly':'readonly', 'class':'form-control'}) } … -
Add Button To Add Student Django Admin
So below is my admin section, what im trying to do is create a button near my drop down list to add a student to a classroom.( Button in screenshot is where it should be placed) The dropdown list is populated from another table called students , however my field students in class will be a list of all the students in the class. Basically im making a roster. The goal is later when i query that classroom list i return all the students in that class. Right now the field students in class is just set to a charfield, not sure if that is correct. Appreciate the help. [ class TeacherClass(models.Model): teacher_class_id = models.CharField(primary_key = True , default = "", max_length = 50, unique = True) teacher_class_name = models.CharField(max_length = 50) teacher_id = models.ForeignKey(Teachers, on_delete = models.PROTECT, default = "") student_id = models.ForeignKey(Student, on_delete = models.PROTECT, default= "") students_in_class = models.CharField(max_length=500, default = "") class Meta: abstract = False verbose_name = "Teacher Class" def __str__(self): return self.teacher_class_name -
Django admin select all checkbox not working
I'm using Django 2.2.7 with python 3.8 in pipenv 2018.11.26. In my django admin i can't select all items checkbox (see pic below) in list of model objects and not see datepicker with actions "now" & "today". -
Confuse about django relationships
I'm developing a storage software and I got kind confuse with this relationship on Django. The project's model has two classes: Places: class Places(models.Model): tipo = models.CharField(max_length=15, null=True) cnpj = models.CharField(null=True, max_length=11) ie = models.CharField(null=True, max_length=13) cep = models.CharField(null=True, max_length=20) cidade = models.CharField(null=True, max_length=54) bairro = models.CharField(null=True, max_length=54) num = models.CharField(null=True, max_length=54) rua = models.CharField(null=True, max_length=254) maintelefone = models.CharField(null=True, max_length=10) sectelefone = models.CharField(null=True, max_length=10) contactperson = models.CharField(max_length=200, null=True) email = models.CharField(null=True, max_length=254) site = models.CharField(null=True, max_length=254) razaosocial = models.CharField(null=True, max_length=254) fantasia = models.CharField(null=True, max_length=254) created = models.DateTimeField(default=timezone.now, editable=False) last_updated = models.DateTimeField(default=timezone.now, editable=False) def __str__(self): return self.razaosocial And Movementacao: class Movimentacao(models.Model): date = models.DateField(default=timezone.now, null=True) produto = models.ForeignKey( 'Produto', on_delete=models.CASCADE, null=True) # Automatizar qtd = models.IntegerField(null=True, default=1) numero_serie = models.CharField(null=True, max_length=154) tipoMov = models.CharField(max_length=5, null=True) tipo = models.CharField(max_length=5, null=True) nf = models.CharField(null=True, max_length=154) date_nf = models.DateTimeField(default=timezone.now, null=True) origem = models.ForeignKey( 'Places', on_delete=models.CASCADE, related_name='origemovi', null=True) destino = models.ForeignKey( 'Places', on_delete=models.CASCADE, related_name='destinomovi', null=True) obs = models.CharField(max_length=254, null=True) created = models.DateTimeField(default=timezone.now, editable=False) def __str__(self): return self.tipoMov The logic is that a Place can have one or more Movimentacao, and Movimentacao can just have one Place ( Many-to-One, I supose) ,but I expect that the Place got the id of the Movimentacao too, not just … -
How to Apply Query Filtering for JSON list like structure in Django
Django has support for jsonfield using postgres. Below is the example for filtering results based on JSON key, value match. OBJ1 : m1 = Movies.objects.create(movie_name='inception',movies_json_data{"review": "Mind Blowing", "rating": 5} OBJ2 : m2 = Movies.objects.create(movie_name='joker',movies_json_data{"review": "horror", "rating": 4} >>> Movies.objects.filter(movies_json_data__rating=5) <QuerySet [<Movies: Inception>]> How do i perform filter query when data is in a list like JSON structure? movies_json_data=[{"review": "horror", "rating": 4},{"review":"horror-with-scify","rating":"4.5"}] -
Django signals.py not called
I know this has been asked several times. But going through everything I cannot see what I'm missing. What should happen: A django signal should be fired after some user logged in Setup settings.py from my_app.local_settings import * [...] PROJECT_NAME = 'my_app' if PROJECT_NAME not in INSTALLED_APPS: INSTALLED_APPS += (PROJECT_NAME,) my_app/__ init __.py import os default_app_config = "my_app.apps.AppConfig" my_app/apps.py from django.apps import AppConfig as BaseAppConfig class AppConfig(BaseAppConfig): name = "my_app" label = "my_app" def ready(self): super(AppConfig, self).ready() run_setup_hooks() import my_app.signals # here I register the signal my_app/signals.py from django.dispatch import receiver from django.contrib.auth.signals import user_logged_in @receiver(user_logged_in) def do_stuff(sender, user, request, **kwargs): with open('/tmp/log.txt', 'w+') as the_file: the_file.write('okay sir') What I've tested: from django.db.models.signals import * from django.contrib.auth.signals import user_logged_in for signal in [user_logged_in]: print signal.receivers [((4653976464, 140735896872616), <weakref at 0x1155bd310; to 'function' at 0x115660b90 (update_last_login)>), ((4688441544, 140735896872616), <weakref at 0x11777b998; to 'function' at 0x11773f0c8 (do_login)>)] It looks as the signals.py is not called at all. Strange as my setup with signals looked like this in other projects without problems. I think I'm missing something really obvious. Is there something I should take care of regarding app label / name in settings which could cause confusion? -
django-ckeditor upload fails in pythonanywhere with pillow backend(keyerror: "pillow")
I am using django-ckeditor in my django project. python 3.7 Django 2.2.6 django-ckeditor 5.8.0 Pillow 6.2.1 For ckeditor, I am using image2. Everything works in my local server. But when I deploy my project to pythonanywhere, I get following errors: in google developer tools-> network-> xhr Status Code: 500 Internal Server Error in error.log of pythonanywhere KeyError: 'pillow' If I comment out the following code in my settings.py, ckeditor works in pythonanywhere. CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_FORCE_JPEG_COMPRESSION = True Any idea why this is the case? Thanks! -
send X-Postmark-Server-Token in header postmark django
I'm facing Postmark API response 401 (Unauthorized): { "ErrorCode": 10, "Message": "The Server Token you provided in the X-Postmark-Server-Token request header was invalid. Please verify that you are using a valid token." } so how can I send token in header using anyemail esp_extra?, currently I'm doing something like this EMAIL_BACKEND = "anymail.backends.postmark.EmailBackend" ANYMAIL = { "POSTMARK_SERVER_TOKEN": "POSTMARK_TOKEN", "POSTMARK_SEND_DEFAULTS": { "X-Postmark-Server-Token": "TOKEN", "tags": ["app"] }, } but it's not working. -
Django on Synology NAS
Has anyone been successful with setting up a django site onto their synology NAS? I've recently installed python and django onto my nas, but because synology uses a default folder for populating websites it doesn't seem like the ideal setup to use django, I'm curious if anyone has found a way around it? -
I want to ask about error in code block in Django
This is code for a template which i am trying to inherit. This is not giving any error in programme but what these warning are trying to suggest -
What would be the best Django view to display Call Queue
Currently, I'm using a function-based view to display the person to call like an UpdateView, so the logged-in person can edit the data and save changes as well as having an option to set up a meeting with the client. Screenshot for show what I mean Screenshot of Page After the call has been made, the user changes the follow-up date and then when the page refreshes it no longer matches the query and it shows the next call. It's paginated by 1 so I can give a preview of the upcoming calls. Sorry for the long introduction but I just feel like it's a really janky way to get this functionality. Am I doing this in a good way or is there a better path forward that I might have missed? I spent a lot of time in the Django Documentation looking for alternative methods. The behaviour I'd like to get is for the user to just save the call note and then move forward to the next call, the way it's set up now, the Follow Up date has to be changed before the queue moves forward. View for Call Queue: def CallQueueView(request): FormSet = modelformset_factory(Client, form=ClientSheet, extra=0) … -
Show user posts in post list
The following method returns a queryset of posts of users that i follow. def get_queryset(self, *args, **kwargs): # returns the users that i follow following_users = self.request.user.profile.get_following() #gets posts of following users qs = Tweet.objects.filter(user__in=following_users).order_by("-timestamp") return qs I want to add my own posts too in this query set. How to add my own user in this queryset? Something like this: def get_queryset(self, *args, **kwargs): # returns the users that i follow following_users = self.request.user.profile.get_following() following_users.append(self.request.user) # This is not working #gets posts of following users qs = Tweet.objects.filter(user__in=following_users).order_by("-timestamp") return qs Something like this> How should i do that? Im begginer plz help. -
sending mail on post_save django
I want to send mail when I create entry in database, I'm using django post_save signal for that, but I'm failing in doing that, I'm not sure what I'm I missing here, is there a change that someone can help me understand what is happening. I'm using postmarker for the email configuration. model.py class Winner(BaseModel): name = models.CharField(max_length=225, blank=True, null=True) email = models.EmailField(unique=True, db_index=True) telephone = models.CharField(max_length=225, blank=True, null=True) postal_code = models.CharField(max_length=225, blank=True, null=True) reseller_code = models.CharField(max_length=225, blank=True, null=True) company_contact = models.CharField(max_length=225, blank=True, null=True) company_name = models.CharField(max_length=225, blank=True, null=True) company_telephone = models.CharField(max_length=225, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, db_index=True) EMAIL_FIELD = 'email' class Meta: verbose_name = 'winner' verbose_name_plural = 'winners' def get_email(self): """ Return the indentifying email for this Winner """ return getattr(self, self.EMAIL_FIELD) def __str__(self): return self.get_email() signal.py def send_winner_info(sender, instance, created, **kwargs): winner = instance if created: winner_dict = { "Name: ", winner.name, "Email: ", winner.email, "Telephone: ", winner.telephone, "Postal Code: ", winner.postal_code, "Reseller Contact: ", winner.reseller_contact, "Company Name: ", winner.company_name, "Company Telephone: ", winner.company_telephone, } message = render_to_string('mails/winner.html', winner_dict) subject = "Giveaway Winner Information" from_email = settings.DEFAULT_FROM_EMAIL recipients_list = settings.DEFAULT_RECIPIENT_LIST send_mail(subject, message, from_email, recipient_list=recipients_list) post_save.connect(send_winner_info, sender=Winner) -
Stripe ID saves to a new row in Django AbstractUser table
I was able to successfully complete a test subscription payment through Stripe. However, when I checked my Postgresql user database table, I found that during the checkout and Stripe customer creation process, the StripeID and Stripe_subscription_id were saved to a new user. The desired behavior is for these two pieces of data to be added to the current logged-in user's profile. I am using a custom AbstractUser model and suspect the issue lies there. I appreciate a point in the right direction to fixing this. My relevant code snippets are below: models.py # users/models.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass # add additional fields in here stripeid = models.CharField(max_length=255) stripe_subscription_id = models.CharField(max_length=255) forms.py # users/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('username', 'email') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = UserChangeForm.Meta.fields admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): model = CustomUser add_form = CustomUserCreationForm form = CustomUserChangeForm admin.site.register(CustomUser, CustomUserAdmin) views.py # pages/views.py import os from django.shortcuts import render, get_object_or_404, redirect … -
Are named URLs in Django really necessary?
The URL mappings I used in my Django applications are "named URLs" as follows (according to Django's documents). For example, in the project's urls.py: path('main/', include('main.urls', namespace='main')), and in the main app's urls.py: path('', views.main, name='main'), With the above namespace and name settings, the following formats may be used in views and templates, respectively: reverse('main:main') {% url 'main:main' %} One of the advantages of using named URLs is that we may easily change the URL mappings without affecting the codes in views or templates. I have developed dozens of real business Django projects. The above may sound reasonable, but I have never changed the URL settings in any of my projects. I wondered what kinds of projects will change the URL mappings from time to time so the named URLs are useful? -
Django automatic login after signup
I'm trying to get users automatically logged in after registration. However the user only seems to be logged in for the duration of rendering the next html page (user.is_authenticated returns True in my templates) and gets logged out immediatly after (request.user returns AnonymousUser in a method I call via AJAX on the next page - moving to another page also makes clear you are not logged in anymore since my templates render the login instead of the logout links again). If I try the commented code instead authenticate() always returns NONE. What am I doing wrong? def signup_view(request): if request.method == 'POST': form = UserSignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) send_confirmation_email(user, current_site.domain) # user_login = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1']) # login(request, user_login) login(request, user, backend='django.contrib.auth.backends.ModelBackend') args = {'user': user} return render(request, 'accounts/signup_success.html', args) else: form = UserSignUpForm() args = {'form': form, 'project_name': settings.PROJECT_NAME} return render(request, 'accounts/signup.html', args) -
AttributeError: 'SendGridAPIClient' object has no attribute 'send'
I am using sendgrid to send mail via django, however, it keeps saying AttributeError: 'SendGridAPIClient' object has no attribute 'send' Steps to Reproduce install sendgrid pip install sendgrid run script from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail sg = SendGridAPIClient("the_api_key") email_data = Mail( from_email="support@email.africa", to_email="example@email.com", subject="YOUR EVENT IS NOW LIVE ON SITE!", ) email_data.dynamic_template_data = json.dumps({ "username": "example username", "item_name": "example item name", "item_slug": "path to example item slug", "template_id": "transactional template id", "message_type": "EMAIL" }) response = sg.send(request_body=email_data.get()) error: Traceback (most recent call last): File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/viewsets.py", line 116, in view return self.dispatch(request, *args, **kwargs) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/mixins.py", line 84, in partial_update return self.update(request, *args, **kwargs) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/mixins.py", line 70, in update self.perform_update(serializer) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/mixins.py", line 80, in perform_update serializer.save() File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/serializers.py", line 209, in save self.instance = self.update(self.instance, validated_data) File "/Users/Retina15/project/store/serializers/event.py", line 358, … -
How can I access foreign keys in Django?
guys! I have the following code: class Model3D(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) description = models.CharField(max_length=500) original_Model = models.ForeignKey('Model3D', on_delete=models.CASCADE, null=True) creation_Date = models.DateTimeField(auto_now=True) stl_File = models.FileField(null=True, upload_to='models/stlFiles') scad_File = models.FileField(null=True, upload_to='models/scadFiles') parameter_id = models.ForeignKey('Parameter', on_delete=models.CASCADE, null=True) part_of = models.ForeignKey('Model3D', related_name="part_of_model3d", on_delete=models.CASCADE, null=True) picture_of_model = models.ForeignKey('Pictures', on_delete=models.CASCADE, null=True) class Pictures(models.Model): id = models.AutoField(primary_key=True) picture = models.ImageField(upload_to='models/pictures', null=True) model_id = models.ForeignKey('Model3D', on_delete=models.CASCADE) As you can see Model3D has a foreign key relationship to itself because a 3DModel can consist of a e.g. three other 3DModel parts. Therefore the field 'part of' which references Model3D again. Every Model3D objects has pictures in the Pictures class. My questions: How do I get an Model3D object with all of its part Models? How do I get all pictures of an Model3D object and all pictures of its part Models? I tried so many things regarding select_related but it does not really work. Thank you for your kind help! -
Django: Populate model with CountryField
I have a model which has a CountryField and I want to populate this model from a csv with data. How I set a value for the CountryField? -
Problem with django.db.utils.OperationalError: no such table: main.auth_user__old
I was trying to follow the tutorial https://github.com/stacklens/django_blog_tutorial of building a blog using Django. (The tutorial is written in Chinese, but I think the problem is about the model) When I setup superuser and trying to add my first article to the database as an admin. This error "django.db.utils.OperationalError: no such table: main.auth_user__old" occur. I looked up the similar question on the overflow, it seems that the problem is solved by upgrading Django version to 2.1.5. However, I'm using Django 2.2.7 which is the most recent version and still get the same error. I have tried downgrade the version to 2.1.5 but it still not working. -
Securing third party API keys of User while using them with my app
I am making a django app that needs 3rd party keys of user to fetch data periodicaly from different api and store in the app. How can I achive this without seeing or accessing the users API keys. If not how can I assure/convince them that I will never use or see their API key? -
How to integrate Tally ERP-9 with Python
How to integrate Tally ERP-9 with Python(Django) for Pushing and pulling amount based on ledger. -
Best implementation follow and unfollow in django rest framework
Trying to implement a following and followers and feature in Django-rest, if I were to create this not using rest framework, I have an idea how this can be done. But this time I have little to no idea how this can be done. Please: 1) What is the best way to do something like this assuming I am working on a big project? 2) I am majorly lost at what to do at the serializer and view section, I just know that that in the serializer part I select the following model alone Assuming I have a profile model like this class Profile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followers', blank=True) other content……. Please any help is appreciated -
Authentication credentials error in react app
I have a react app which uses a Django Rest Framework as backend. When I run both DRF as well as React app on local machine it works perfectly. But When I use the Amazon deployed version of the DRF, it does not let me sign-in in the react app Here's the settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ] } CORS_ORIGIN_ALLOW_ALL = True What is it that I am doing wrong? How can I use the live version of my backend with the local Frontend ?