Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Updating email field in both user and custom user models
When creating an account, I have a registration form made of 2 forms, from which email field gets saved in both User and Student models. Now, I made an update account info view. Problem is, I want that email will get updated the same, in both models. But I get error: 'StudentEditForm' object has no attribute 'email' Here is my code: class StudentEditForm(forms.ModelForm): email = forms.EmailField(required=False) name = forms.CharField(max_length=30) surname = forms.CharField(max_length=50) photo = forms.ImageField(required=False) phone = forms.CharField(max_length=15, required=False) class Meta: model = Student fields = ('email', 'name', 'surname', 'phone', 'photo') class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=30, null=True, blank=True, default=None) surname = models.CharField(max_length=50, null=True, blank=True, default=None) email = models.EmailField(unique=True, null=True, blank=True, default=None) student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')], null=True, blank=True, default=None) photo = models.ImageField(upload_to='students_images', null=True, blank=True, default=None) phone = models.CharField(max_length=15, null=True, blank=True, default=None) def __str__(self): return self.surname User.student = property(lambda p: Student.objects.get_or_create(user=p)[0]) def profile_edit(request): user = request.user student = request.user.student if request.method != 'POST': form = StudentEditForm(instance=student) else: form = StudentEditForm(request.POST, instance=student) user.email = form.email form.save() return render(request, 'index.html') context = { "form": form, } return render(request, "registration/profile_edit.html", context) -
Hide password field in GET but not POST in Django REST Framework where depth=1 in serializer
I have 2 models : User & UserSummary. UserSummary has a foreign key to User. I just noticed that if I set depth= 1 within UserSummarySerializer, the password field is included in the output. It's hashed, but it would still be best to exclude this field. To hide the password field, I've just set the user field explicitly in the serializer, just like this : class UserSerializer(serializers.ModelSerializer): """A serializer for our user profile objects.""" class Meta: model = models.User extra_kwargs = {'password': {'write_only': True}} exclude = ('groups', 'last_login', 'is_superuser', 'user_permissions', 'created_at') def create(self, validated_data): """Create and return a new user.""" user = models.User( email = validated_data['email'], firstname = validated_data['firstname'], lastname = validated_data['lastname'], mobile = validated_data['mobile'] ) user.set_password(validated_data['password']) user.save() return user class UserSummarySerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = models.UserSummary fields = '__all__' depth = 1 The downside of this way of doing is that, the field password is not available anymore on the POST request when creating a new user. How could I hide the password field on the GET request of UserSummary but display it in the POST request of User ? -
How does the Model Class convert attributes to database columns? DJANGO
Before posting this question, I have read through the Official Django Documentation, scouring it for a comprehensive explanation for beginners. I have read the code of the actual Model Class, and searched around on StackOverflow. When working with databases in Django, you work with classes inheriting from the Model class in the models module. This helps programmers avoid double-typing everything, jumping between database specific syntax and python. As I have read, 'the model class that each model inherits from automatically takes care of translation'. How does this work? How Does the Model Class convert model attributes to database columns? I suppose some methods inherited from the parent Model Class are able to use the variables specified in each new model, but would like a better explanation if possible! Also, why write 'models.Model' if the Model class is within models.base? LINK TO MODEL CLASS: https://docs.djangoproject.com/en/1.11/_modules/django/db/models/base/#Model -
SMTPAuthenticationError in Django
I have a problem like in a subject. I've create the form for sending emails from my project in django. When I set everything the python responde me a error. SMTPAuthenticationError at /kontakt/ (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials g69sm1490980lji.90 - gsmtp') I wanto to say I turn on in lessscureaps and still this same problem. I have no idea where can be a error. In settings.py I have EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mymail@gmail.com' EMAIL_HOST_PASSWORD = '********' EMAIL_PORT = 587 EMAIL_USE_TLS = True In views.py I declared the function : def kontakt(request): sent = False if request.method == 'POST': form = WyslijEmail(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] send_mail(subject, message, from_email,['mymail@gmail.com']) sent = True else: form = WyslijEmail() return render(request,'bajki/kontakt.html', {'form':form, 'sent': sent}) And in kontakt.html I have a code {% if sent %} <h1>Wysłano</h1> {% else %} <h1>Wyslij email</h1> <form action="." method="post"> {% csrf_token %} {{ form.as_p }} <p><input type="submit" value="Wyślij wiadomość"></p> </form> {% endif %} Maybe someone have some ideas how to solve this problem? -
Django 2 paths and urls
I am starting with Django 2 and there is significant change to urls with paths and all that. Does anyone know how to write a path from a template view now? If I previously wrote something like: url(r'^about/$', TemplateView.as_view(template_name='about.html')), Or if I include an app like: url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), What would it look like with paths in Django 2? -
TypeError: Object of type 'Decimal' is not JSON serializable
We have a field with JSON (PostgeSQL JSONB) where product prices are stored: {"total": 2400000, "currency": "USD", "per_meter": 3404} When we try to filter this field with NumberFilter with django-filters library we've got an error: TypeError: Object of type 'Decimal' is not JSON serializable https://sentry.io/share/issue/43b4eb682bf64562961f12f60b05f9f6/ django 2.0.1 django-filters 1.1.0 rest_framework 3.7.7 Error query: SELECT "core_properties"."id", "core_properties"."src_id", "core_properties"."is_public", "core_properties"."property_type", "core_properties"."place_id", "core_properties"."place_building_id", "core_properties"."place_section_id", "core_properties"."created_at", "core_properties"."updated_at", "core_properties"."is_for_sale", "core_properties"."s_src_updated_at", "core_properties"."is_for_rent", "core_properties"."r_src_updated_at" FROM "core_properties" INNER JOIN "core_places" ON ("core_properties"."place_id" = "core_places"."id") INNER JOIN "core_places_sites" ON ("core_places"."id" = "core_places_sites"."places_id") INNER JOIN "core_properties_sale" ON ("core_properties"."id" = "core_properties_sale"."property_id") WHERE ("core_properties"."property_type" = 'квартира' AND "core_properties"."is_for_sale" = True AND "core_places_sites"."site_id" = 3 AND ("core_properties_sale"."price_rub" -> 'total') >= <django.contrib.postgres.fields.jsonb.JsonAdapter object at 0x11131b6a0>) -
Django problems with primary keys and data inserts
My console shows this problem when trying to push data into my db invalid literal for int() with base 10: My views.py class: def routineInput(request): if request.method == 'POST': form = CreateRoutine(request.POST) query = request.POST["name_of_routine"] newEntry = Todolist(str(query)) #newEntry.name = () if form.is_valid(): newEntry.save() return HttpResponseRedirect('/todo/saved/') else: form = CreateRoutine() This is my models.py class: class Todolist(models.Model): id = models.AutoField(primary_key=True) name = models.TextField() created_at = models.DateTimeField(default = datetime.now, blank = True) updated_at = models.DateTimeField(default = datetime.now, blank = True) The newEntry = Todolist(str(query)) is my problem. If I change it to newEntry = Todolist(1, str(query)) my code works. But in the last case my code pushes the integer into the "id" field although it should be my auto increment primary key. Without the integer in my function my browser throws me this message: invalid literal for int() with base 10:... -
Django CBV best practice: Setting instance variables
In a class based view, I want to set an instance variable. This variable creates an instance from another class which collects data from other parts of the code to be used in the get_context_data. In this older question, and this newer one, @jpic and @catavaran suggest that the logic of instance variables can be deployed at the dispatch method: ...you could parse the request and set class view instance attributes in an overload of django.views.generic.base.View.dispatch, this is safe according to the source In an October 2013 talk Andrew Pinkham suggests that Overriding dispatch() is appealing (and what I did originally when I presented this talk) because it offers a single simple place to do so, but this defies the logic of dispatch(). Instead, it is best to call set_account() [a method that defines instance variables] in overrides of both get() and post(). At a first glance this is not very DRY. Moreover, the author uses a vague argument to promote it as a better solution, closer to the logic of CBV. Thank you @danielroseman, I fully understood that by overriding the get method, the logic of CBV is purely defied: By overriding get, you've bypassed all the built-in functionality … -
python django number format
I'm trying to format numbers. Examples: 24.324324324324323 18.91891891891892 I want to delete the numbers behind it to be like this 24.3 18.9 what can use django template tags? or using some code? -
Django Python "TypeError: view must be callable or a list/tuple in the case of include()" with urls
I'm getting a "TypeError: view must be callable or a list/tuple in the case of include()" for the subscribe url below for Weather_App/urls.py import signupform.urls import signupform.views as views app_name = "Weather_App" urlpatterns = [ url(r'^admin/', admin.site.urls, name='admin'), url(r'^subscribe/', signupform.urls, name='signup'), ] In my other urls file signupform/urls.py, I had a similar issue but fixed it using a views import from django.conf.urls import url from . import views as Weather_App_views urlpatterns = [ url(r'^$', Weather_App_views.index, name='index'), url(r'confirm/$', Weather_App_views.confirm, name='confirm'), ] -
How to populate django form , based on two ModelForm
I want my app users to be able to edit two forms using one html page , where these two forms will be populated with initial data from two related models,but i am not able to accomplish this result yet, models.py class User(AbstractUser): is_vendor = models.BooleanField(default=False) class Vendor(models.Model): user = models.OneToOneField(User) phone = models.CharField(max_length=15) forms.py class VendorProfileForm(forms.ModelForm): class Meta: model = Vendor fields = ['phone',] class UserForm(forms.ModelForm): class Meta: model = User fields = ['username','email'] views.py def Edit_Vendor_Profile(request, pk): # querying the custom User model . user = User.objects.get(pk=pk) if request.method == "POST": vendor_form = VendorProfileForm(request.POST,request.FILES, instance=user) user_form = UserForm(request.POST, instance=user) if vendor_form.is_valid() and user_form.is_valid(): vendor_form.save() user_form.save() return HttpResponseRedirect('/profile/') else: vendor_form = VendorProfileForm(request.POST,request.FILES, instance=user) user_form = UserForm(instance=user) return render(request, "accounts/update.html", {'vendor_form':vendor_form, 'user_form':user_form}) so the problem is that fields of user model are being populated fine but fields from Vendor model are not.so what that i am doing wrong, thank you very much in advanced . -
Can you save a new object over an existing object?
Let's say I have the following Listing model. I retrieve a listing and store that in old_listing, and set up a new one and store that in new_listing. Now is there some way to save new_listing into old_listing, basically overriding all fields except the auto-incrementing id field? class Listing(models.Model): street = models.CharField(max_length=500) old_listing = Listing.objects.get(id=1) # Assuming this record already exists new_listing = Listing(street='123 Main Street') old_listing.save(new_listing) # This obviously doesn't work -
"to" argument must be a list or tuple in Django
I have a bug like in subject of this question: "to" argument must be a list or tuple I want to create a email form and I can't find a error. Maybe someone help me? My files are: forms.py from django import forms class WyslijEmail(forms.Form): name = forms.CharField(max_length=25) subject = forms.CharField(max_length=255) email = forms.EmailField() message = forms.CharField(required=True, widget=forms.Textarea) views.py from django.shortcuts import render, redirect from django.core.mail import send_mail, BadHeaderError from .forms import WyslijEmail def kontakt(request): if request.method == 'GET': form = WyslijEmail() else: form = WyslijEmail(request.POST) if form.is_valid(): name = form.cleaned_data['name'] subject = form.cleaned_data['subject'] email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(name,subject,email,message, ['admin@gmail.com',]) except BadHeaderError: return render('Niewlasciwe cos tam') return redirect('sukces') return render(request,'bajki/kontakt.html', {'form':form}) def sukces(request): return render('Sukces udało sie') kontakt.html <form method="post"> {% csrf_token %} {{ form.as_p }} <p><input type="submit" value="Wyślij wiadomość"></p> </form> What I must define to fix this problem? -
Generic detail view needs object pk or a slug
But I already refer to primary keys, don't I? It says this error relates to: class CommentUpdate(UpdateView): model = Comment fields = ['body'] def form_valid(self, form): film = Film.objects.get(pk=self.kwargs['film_id']) comment = Film.objects.get(pk=self.kwargs['comment_id']) form.instance.user = self.request.user form.instance.film = film form.instance.comment = comment return super(CommentUpdate, self).form_valid(form) I am not sure once this issue is fixed if that code above will work but the view I have to create a comment does: class CommentCreate(CreateView): model = Comment fields = ['body'] def form_valid(self, form): film = Film.objects.get(pk=self.kwargs['film_id']) form.instance.user = self.request.user form.instance.film = film return super(CommentCreate, self).form_valid(form) My urls.py: path('<int:film_id>/comment/', views.CommentCreate.as_view(), name='add_comment'), path('<int:film_id>/comment/<int:comment_id>/', views.CommentUpdate.as_view(), name='update_comment'), model: class Comment(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) film = models.ForeignKey(Film, on_delete=models.CASCADE) body = models.CharField(max_length=200) def get_absolute_url(self): return reverse('films:detail', kwargs={'pk': self.film.pk}) And html link I have: <a href="{% url 'films:add_comment' film_id=film.id %}">Leave a comment</a> <a href="{% url 'films:update_comment' film_id=film.id comment_id=comment.id %}">Update</a> -
Many errors on deploying local Django app to Heroku
This is my first time to use Heroku . I have gone through other questions , but I am facing multiple errors , eg. some are related to Procfile not able to get identified (i have done an echo too using other question ) and I am also confused about how my app's structure should be deployed . My Django App structure : Please ignore the /api directory - i am not using it all Current error : I am following these tutorials but I am totally confused about what is my App and what is my Django project . Currently my git repository starts from /wantedly . The project is working fine on local . I need step by step help on how to deploy my local django app to heroku . -
Return particular string from response
I am trying to return a particular string value after getting response from request URL. Ex. response = { 'assets': [ { 'VEG': True, 'CONTACT': '12345', 'CLASS': 'SIX', 'ROLLNO': 'A101', 'CITY': 'CHANDI', } ], "body": "**Trip**: 2017\r\n** Date**: 15th Jan 2015\r\n**Count**: 501\r\n\r\n" } This is the response which i am getting, from this I need only Date: 15th Jan 2015. I am not sure how to do it. Any help would be appreciated. -
What is the right way to create projects in Django ? (Folders)
Sorry for the weird question. I am creating a MMORPG Text browser game, and I feel like my project is wrong. I am creating a new app for everything I need (Account app, Menu app, Fight app). And when I browse Github, people only have like 5/6 folders while I'm at 20 currently. Where should I put my classes/forms/things normally ? Like, where should I have my fight system placed ? Thanks ! (Sorry for bad english) -
UpdateView in Django
I can successfully add a comment with the below code: views.py: class CommentCreate(CreateView): model = Comment fields = ['body'] def form_valid(self, form): film = Film.objects.get(pk=self.kwargs['film_id']) form.instance.user = self.request.user form.instance.film = film return super(CommentCreate, self).form_valid(form) class CommentUpdate(UpdateView): model = Comment fields = ['body'] def form_valid(self, form): film = Film.objects.get(pk=self.kwargs['film_id']) comment = Film.objects.get(pk=self.kwargs['comment_id']) form.instance.user = self.request.user form.instance.film = film form.instance.comment = comment return super(CommentUpdate, self).form_valid(form) urls.py: path('<int:film_id>/comment/', views.CommentCreate.as_view(), name='add_comment'), path('<int:film_id>/comment/', views.CommentUpdate.as_view(), name='update_comment'), models.py: class Comment(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) film = models.ForeignKey(Film, on_delete=models.CASCADE) body = models.CharField(max_length=200) def get_absolute_url(self): return reverse('films:detail', kwargs={'pk': self.film.pk}) links in html file: <a href="{% url 'films:add_comment' film_id=film.id %}">Leave a comment</a> <a href="{% url 'films:update_comment' film_id=film.id %}">Update</a> As you can see, I have tried to add update functionality but at the moment when I click the update link and save a comment it creates a new instance rather than amending an existing one. -
ForeignKey admin link name
In my Django model, I have class PhotoComment(AbstractComment): photo = models.ForeignKey(Photo, on_delete=models.PROTECT, related_name='comment') I called it like this to distinguish from a PersonComment class defined in the same project. The URL in the admin page now looks like this: https://xxx.yyy/admin/people/personcomment/ I would love to have https://xxx.yyy/admin/people/comment/ instead. Is it possible? -
indexError at /xadmin/users/userprofile/1/update/
it's a error about xadmin. I can log in xadmin, but when I want to edit user profile, the error as below: this is what show me after checking users in xadmin. and enter image description here -
create Confusion matrix from prediction audio in python django
I'm working on a task to predict the sound, but I get the problem, I can not show the confusion matrix i want to show Confusion matrix from my prediction variable, How to do it? is there anyone who can help me? def creatematrix(request): if request.method == 'POST': myfile = request.FILES['sound'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) # load json and create model json_file = open('TrainedModels/model_CNN.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # load weights into new model loaded_model.load_weights("TrainedModels/model_CNN.h5") print("Model restored from disk") sound_file_paths = filename # "22347-3-3-0.wav" parent_dir = 'learning/static/media/' sound_names = ["air conditioner","car horn","children playing","dog bark","drilling","engine idling","gun shot","jackhammer","siren","street music"] predict_file = parent_dir + sound_file_paths a = read(predict_file) output = np.array(a[1],dtype=float) predict_x = extract_feature_array(predict_file) test_x_cnn = predict_x.reshape(predict_x.shape[0], 20, 41, 1).astype('float32') loaded_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # generate prediction, passing in just a single row of features predictions = loaded_model.predict(test_x_cnn) # get the indices of the top 2 predictions, invert into descending order ind = np.argpartition(predictions[0], -2)[-5:] ind[np.argsort(predictions[0][ind])] ind = ind[::-1] c = sound_names[ind[0]], "(",round(predictions[0,ind[0]]),")" j = sound_names[ind[1]], " (",round(predictions[0,ind[1]]),")" jx = sound_names[ind[2]], " (",round(predictions[0,ind[2]]),")" jv = sound_names[ind[3]], " (",round(predictions[0,ind[3]]),")" jvt = sound_names[ind[4]], " (",round(predictions[0,ind[4]]),")" I really need help -
Django - What is settings.py for?
I was creating my Django application, so my project structure is just like the bottom example: I would like to know what is the settings.py for: -
Applying for advice for an important choice
I want to write a program that in terms of workload, it is similar to a telegram،That means the number of requests must be processed And answer the requests. Now, my question is which programming language is more suitable for the back end? for example Node.js Or django Or etc. thank you -
Trying to update user information from 2 forms in Django
So I have a student model which inherits from AbstractUser. I used 2 forms in one view for registration since I needed email, name and surname to be in my student database (as well as other fields). Now I'm trying to make an update profile view, with 2 forms that I made especially for updating the info. But I think I'm getting it wrong.. might need a little help here. I need the student to be able to update his email (which is from User model) and his photo, phone, name and surname (which are in Student model). <form method="POST" action="{% url 'profile_edit' %}" class="" > {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> def profile_edit(request): user = request.user form1 = UserEditForm(request.POST or None, initial={'email': user.email, }) form2 = StudentEditForm(request.POST or None, initial={'name': user.student.name, 'surname': user.student.surname, 'phone': user.student.phone, 'photo': user.student.photo}) if request.method == 'POST': if form1.is_valid() and form2.is_valid(): user.email = request.POST['name'] user.student.name = request.POST['name'] user.student.surname = request.POST['surname'] user.student.phone = request.POST['phone'] user.student.photo = request.POST['photo'] user.save() return render(request, 'index.html') context = { "form1": form1, "form2": form2 } return render(request, "registration/profile_edit.html", context) class UserForm(forms.ModelForm): email = forms.EmailField(required=True) password = forms.CharField(label='Password', max_length=32, required=True, widget=forms.PasswordInput) confirm_password = forms.CharField(label='Confirm', max_length=32, required=True, widget=forms.PasswordInput, help_text="Passwords must match!") … -
Error: Reverse for 'detail_page' not found. 'detail_page' is not a valid view function or pattern name
I trying to create own page for each post(detail), but when I am launching page with all post, I have this error: Reverse for 'detail_page' not found. 'detail_page' is not a valid view function or pattern name. When I delete <a...> in <h3 class="name-detail"><a href="{% url 'detail_page' pk=detail.pk %}">{{ detail.detail }} для {{ detail.car }}</a></h3> all is working views.py: ... def porshe_cayenne(request): page = request.GET.get('page', 1) paginator = Paginator(Detail.objects.filter(car="Porsche Cayenne")[::-1], 20) images = DetailImage.objects.all() try: details = paginator.page(page) except PageNotAnInteger: details = paginator.page(1) except EmptyPage: details = paginator.page(paginator.num_pages) return render(request, 'shop/list.html', {'details': details, 'images':images}) def detail_page(request, pk): detail = get_object_or_404(Detail, pk=pk) images = DetailImage.objects.filter(detail=detail) return render(request, 'shop/detail.html', {'detail': detail, 'images':images}) list.html: ... <div class="infinite-container"> {% for detail in details %} <div class="background_detail"> <div class="detail"> <h3 class="name-detail"><a href="{% url 'detail_page' pk=detail.pk %}">{{ detail.detail }} для {{ detail.car }}</a></h3> #HERE IS PROBLEM <br> <h6>{{ detail.description }} <em class="fa fa-arrow-down"></em> Всі контакти внизу <em class="fa fa-arrow-down"></em></h6> <br> {% for img in images %} {% if img.detail == detail %} <img class="detail-foto" src="{{ img.image.url }}" /> {% endif %} {% endfor %} <br> <div class="price"> Ціна: {{ detail.price }} </div> </div> </div> {% endfor %} </div> ... urls.py: url(r'^porshe_cayenne/$', views.porshe_cayenne, name='porshe_cayenne'), url(r'^detail/(?P<pk>\d+)/$', views.detail_page, name='detail_page_plz'), …