Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass model fields to a signal receiver method?
I have a Founder(models.Model) with some fields like name=models.charfield; I want to execute post_save signal to a receiver function "generate" which will run a custom "management.call_command" function which takes "name" as an argument. To my understanding, this receiver "generate" function should be a method of a Founder for it to be able to take it's name field as an argument ? but when I'm creating a founder in admin, I get an error in console saying TypeError: generate() missing 1 required positional argument: 'self' -
Cross-project iframe testing on localhost with different ports
I am relatively new to iFrame, and what I try to do is to load project A in an iframe that is in project B. Project A is running as a Django project on localhost:8000, and project B as a separate Django project on localhost:8001. Inside the project B, I have a Django template with the following content: <iframe src="http://127.0.0.1:8001" height="500px" width="500px"></iframe> The problem is that instead of seeing the content of project A home page, I see error message stating that: 127.0.0.1 refused to connect Is there anything I am terribly missing? -
Nested if in Django Rest API [closed]
Want to update details in two models,so here using curresponding serializers and the out: first key value is updated but remaining is still not updating Help to solve this -
Django: Method to execute after "clean" in admin
Fairly simple: Which method can be overwritten after "clean" method? I am using "clean" to verify an uploaded image and once I confirmed it is ok and saved, I want to switch it using some external API: class FooAdminForm(forms.ModelForm): class Meta: model = Asset fields = ["name", "file",] def clean(self): cleaned_data = super(FooAdminForm, self).clean() ... return cleaned_data def bar(self): # do stuff with new data in database class FooAdmin(admin.ModelAdmin): list_display = ["name", "file",] form = FooAdminForm is there some method bar that can do what I need? Or do I have to wrsetle with a signal (like here)? -
Как в cookie хранить значение checkbox, чтобы у сайта была возможность вкл темный режим django [closed]
Я новичок и хочу в сайте сделать темный режим любим способом будто с помощью django или js -
django-rest-framework csrf cookie not set react
I am new to Django, react and "http header" related stuff. My django dev server runs at: http://127.0.0.1:8000/ and my react dev server runs at: http://127.0.0.1:3000 In order to access the website, login is required. So, all unauthorized requests are 1st redirected to login page, by configuring react-router and following this template. So, till now, no api calls are made. In order to post login data, i need to have csrf token set by the server. But since i have not made any api calls, i created an endpoint /api/csrf/ explicitly, to set the csrf token. # URL: /api/csrf/ class CSRFGet(APIView): """ Explicitly set csrf cookie """ @method_decorator(ensure_csrf_cookie) def get(self, request): return Response('hello') I call this endpoint, when useProvideAuth hook is mounted. function useProvideAuth() { const [token, setToken] = useState(null); const login = (username, password) => { return axios.post( '/auth/', { username: username, password: password }) .then(response => { setToken(response.token) }) } useEffect(()=> { axios.get( '/csrf/' ) },[]) return { token, login, } } To retrieve and set this cookie, i followed the official Django docs. I also enabled CORS policy using django-CORS-headers allow all origins. Now, when i make a request to any page, it redirects to login page, … -
preview before save image in Django admin inline
I'd like to preview the picture chosen as [choose file]. Like in the picture below. I'm using django, what should I do? admin.py class GolferPhotoInline(NestedStackedInline): model = GolferPhoto extra = 1 formset = GolferPhotoInlineFormset class GolferProfileInline(NestedStackedInline): model = GolferProfile extra = 1 inlines = (GolferPhotoInline,) @admin.register(GolferUser) class GolferUserAdmin(NestedModelAdmin): inlines = (GolferProfileInline,) readonly_fields = ("user_gender", "user_join_dts", "is_secession") fields = ["user_nm", "user_gender", "user_email", "user_tel"] list_display = [ "id", "user_nm", "user_gender", "user_email", "user_tel", "is_secession", "user_join_dts", ] -
How to create password confirmation with old password for update profile?
I want to create a confirmation for updating the profile. For example, when a user wants to change name or password, he/she should enter their old password for confirmation. How can I do that? models.py class UserProfile(AbstractUser, UserMixin): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) password = models.CharField(max_length=250) email = models.EmailField(max_length=254) image = models.ImageField(upload_to='profile_image', blank=True, null=True, default='profile.png') views.py def update_user(request, id): user = request.user form = SignUpChangeForm(request.POST or None, request.FILES or None, instance=user) if form.is_valid(): form.save() ... if form.cleaned_data['password1'] != "": user.set_password(form.cleaned_data['password1']) user.save() auth_login(request, user) return redirect('home') context = { 'form': form, } return render(request, "update_user.html", context) forms.py class SignUpChangeForm(forms.ModelForm): password1 = forms.CharField(max_length=250, required=False, label="New Password (leave blank if you do not want to change it)", widget=forms.PasswordInput) password2 = forms.CharField(max_length=250, required=False, label="New Password Confirmation (leave blank if you do not want to change it)", widget=forms.PasswordInput) class Meta: model = UserProfile fields = ('first_name', 'last_name', 'email', 'image') widgets = { 'password1': forms.PasswordInput(), 'password2': forms.PasswordInput(), 'old_password': forms.PasswordInput(), } def clean(self): cleaned_data = super(SignUpChangeForm, self).clean() if cleaned_data['password1'] != cleaned_data['password2']: raise ValidationError("Password confirmation does not match!") return cleaned_data -
How to Group by timestamp column serving as PK by day/month/year, and select that timestamp column at the same time in Django
I have a table with a 'timestamp' field as its PK. In Django View, I want to select all from the table and group by month('timestamp) and year('timestamp). In terms of MySQL script, I am looking for this: SELECT timestamp, sum(col1) col1, sum(col2) col2 FROM my_table GROUP BY MONTH(timestamp), YEAR(timestamp) ORDER BY timestamp One approach I have followed is from here. You can find more elaboration on that answer here. So to GROUP BY the rows, I work with annotate and values as discussed in this answer. The code in my Django View is the following: from django.db.models.functions import TruncMonth, TruncYear from django.db.models import Sum queryset = MyModel.objects .annotate(month=TruncMonth('timestamp'), year=TruncYear('timestamp')) .values('month', 'year') #Group by Month and Year .annotate(col1 = sum('col1'), col2 = sum('col2')) #Sum data of two columns .order_by('month', 'year') #Also tried 'timestamp' here. queryset_serialized = MySerializer(queryset, many=True) The code above does produce the query as expected. Here is the query generated from the code above: SELECT CAST(DATE_FORMAT(`timestamp`, '%Y-%m-01 00:00:00') AS DATETIME) AS `month`, CAST(DATE_FORMAT(`timestamp`, '%Y-01-01 00:00:00') AS DATETIME) AS `year`, SUM(`col1`) AS `col1`, SUM(`col2`) AS `col2` FROM `my_table` GROUP BY CAST(DATE_FORMAT(`timestamp`, '%Y-%m-01 00:00:00') AS DATETIME), CAST(DATE_FORMAT(`timestamp`, '%Y-01-01 00:00:00') AS DATETIME) ORDER BY `month` ASC However, while serializing the data … -
How to catch / get json from webhook in Django?
I am working with Pipedrive and Django. So far I have the following: I have configured a webhook in pipedrive that fires every time a new Deal is created, I am receiving the correct http status in the Django console, however, I cannot capture the data from the json that the webhook sends . The idea is to capture that data and then enter it into Django's model. -
Call function after update/bulk_update in Django
I am calling a function after an object is created in the model like this: class MyModel(models.Model): name = models.CharField() image = models.OneToOneField(Image, on_delete=models.CASCADE) def save(self, *args, **kwargs): super().save(*args, **kwargs) self.image.my_function() Now I want to call the same function after updating/bulk_updating the instances. I know I can create a post_save listener which can handle the case after update(), but how to call the function after bulk_update()? -
Odoo developer as a Full stack developer
Is odoo developer will work as a full stack developer later in career. He can work on core python and framework like Django??? -
Setting time zone according to user's Country
I am building a BlogApp AND i am stuck on a Problem. What i am trying to do :- I am trying to store timezone in every field ( post date, comment date ) according to User's Country. Suppose, A user is registered account on webapp from Brazil then i am trying to automatically set time zone of Brazil for the User. But i have tried many answers LIKE THIS and LIKE THIS but nothing worked for me. Some told that it should be done through JavaScript BUT i have no idea idea how can i do it. When i try to register then it automatically sets the timezone which i have settled in settings.py. TIME_ZONE = 'UTC' Any help would be appreciated. Thankyou in advance. -
user register form in the django not getting register
I am trying to register the user of the django website but it was not getting register I am posting the code please help me this is the code of the views.py where I get the input from django.shortcuts import render , redirect # Create your views here. from django.contrib.auth import login from django.contrib.auth.forms import UserCreationForm from .models import User_Main def become_user(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request , user) user_main = User_Main.objects.create(name = user.username, created_by=user) return redirect('home') else: form = UserCreationForm() return render(request, 'user_of_ecommerce/become_user.html' ,{'form':form}) code of urls.py from django.urls import path from . import views urlpatterns = [ path('become-user/' , views.become_user , name="become_user") ] and here is the code of the form {% extends "core_of_ecommerce/base.html" %} {% block content %} <form action="." method="post" > {% csrf_token %} {{form.as_p}} <div> <button>sbmot</button> </div> </form> {% endblock content %} another URLs.py from django.urls import path from . import views urlpatterns = [ path('' ,views.home, name='home') ] -
One transaction for mongoDB and MySQL with one to many relationship
My Django application uses both MySQL and MongoDB to store its data. I need to create one transaction to delete an instance with its relations from both MySQL and MongoDB. If the execution of one of the queries fails (SQL or Mongo) I must rollback all the executed queries. Is that possible? Example: from django.db import models class Car(models.Model): manufacturer = models.ForeignKey('Manufacturer',on_delete=models.CASCADE) # ... def delete(self, *args, **kwargs): ... # delete from mongoDB (must use a session to support multi document tr return super(Instance, self).delete(*args, **kwargs) class Motorcycle(models.Model): manufacturer = models.ForeignKey('Manufacturer',on_delete=models.CASCADE) # ... def delete(self, *args, **kwargs): ... # delete from mongoDB (must use a session to support multi document tr return super(Instance, self).delete(*args, **kwargs) class Manufacturer(models.Model): # ... pass def delete(self, *args, **kwargs): ... # delete from mongoDB (must use a session to support multi document transaction) return super(Instance, self).delete(*args, **kwargs) When I delete a manufacturer, I need to delete the related cars and motorcycles from both MySQL and MongoDB. If one transaction fails (let's say delete one of the motorcycles has failed for some reason), I need to rollback all the transactions. Is there any way to do it? -
preferred way of designing model in Django
I have a very simple model in Django with 3 fields. The issue is that I have dozens of billions of data that needs to be stored in the table associated with that model in Postgresql database. I stored around 100 millions of rows, and then my server first got sluggish and then gave me "Nginx 505 bad gateway" when clicking on that table in Django admin or requesting data using API. I was wondering what is the best way to handle this simple scenario of having massive data in Django. What's the best model. Should I split my model in order to split my table? Thanks, -
Why does ChannelsLiveServerTestCase doesn't allow file upload
I am currently using ChannelsLiveServerTestCase to spin-up a runserver for my test, for some reason when I try to test my file upload feature it is failing but when I try using different "test server" (StaticLiveServerTestCase) it is working well. I opted to use ChannelsLiveServerTestCase because I need the websocket support which is not possible with StaticLiveServerTestCase. -
Can't login my users, they don't seem to be registering properly
I'm trying to login the users I registered in my registration view (where I get a 200 code that says POST request was successful) but I get "Unable to log in with provided credentials." when I try to log them in. When I check in the shell with User.objects.all(), I only get my superuser back so I think the users are not being saved to the database. I don't understand why this is happening so if anyone has an idea, it'd be appreciated. Here's the code. Models: from django.db import models, transaction from django.conf import settings from django.contrib.auth.models import BaseUserManager, AbstractUser class UserManager(BaseUserManager): @transaction.atomic def create_user(self, email, username, password=False): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save() return user def get_by_natural_key(self, username): return self.get(username=username) def create_superuser(self, username, password, email): user = self.create_user( username=username, email=email, password=password, ) user.is_superuser = True user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField( verbose_name= 'username', max_length= 50, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return str(self.username) Serializers: … -
iterating issue in a for loop (Python3 + Django)
I am a newbie so please be kind, working on a blog app within my django project the idea is to check if there are articles , if there is list each article. if there is not articles show no articles found below is my view function, however when I test this it only list the first item in my list which mike, other names are not showing on the page or on source like they do not exist ??? any help with this would be great. thanks in advance def add(request): articles=["mike","sammy","ahmed"] if not articles : return HttpResponse("<body><h1>No Articles to display here</h1></body>") else: for article in articles: return HttpResponse(f"{article}") -
How can I allow a user to upload the template for a landing page for another user in Django?
I have the admin user able to upload via forms a landing page for a selected role (Student, Advisor, Admin) and I want to be able to get it to render properly. Right now, it renders properly the html and the css but prints out in plain text the {{ }}'s and the {% %}'s which isn't helpful. The view for the roles landing pages as of right now sends the plain text html (context['page'] = LandingPage.objects.get(role='adm', live=True)) stored in the database to the html stored in templates which has nothing in it except {{ page| safe}}. -
Add celery (tasker) To Django Admin panel on Search click
I am using the Admin panel of django for searching. Sometimes it can take 15 + minutes for search to finish and I get timeout (502). But search process still exist (consuming resources). I would like to show a progress bar waiting for task to finish when clicking: What is the best option for me ? -
django-channels: PUT request info not saving when user disconnects from websocket then reconnects
I have a problem. The app in question is basically complete, but there's a bug with the user PUT endpoint to edit the user info. If the websocket is disconnected, the endpoint works well. same if the websocket is connected. But If I edit the profile with the websocket connected, disconnect the websocket and connect it again, the changes I made are reverted. anyone know why? What's also weird is that the websocket is used only in chat, not for profile editing (chat is an entirely different app) Any help is appreciated -
Django HTML Email, Table List not working
Im working with Django HTML email. Sending Email with HTML template is working but my problem is the data not showing in table once already sent via email but in my localhost present. Please help me to fixed my issue,Thank You! This is the output when I show via localhost: This is the output when template already sent via email, The data in the table are missing. Here is my django email script: elif month == 4: cstatus = Regdata.objects.filter( Registration_month="APR", sent_email="No") s = "" for carreg in cstatus: print(carreg.PLATE_NO) s += carreg.PLATE_NO cstatus.update(sent_email="Yes") if s != "": subject = 'Hi' html_message = render_to_string('email.html', {'context':'value'}) plain_message = strip_tags(html_message) from_email = 'From <example@gmail.com>' to = 'example@gmail.com' mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message) Html Email Template: <body> <h2>Hi,</h2> <p>Body message..........</p> <table id="example" class="display nowrap" style="width:100%"> <thead> <tr> <th>Plate Number</th> <th>CR Name</th> <th>Model</th> <th>Brand</th> </tr> </thead> <tbody> {% for object in apr_email %} <tr class="odd gradeX"> <td>{{ object.PLATE_NO }}</td> <td>{{ object.CR_NAME }}</td> <td>{{ object.MODEL }}</td> <td>{{ object.BRAND }}</td> </tr> {% endfor %} </tbody> </table> </body> -
removing default --------- option from radio button rendering in template
I am trying to remove the -------- value in my radio button display. The field is declared like this in models.py my_field = models.CharField(max_length=50, choices=MY_CHOICE, blank=True, null=True) I am using this ModelForm to apply some custom CSS forms.py class MyAppForm(ModelForm): class Meta: model = MyApp exclude = [] def __init__(self, *args, **kwargs): super(MyAppForm, self).__init__(*args, **kwargs) self.fields['my_field'].empty_label = None for i, f in self.fields.items(): f.widget.attrs['class'] = 'custom-class' I have seen this line self.fields['my_field'].empty_label = None suggested in multiple Answers on StackOverflow, but, it seem to have no effect in my setup. I am getting the value of the selected choice using this piece of code in views.py def app_view(request, fk_id): app_value = MyApp.objects.get(my_fk=fk_id) # my_fk is a fk from another model app_form = MyAppForm(instance=app_value) I am rendering this form by simply {% for value, text in my_field.my_field.field.choices %} <li> <input id="{{ value }}" name="{{ app_form.my_field.name }}" type="radio" value="{{ value }}" {% if app_value.my_field == value %}checked="checked"{% endif %}> <label for="{{ value }}">{{ text }}</label> </li> {% endfor %} What could I be doing wrong in this setup that is not removing the default select option, ------? -
"Unable to log in with provided credentials." when trying to login my user
I'm getting this error when I try to login a registered user. I read a bunch of answers in people asking the same question but none of them have solved my issue so I'm confused at to what's happening. I added some stuff to my settings like some comments said and changed some things and so far this is what I've written to no avail. Maybe some extra eyes can help. Thank you. I'll show here my serializers: user = get_user_model() class UserRegistrationSerializer(serializers.ModelSerializer): username = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all(),lookup='iexact')] ) email = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all(),lookup='iexact')] ) password = serializers.CharField( required=True, label="Password", style={'input_type': 'password'} ) password_2 = serializers.CharField( required=True, label="Confirm Password", style={'input_type': 'password'} ) class Meta: model = User fields = ['username', 'email', 'password', 'password_2',] def validate_password(self, value): if len(value) < 8: raise serializers.ValidationError( "Password should be at least 8 characters long.") return value def validate_password_2(self, value): data = self.get_initial() password = data.get('password') if password != value: raise serializers.ValidationError("Passwords don't match.") return value def validate_username(self, value): if User.objects.filter(username=value).exists(): raise serializers.ValidationError("Username already exists.") return value def create(self, validated_data): user = User( email=validated_data['email'], username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user class UserLoginSerializer(serializers.ModelSerializer): username = serializers.CharField( required=True, write_only=True, ) token = serializers.CharField( allow_blank=True, read_only=True ) password …