Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and Heroku: Request has blocked by CORS in production
I created a single page web app and used Django as backend. The webapp worked as expected on local but my requests from client side has been blocked by CORS in production (I host backend on Heroku). My current code is like this. settings.py INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ... ] ... CORS_ALLOWED_ORIGINS = [ "http://...", ] ... This settings works on local but doens't work on production. Am I missing something? -
django.db.utils.OperationalError: FATAL: password authentication failed for user using postgres
I have this code in my settings.py, and why i am getting this is error? django.db.utils.OperationalError: FATAL: password authentication failed for user "gmovesDatabasev1"? ive already done doing this to my pgadmin CREATE USER gmovesDatabasev1 WITH PASSWORD 'password'; and still im getting stuck in this error DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'gmoves', 'USER': 'gmovesDatabasev1', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', } } -
How to prevent Duplicate Signals in Django
I have added a notification where every time a user submits a Like button to a post, the owner of the liked post receives a notification. I have set Value options for each Like button to be Like or Unlike I have restricted the notification to be sent only if the Value of the like clicked is Like only. So, now in the Like Model I have added signal and a condition that if the Like.value== Like the signal activates but for some reason it is sent twice only when a new post is created and a new user clicks like for the very first time, afterwards if he unike and likes again it is sent once. My question is: Why is the signal duplicated everytime a new user clicks the Like button? How to fix it? Here is the post models.py: class Post(models.Model): title = models.CharField(max_length=100, unique=True) likes = models.ManyToManyField(User, related_name='liked', blank=True) here is the Like model.py: LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): # To know Who liked user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.post}-{self.user}-{self.value}" def user_liked_post(sender, instance, *args, … -
I'm using the Google Calendars API with Django, where do I get my token and refresh_token?
I'm trying to do something like what's shown below. However, I can only see my client ID and secret key on the developers console. I wasn't sure about the token, but I tried creating an API key and passing that in. However, I have no clue where to get the refresh_token. I've included a screen cap of my developer console. We're using django-allauth, and I know that you can set social account tokens in the Django admin, is that what I would need to do? from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials creds = Credentials( token='token here', refresh_token='refresh token here', scopes=['scopes', 'listed', 'here'], token_uri='https://accounts.google.com/o/oauth2/token', client_id='client_id', client_secret='client secret' ) creds.expiry = timezone.make_naive(self.token.expires_at) if not creds.valid or creds.expired: creds.refresh(Request()) -
Use Wordpress for authenticating Django users
I have a WordPress site with multiple users configured. I also have a Django-based site. I would like to have my Django site use the Wordpress site to authenticate users. Is it possible to have Wordpress serve as an authentication server for a Django site? If so, how? If that's not practical, I would also be OK with configuring a self-hosted third-party authentication server that both systems could query to authenticate a user. The net result, either way, is that I'd like for the same Wordpress credentials to work in Django, even if it requires entering them separately - I don't need the logged-in session to pass from one to the other. Thanks! -
django-allauth AUTHENTICATED_LOGIN_REDIRECTS is not working
the redirect from /login/ when user is authenticated is handled in this method: class RedirectAuthenticatedUserMixin(object): def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated and app_settings.AUTHENTICATED_LOGIN_REDIRECTS: redirect_to = self.get_authenticated_redirect_url() response = HttpResponseRedirect(redirect_to) return _ajax_response(request, response) else: response = super(RedirectAuthenticatedUserMixin, self).dispatch( request, *args, **kwargs ) return response def get_authenticated_redirect_url(self): redirect_field_name = self.redirect_field_name return get_login_redirect_url( self.request, url=self.get_success_url(), redirect_field_name=redirect_field_name, ) the AUTHENTICATED_LOGIN_REDIRECTS is set by default to True according to documentation using breakpoints to debug, I have found out that request.user.is_authenticated and app_settings.AUTHENTICATED_LOGIN_REDIRECTS is always returning false, changing the condition to request.user.is_authenticated and settings.AUTHENTICATED_LOGIN_REDIRECTS the condition was corrected and it returns True and the user was redirected from /login/ URL to the one set in settings: LOGIN_REDIRECT_URL = "/" my question why the app_settings was not able to fetch the variables in settings? and How do I fix this problem? -
How to reload django app if there is a file change inside it?
I have two api in django apps python, create model api and use model api for predict data. how to automatically reload file change on it? -
Django template parse model field into a html string
I am trying to loop through a model field in my template, for each value I would like to add an image to my web page. However this involves parsing the value into the src attribute for the image which is a string. code: <td class=""> {% for i in card.colors %} <img class="icon" src="{% static 'img/symbology/{ {{i}} }.png' %}"> <span>{{i}}</span> {% endfor %} </td> screenshot: -
Problemas al momento de trabajar en el modelo django el error que me da es (TypeError: __str__ returned non-string (type tuple))
He intentado varias cosas para poder solucionar esto tanto el .format que busque dentro de otras preguntas pero aun no logro solucionarlo asique ya despues de recorrer todo lo que entendi no encontre mas que hacer esto sucede cuando entro a la pagina de admin y apreto para agregar al Horas_medica class Horas_medica(models.Model): id_boxes = models.ForeignKey(Boxe, on_delete=models.CASCADE) id_medico = models.ForeignKey(Medico, on_delete=models.CASCADE) id_paciente = models.ForeignKey(Paciente, on_delete=models.CASCADE) descripcion = models.TextField() diagnostico = models.TextField() created_date = models.DateTimeField( default=timezone.now) def __str__(self): return str(self.id) y la consola me devuelve TypeError: str returned non-string (type tuple) -
How to return the partial result of a search to a grid?
Currently, the system I work on (python / django / dojo) has a textual search feature inside .pdf files. It is a heavy search and the return is total: it returns all the records that matched the search only when it finishes browsing all the records. Exemple.: def search_document(request): list = [] for doc in Document.objects.filter(QQ): # search inside every reg with .pdf # if it match list.append(doc) return list I would like to return to the screen as the records match. What should be the logic to be used? Tool? Ajax? Jquery? -
Django template replace text returned from model with local image
I have have a model which I am pulling data from and adding it into a table on my page. There is a particular field I am returning which contains a combination of 64 version of {x}. Replacing each version with a corresponding image. For example, the data is returned in the format of {B}, {B}{U},{B}{B},{1}{W}{R}. There are 64 different version of {x} which could be arranged in any combination. I have corresponding .png files for each version, and I am trying to replace the text with the image. My code below only works if there is an single instance of a version, however I also think it would be very inefficient if I were to do this for each of the 64 versions. It doesn't work if there are multiple of the same version, eg. {B}{B} Is there a way I could loop through each one and replace it with the correct image. html <td class=""> {% if "{B}" in card.colors %}<img class="icon" src="{% static 'img/symbology/{B}.png' %}">{% endif %} {% if "{G}" in card.colors %}<img class="icon" src="{% static 'img/symbology/{G}.png' %}">{% endif %} {% if "{R}" in card.colors %}<img class="icon" src="{% static 'img/symbology/{R}.png' %}">{% endif %} {% if "{U}" in … -
Access editing profile only by profile owner using UserPassesTestMixin showing error?
i have managed to create profile pages for each user and every user should edit their own profile. in model, i have used AbstractUser model. and for the editing access i have imported UserPassesTestMixin. here is my models.py: class Profile(AbstractUser): name=models.CharField(max_length=30, blank=True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birthdate = models.DateField(null=True, blank=True) here is my views.py: class ProfileDetailView(DetailView): template_name='profile.html' model=Profile def get_user_profile(self,pk): return get_object_or_404(Profile,pk=pk) class ProfileEditView(LoginRequiredMixin,UserPassesTestMixin,UpdateView): model=Profile template_name='profile_edit.html' fields=['name','bio','birthdate','location','gender',] login_url='login' success_url = reverse_lazy('home') def get_user_profile_edit(self,pk): return get_object_or_404(Profile,pk=pk) def test_func(self): obj = self.get_object() return obj.username == self.request.user the problem is when the logged in user wants to edit it's profile it is showing 403 forbidden. no user can edit their profile. in test function what should is use to fix that? -
no data found issue while running selenium on DJango
I have made a crawler which extracts data from a website I have used selenium in headless mode with chrome webdrivers. I am trying to integrate the same with the Django as an api, it is not fetching the data returning NoDatafound exception. But the same code is woking fine on my jupyter notebook. I have tried with both selenium and splinter both are not working. -
Django -> Registering New User -> Check if the user is already authenticated by email and username
I have the following code in my register_view function. When I register a new user it updates in the database, but I want to check whether a user has already been authenticated by email or user. I have tried request.user.is_authenticated but this always returns true, and the request body is always saving when I fire a new POST call. @csrf_exempt def register_view(request): if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') email = form.cleaned_data.get('email').lower() raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) return JsonResponse(f'User {email} : {username} has been registered.', status=200, safe=False) else: form = RegistrationForm() return JsonResponse('You are missing some fields.', status=422, safe=False) --> User Model class User(AbstractBaseUser): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) email = models.EmailField(verbose_name="email address", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'firstname', 'lastname'] class Meta: db_table = "users" def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True --> Registration Form class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=255, help_text="Email address required.") firstname = forms.CharField(max_length=30, help_text="First name required.") lastname = … -
How do I make POST form-data request with Alamofire? - Swift
I am trying to imitate this in Xcode using Alamofire: Here is what I created on Swift/Xcode according to Alamofire docs : let url = "http://127.0.0.1:8000/" /* your API url */ AF.upload(multipartFormData: { multipartFormData in multipartFormData.append(Data("one".utf8), withName: "file") }, to: url, method: .post) .responseJSON { response in debugPrint(response) } The response I get from the server is. "Number of Files: " = 0; Meaning the server is not receiving the file, however it works when I do it from Postman, so what am I missing? Also here is my django server which is taking the request, if this is needed: @csrf_exempt def test(request): length = 0 try: length = len(request.FILES) except Exception as e: print(e) return JsonResponse({'Number of Files: ': length}) -
Filtering between two models to get aggregates in Django
I have these two models Transactions and bank statement. I am trying to reconcile transactions that have been paid based on the bank statement entry. The assumption is that from the BankTransaction model Naration we can be linked to invoices from transaction model. How do I filter the BankTransaction based on the transaction model to generate the following results Total invoice paid by each customer (credited to the bank) total amount due by each customer class Transactions(models.Model): customer_name= models.ForiegnKey(Customer, on_delete= Model.CASCADE) ..... Invoice_Number= models.CharField(max_length=20) Invoice_date = models.DateField() Date_Due = models.DateField() Invoice_status =models.CharField(max_length=20) def __str__(self): return 'Invoice Number: {}'.format(self.Invoice_Number) def save(self,*args,**kwargs): .... if self.Invoice_date < self.Date_Due: self.Invoice_status = 'Not Due' else: self.Invoice_status = 'Due' super().save(*args, **kwargs) class BankTransaction(models.Model): Bank_name= models.CharField(max_length= 50) .... Narration= models.CharField(max_length=100, blank=False, null=False)// this contains details of the invoice def __str__(self): return self.Bank_name -
How do I use the Google Calendars API on my Django project hosted on Heroku?
In my project, a user can input details into a form, and the information is used to create an event with Google calendars. This works fine locally, however when I put the site up on Heroku, it does not work (according to the logs, it tries to get the server to open a window and sign in/authenticate). However, I'm still struggling to figure out how to get the API working on a server-side application. I'm already using oauth to allow users to sign in with their Google accounts, so I'm thinking that I need to use those same credentials. Here is some of the code from my views.py that is used to create the calendar event: SCOPES = ['https://www.googleapis.com/auth/calendar'] flow = InstalledAppFlow.from_client_secrets_file(os.path.dirname(os.path.realpath(__file__)) + '/credentials.json', SCOPES) service = build('calendar', 'v3', credentials=creds) event = { ... } service.events().insert(calendarId='primary', body=event).execute() service.close() Where credentials.json is the file I got from the Python Quickstart tutorial. as I understand it I need to use the json from the oauth settings used for Google login, but I'm not really sure where to go from there. I found this tutorial from Google for server-side apps, but the code seems a little verbose and I'm feeling like I shouldn't … -
Django - How to change form field based on database variable?
I'm making a survey app. There's a question class that specifies what type of input it would like (text, dropdown, checkbox, radio). My questions is: How can I change a form field from a text field to a dropdown, or a series of checkboxes, or radio buttons etc. programatically based on the variable in the question class? I currently have this code for my form_class for answers to the questions: forms.py class AnswerCreationForm(forms.ModelForm): answer = forms.CharField(widget=forms.TextInput(attrs={'class':'text_input', 'placeholder': 'enter your answer here...'})) class Meta: model = Answer fields = ('answer',) This works fine when the question expects a TEXT response, but I'm wondering if theres a way for me to change "answer" to a "choiceField" when the question is looking for a multi choice repsonse with the relevant choices programatically? This is my code for my question model: models.py class Question(TimeStampMixin): class AnswerType(models.TextChoices): TEXT = 'TEXT', "Text" DROPDOWN = 'DROPDOWN', "Drop Down" CHECKBOX = 'CHECKBOX', "Checkbox" RADIO = 'RADIO', "Radio Buttons" survey = models.ForeignKey('surveys.Survey', db_index=True, related_name="questions", on_delete=models.PROTECT) question = models.TextField() order = models.IntegerField() answer_type = models.CharField(max_length=8, choices=AnswerType.choices) def __str__(self): return self.question and when answer_type isn't TEXT, the choices for the answer are stored in this class: models.py (continued) class AnswerChoice(TimeStampMixin): question … -
Django application: the directory_name to which an image has to be uploaded, should be auto populated
I want to upload images to the django server using my application and the folder/directory_name to which the image has to be uploaded, should be auto populated using the foreignkey relationship that my models are sharing My models classes are as follows, class Event(models.Model): event_name = models.CharField(max_length=200) event_desc = models.CharField(max_length=5000) def __str__(self): return self.event_name class Image(models.Model): event_id = models.ForeignKey(Event, on_delete=models.CASCADE) image_name = models.CharField(max_length=200) image = models.ImageField(upload_to='events/{}'.format("something")) def __str__(self): return self.image_name the something in the models.ImageField function has to be replaced by the event_name dynamically and the value for event_name should be populated dynamically. -
views.edit didn't return an HttpResponse object. It returned None instead
I'm trying to edit items on a form on a page called 'website/edit1,2,3,4,...' When I click 'edit' after editing the form items, I get the error above. None of the errors on the site resembles a solution. The tutorial I was following (and now trying to add my own edit function) says to import HttpResponseRedirect and not HttpResponse as in the solutions on S/O. Anyways, here's the views.py file from django.shortcuts import render, redirect from .models import List from .forms import ListForm from django.contrib import messages from django.http import HttpResponseRedirect def home(request): all_items = List.objects.all return render(request, 'home.html', {'all_items': all_items}) def about(request): return render(request, 'about.html', {}) def edit(request, item_id): if request.method == 'POST': item = List.objects.get(pk=item_id) form = ListForm(request.POST or None, instance=item) if form.is_valid(): form.save() messages.success(request, ('Item Had Been Edited')) return redirect('home') else: item = List.objects.get(pk=item_id) return render(request, 'edit.html', {'item': item}) def delete(request, item_id): item = List.objects.get(pk=item_id) item.delete() return redirect('home') Here's the urls.py file from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('about', views.about, name='about'), path('delete/<item_id>', views.delete, name='delete'), path('edit/<item_id>', views.edit, name='edit') ] .. . and the forms.py file from django import forms from .models import List class ListForm(forms.ModelForm): class Meta: model = List fields … -
Code optimization in a Django when populating field based by a foreign key
I'm searching for some advice on the optimization problem. In this case, I'll use a simple example, I've got these classes: class Genere(models.Model): genere_name = models.CharField(max_length=100) short = models.CharField(max_length=2) class Book(models.Model): name = models.CharField(max_length=100) genere_name = models.ForeignKey(Genere, on_delete=models.SET_NULL, null=True) book_system_id = models.CharField(max_length=100) My field book_system_id describe id number based on genre, for example (in a simplified way): id|name |genere_name|book_system_id 1|Dune |sci-fi |sf001 2|Invisible Man |novel |n001 3|Kindred |sci-fi |sf002 4|Neuromancer |sci-fi |sf003 5|IThings Fall Apart|novel |n002 Now, to populate the field book_system_id in views I use queryset to count elements based by genre, and I'm updating this object (genere_id I'm passing in URL to view function when I create new book object), bellow this is the code snippet: book.save() book.book_system_id = genere.short + str(Book.objects.filter(book_system_id=genere_id).count()) book.save() I'm knowing that this is probably the worst way to do this. That will be really slow when I have a big amount of objects stored in this table. I am wondering how to improvise to do this in the best way; I can add an extra field to store number current order, and when a new object is saved we can get the last number from DB. The second idea was that I can … -
Django Rest Framework - Write for Relational nested Serializers
I am quite new DRF so I am sorry beforehand for any mistake. For example, I have Post model which has Author as foreign key to NewUser model. When I list posts, instead of getting primary key of author, I wanted to get nested object with author details and that is why I created my serializer like this. class PostAuthorSerializer(serializers.ModelSerializer): class Meta: model = NewUser fields = ["id", "email", "user_name"] class PostSerializer(serializers.ModelSerializer): author = PostAuthorSerializer() class Meta: model = Post read_only_fields = ("slug",) fields = ( "id", "title", "author", "excerpt", "content", "status", "slug", ) lookup_field = "slug" However, now I don`t how to /POST a post back. I searched for 2 days but cannot find a proper guide for understand how to do. My main goal is to learn/understand rather than solve the issue so a little bit explanation also would be great! I was really motivated to learn DRF, but I think it lacks a detailed documentation and examples in internet or at least I could not find answer to my question. So, I want to learn 2 ways of posting: Representation is staying this way but I still /POST a post with showing "author":id Representation is staying this … -
Django global/thread objects
Often in Django I want to create and configure some object at startup, and have it available everywhere. For example a third-party API client. So when django starts I want to do this: from some.thirdparty import ThirdPartyClient from django.conf import settings ... my_thirdparty_client = ThirdPartyClient(configstring=settings.SOME_CONFIG_ITEM) And then in a view somewhere I want to do this: from somewhere import my_thirdparty_client def whatever(request): my_thirdparty_client.do_stuff() my_thirdparty_client.do_even_more_stuff() Obviously I understand that I can instantiate the client at the start of the view, but if initalizing the instance is expensive I don't want to do it on every request. What is the idiomatic Django way of creating these kinds of objects that I want to share between views? -
Exception has occurred: ImportError using Django on lines 13 and 23
When I try to rune the [ python manage.py runserver ] to run the server I get an "Exception has occurred: ImportError" and then it will states "Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? File "/Users/tarikzukic/Desktop/DJwebsite/manage.py", line 13, in main raise ImportError( File "/Users/tarikzukic/Desktop/DJwebsite/manage.py", line 22, in main()" Down bellow is the code snippet to be examined. #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DJwebsite.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
__str__ returned non-string (type datetime.date)
In Django I have 2 models: in inventory/models.py: class Transaction(models.Model): date = models.DateField() product = models.ForeignKey( Product, on_delete=models.PROTECT) type = models.ForeignKey(TransactionType, on_delete=models.PROTECT) quantity = models.IntegerField() location = models.ForeignKey(Location, on_delete=models.PROTECT) note = models.TextField(null=True, blank=True) def __str__(self) -> str: return f'{self.date}, {self.product.name}, {self.type.name}' And it's working normal. On the other hand. This model in sales/models.py: class Sale(models.Model): date = models.DateField() sale_id = models.IntegerField() sku = models.CharField(max_length=10) product = models.CharField(max_length=100) quantity = models.IntegerField() price = models.FloatField() channel = models.CharField(max_length=100) nooks_payout_schedule = models.ForeignKey( NooksPayoutSchedule, on_delete=models.RESTRICT, blank=True, null=True) def __str__(self) -> str: return f'{self.date}, {self.product}' give me error: __str__ returned non-string (type datetime.date) when trying to see it in admin dashboard. What Ive tried Ive tried to use str(self.date), but it's same error. I can't see the difference between those 2 models yet they are working differently. Do you know why? Full trace: Environment: Request Method: GET Request URL: http://localhost:8000/admin/sales/sale/160/change/ Django Version: 3.1.2 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'sales', 'inventory', 'graphene_django', 'corsheaders', 'django_pivot', 'drf_spectacular', 'django_extensions'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/tomo/anaconda3/envs/vdora/lib/python3.8/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19 __str__ returned non-string (type datetime.date) 9 : {% for field in line %} 10 …