Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
implementing following and followers doesn't work properly
I have a user model that has a slug field for lookup. I am trying to implement a user following and followers as its own model in my rest API, so I can save more info about the following and followers, and since I am trying to build a big project, I gathered it was a better practice. The problem is that the code doesn't work and the user when he tries to follow does not follow the user. I want to be able to follow the user if the user, and the user not able to follow himself and to follow once models.py class UserFollowing(models.Model): following = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="follows", null=False, blank=False, on_delete=models.DO_NOTHING) followers = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="followed_by", null=False, blank=False, on_delete=models.DO_NOTHING) followed_on = models.DateTimeField(auto_now_add=True) serializers.py class UserFollowingSerializer(serializers.ModelSerializer): following_count = serializers.SerializerMethodField(read_only=True) followers_count = serializers.SerializerMethodField(read_only=True) user_is_following = serializers.SerializerMethodField(read_only=True) followed_on = serializers.SerializerMethodField(read_only=True) class Meta: model = UserFollowing fields = "__all__" def get_followed_on(self, instance): return instance.followed_on.strftime("%d %B, %Y") def get_following_count(self, instance): return instance.following.count() def get_followers_count(self, instance): return instance.followers.count() def get_user_is_following(self, instance): request = self.context.get("request") return instance.following.filter(slug=request.user.slug).exists() views.py class UserFollowAPIView(APIView): serializer_class = UserFollowingSerializer permission_classes = [IsAuthenticated] def delete(self, request, pk): user = get_user_model().objects.get("slug") UserFollowing.objects.delete(user_id=user, following_user_id=user) def post(self, request, pk): user = get_user_model().objects.get("slug") UserFollowing.objects.create(user_id=user, following_user_id=user) urls.py path("<slug:slug>/follow/", … -
How to pre select value in a django forms.Select field
I am new to django. I am creating a simple CRUD application using django 2.2, I have a simple addstudent.html page where i can add data in some fields including a dropdown where I can select the class of student and database is updated. Below is my code: forms.py class StudentForm(forms.ModelForm): class_list= [ ('Class IIX', 'Class IIX'), ('Class IX', 'Class IX'), ('Class X', 'Class X'), ('Class XI', 'Class XI'), ('Class XII', 'Class XII') ] student_class= forms.CharField(label='Class', widget=forms.Select(choices=class_list,attrs={'style': 'width:175px'})) class Meta: model=Student fields='__all__' models.py class Student(models.Model): student_id=models.CharField(max_length=20) student_name=models.CharField(max_length=100) student_email=models.EmailField() student_contact=models.CharField(max_length=100) student_class=models.CharField(max_length=100) class Meta: db_table='student' snippet of addstudent.html template where dropdown is shown correctly <div class="form-group row"> <label for="sname" class="col-sm-4 col-form-label">Student Class:</label> <div class="col-sm-8"> {{form.student_class}} </div> </div> Problem: I am not able to figure out how to preselect the dropdown when I edit a student, I get the value as 'Class X' from the database but how do i use this database value to select correct option in dropdown? Please Note: This project is for school kids and I can't use JQUERY/JAVASCRIPT here. -
best languge to design a social network [closed]
what's the best programming language should I use to design social network like facebook Instagram twitter... ruby on rail or python with Django or JavaScript or php or what so please give me the best I should use also I just want to say that I like Django the most but I want my website be the best -
'OneHotEncoder' object has no attribute 'categories_'
I'm trying to run a python3 project of predicting the outcome of cricket matches using Random Forest Algo for the training of the machine. I'm currently getting this error **Traceback: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/kyvinay/cfd_apriori/4th_umpire/web/fourth_umpire/views.py" in prematch 107. probab = pre_match_predict("2016",team1,team2,venue) File "/Users/kyvinay/cfd_apriori/4th_umpire/web/fourth_umpire/predictions/pred.py" in pre_match_predict 17. X_test = enc.transform(X_test).toarray() File "/Users/kyvinay/cfd_apriori/4th_umpire/web/scikit-learn/sklearn/preprocessing/_encoders.py" in transform 390. X_int, X_mask = self._transform(X, handle_unknown=self.handle_unknown) File "/Users/kyvinay/cfd_apriori/4th_umpire/web/scikit-learn/sklearn/preprocessing/_encoders.py" in _transform 107. if n_features != len(self.categories_): Exception Type: AttributeError at /pre_pred/ Exception Value: 'OneHotEncoder' object has no attribute 'categories_'** The corresponding code is import numpy as np from scipy import sparse from ..base import BaseEstimator, TransformerMixin from ..utils import check_array from ..utils.fixes import _argmax from ..utils.validation import check_is_fitted from ._label import _encode, _encode_check_unknown __all__ = [ 'OneHotEncoder', 'OrdinalEncoder' ] class _BaseEncoder(TransformerMixin, BaseEstimator): """ Base class for encoders that includes the code to categorize and transform the input features. """ def _check_X(self, X): """ Perform custom check_array: - convert list of strings to object dtype - check for missing values for object dtype data (check_array does not do that) - return list of features (arrays): … -
Is there a way to use the python modele "webbrowser" with Heroku?
I am working on deploying a django app to heroku and I am having trouble with the webbrowser module. The function initially creates a pdf from html using pdfkit (this part works fine). Afterwards, I use '''webbrowser.open_new_tab''' to render the pdf in a new tab. This works perfectly locally, but not when I deploy to Heroku :( I checked the Heroku log, and it indicates that the pdf is being properly compiled and that the webbrowser command is successfully called, but alas, a new tab is not opened... Are there any suggestions on how best to tackle this issue? Perhaps I am missing an important environment variable that allows me to open new pages on the user's browser? Thank you, -- Carter -
Django - Check If form field contains a whitespace
In my project, I have a forms.py that contains the following field: fullName = forms.CharField(min_length=3, max_length=255, widget=forms.TextInput(attrs={'placeholder': 'Full Name', 'class': 'fullNameField'})) In my views.py, I check if the field does not contains a whitespace: if not ' ' in form.cleaned_data.get('fullName'): context ['fullNameError'] = "Please enter a valid full name" When I submit the form and add a space, the context ['fullNameError'] is called when it shouldn't be. Does anybody know why? Thank you. -
How do I use the AdagradDAOptimizer Optimizer by using tf.compat.v1.train?
I tried using the AdagradDAOptimizer for my model but I got an error while I did the same thing to the ProximalAdaGrad Optimizer class. I did not get an error for that one so I am confused as to what I am doing wrong. My code: import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt import numpy as np import time start_time = time.time() data = tf.keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = data.load_data() class_names = ['T-shirt', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle Boot'] train_images = train_images/255.0 test_images = test_images/255.0 optimizer1 = tf.compat.v1.train.AdagradDAOptimizer(0.001) model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(100, activation="softsign"), keras.layers.Dense(10, activation="softmax") ]) model.compile(optimizer=optimizer1, loss="sparse_categorical_crossentropy", metrics=["accuracy"]) model.fit(train_images, train_labels, epochs=5) test_loss, test_acc1 = model.evaluate(test_images, test_labels) print("Test acc is:", test_acc1) print("--- %s seconds ---" % (time.time() - start_time)) Error Message: ERROR:root:Internal Python error in the inspect module. Below is the traceback from this internal error. Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-bdc36910ec8c>", line 11, in <module> data = tf.keras.datasets.fashion_mnist File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/util/module_wrapper.py", line 193, in __getattr__ attr = getattr(self._tfmw_wrapped_module, name) AttributeError: module 'tensorflow' has no attribute 'keras' During handling of the above exception, another exception occurred: Traceback (most recent … -
Django how to get id from the database and show in the html
this is my views.py: def gradescales(request): grade = list(gradeScalesSetting.objects.all()) # < DB hit once gradeScalesSettings = gradeScalesSetting.objects.all() rounding = [] configuration = [] for i in grade: if i.Rounding not in rounding: rounding.append(i.Rounding) if i.Configuration not in configuration: configuration.append(i.Configuration) return render(request, 'Homepage/gradescale.html', {"rounding": rounding, "configuration": configuration,"gradeScalesSetting":gradeScalesSettings}) i use this code because i dont want to use distinct(), but im getting trouble in getting their id. this my template <select name="gradescale" id="gradescale" onchange="summary(this.value)" required="required" > {% for r in configuration %} <option value="{{r}}">{{r}}</option> {% endfor %} </select> this is the result: i just want that in my the value is the id of what list i selected this is my database -
Django 2.2: How to redirect a user from a view to a specific page with a context?
Our website is listing properties ads. When a user publish an ad, I would like to redirect him to a "thank you" page. But inside this thank you page I would like to put a button with the link to the detailed view of the created ad. I don't want to use "messages" framework because I need a dedicated page for tracking purpose. How can I send the context (in this case the absolute url of the created object) to the "thank you" page? It doesn't matter if the solution requires the use of a class based view or a function view. Many thanks in advance ! -
Use Django with Python3?
I've been following the official Django tutorial, but I cannot get it to work with Python 3. I used: django-admin startproject mysite in order to create a site, but it runs on Python2... Since I know all the syntax for Python3 I would really like to find a way to code in Python3 Thank you very much ! -
Adding Django MultipleChoiceField one after the other using Javascript
I am working on a Django views based on the following form: class MyForm(forms.Form): def __init__(self, data, examen, *args, **kwargs): super(MyForm, self).__init__(data, *args, **kwargs) self.fields['q1'] = forms.MultipleChoiceField( label=mark_safe("Label question 1"), required=True, widget=forms.CheckboxSelectMultiple, choices=(('1', 'answer 1'), ('2', 'answer 2'), ('3', 'answer 3')) ) self.fields['q2'] = forms.MultipleChoiceField( label=mark_safe("Label question 2"), required=True, widget=forms.CheckboxSelectMultiple, choices=(('1', 'answer 4'), ('2', 'answer 5'), ('3', 'answer 6')) ) ... #TODO : add questions q3 to q9 self.fields['q10'] = forms.MultipleChoiceField( label=mark_safe("Label question 10"), required=True, widget=forms.CheckboxSelectMultiple, choices=(('1', 'answer 28'), ('2', 'answer 29'), ('3', 'answer 30')) ) Il would like to display on a single view self.fields['q1'] with a [submit] button. The idea is for the user to select the answer he considers as correct and the hit the [submit] button. Following that self.fields['q1'] will turn into read-only and self.fields['q2'] will display just below with again a [submit] button... and son on until self.fields['q10']. I do believe that the only way to achieve that is to use Javascript (and even JQuery or any other library). The problem is that I'm not very familiar with Javascript and would gladly appreciate hints on how to tackle that issue. Thank you for what you can do! PS: I'm happy to change my Django design … -
how to set django 2.1 database for production for heroku postgresql?
Why I am asking this question? Ans:My db rows were deleted and came back to original position after creating another user and added some rows to table by him. I came to know that heroku refreshes postgre sql database and added django_heroku. Here are the steps I followed: created an app. hosted on heroku. added heroku_django package in settings as it will cover dj_database_url for django 2.1 python manage.py makemigrations (in local). git push github. git push heroku. heroku run python manage.py migrate. -
Django Allow User to Add a New Item to a List
I have a todo website that would allow users to create a list, and have them create events and specify which list to put it in. Right now, I have a Reminder model that contains a list with a General option: class Reminder(models.Model): remind_types = [('Regular', 'Regular'), ('Long Term', 'Long Term')] remind_lists = [('General','General')] title = models.CharField(max_length=100) description = models.TextField() remind_time = models.DateTimeField(blank=True) parent_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) type_of_remind = models.CharField(max_length=12, choices=remind_types, default='Regular') remind_list = models.CharField(max_length=20, choices=remind_lists, default='General') complete = models.BooleanField(default=False) I was thinking of creating a form that would have the user input a title, and add the title to remind_list. I would have a menu that allows the user to view reminders based on a specific list, and have reminders passed through like this: from .models import remind_lists @login_required(login_url='/login') def home(request): user = get_object_or_404(User, username=request.user.username) context = { 'events': ToDoItem.objects.filter(parent_user=user), 'reminders': Reminder.objects.filter(parent_user=user, type_of_remind='Regular'), 'long_term_reminders': Reminder.objects.filter(parent_user=user, type_of_remind='Long Term'), } for list_menu_name in remind_lists: context[list_menu_name] = Reminder.objects.filter(parent_user=user, type_of_remind='Long Term', remind_list=list_menu_name) return render(request, 'main/home.html', context) But I'm kind of lost on how to do this. I was thinking of creating a model with just a CharField, but I don't know how to add just the name into the list of remind_lists. … -
SMTPSenderRefused at /password-reset/ Authentication Required
I am adding password reset feature in my Django app, here is the code in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD') if I replace last two lines with: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemail@here.com' # this EMAIL_HOST_PASSWORD = 'passwordOfEmailHere' # this this one works fine, this is the error I get when I use environment variables: Environment: Request Method: POST Request URL: http://localhost:8000/password-reset/ Django Version: 2.2.7 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blogApp', 'users.apps.UsersConfig', 'crispy_forms'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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'] Traceback: File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\utils\decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\contrib\auth\views.py" in dispatch 220. return super().dispatch(*args, **kwargs) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\views\generic\base.py" in dispatch 97. return handler(request, *args, **kwargs) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\views\generic\edit.py" in post 142. return self.form_valid(form) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\contrib\auth\views.py" in form_valid 233. form.save(**opts) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\contrib\auth\forms.py" in save … -
Django router withe multiple tables
I settled a django router to link my datatables to the rest api. To do so, I have my models given by: class Lab(models.Model): nom = models.CharField(max_length=50) ville = models.CharField(max_length=50) and its serialization method like this: class LabSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Lab fields = ('url', 'nom', 'ville', 'pk') To access this table, I created a ViewSet in a views file like this : class LabViewSet(viewsets.ModelViewSet): queryset = Lab.objects.all() serializer_class = LabSerializer And in the urls file, I register my view like this : router.register('labs', LabViewSet) This is working, but I'd like to add a new table, Member, linked to the Lab table : class Member(models.Model): email = models.EmailField() nom = models.CharField(max_length=50) prenom = models.CharField(max_length=50) lab = models.ForeignKey(Lab, on_delete=models.CASCADE) How can I access the data throuht a single request joining both tables ? -
How do i update a date field of a user when the admin form is saved?
I have built a django application that is used to store the notes of a meeting. The studio note object is called StudioMeetingNote and it has 2 foreign key fields with the CustomUser model, namely secretary and chairman. Each CustomUser instance has 2 date fields namely last_date_chairman and last_date_secretary. When a user is assigned chairman in the StudioMeetingNote form I want the last_date_chairman field of this user to get the same value as the date assigned to the field meeting_start_date field that belongs to the StudioMeetingNote itself. The same goes for last_date_secretary. I decided to use the def save_model method for this. It resides in the StudioMeetingNoteAdmin class that represents the StudioMeetingNote class in the admin section. The entire implementation looks like this: class StudioMeetingNoteAdmin(admin.ModelAdmin): fields = (('meeting_start_time', 'meeting_end_time'), ('chairman', 'secretary'), 'absent_persons',) # fieldsets = [ # ('Tijden', {'fields': ['meeting_start_time', 'meeting_end_time']}), # ('Wie is de voorzitter/notulist', {'fields': [('chairman', 'secretary')]}), # ('Opkomst', {'fields': [('attending_persons', 'absent_persons')]}), # ] inlines = [OpeningAndParticularitiesInline, ActionListPointInline, RemarksPriorMeetingInline, IssuesToAddressInline, OurNextMoveInline, QuestionRoundInline] list_filter = ['meeting_start_time'] search_fields = ['meeting_start_time'] list_display = ('meeting_start_time', 'chairman', 'secretary') save_as = True def save_model(self, request, obj, form, change): save_user = False if 'chairman' in form.changed_data: obj.chairman = form.cleaned_data['chairman'] obj.chairman.last_date_chairman = form.cleaned_data.get('meeting_start_date') save_user = True … -
Dynamic choices for django forms
I'm building a booking form, and want to allow users to pick a date of booking from available dates in the next 60 days. I get the next 60 days by: base = datetime.date.today() date_list = [base + datetime.timedelta(days=x) for x in range(60)] Then I subtract already booked dates which are stored in the db: bookings = list(Booking.objects.all()) primarykeys = [] unav = [] for b in bookings: primarykeys.append(b.pk) for p in primarykeys: unav.append(Booking.objects.get(pk=p).booking_date) for date in unav: if date in date_list: date_list.remove(date) Then I change the result into tuple for the forms(not sure if this is right?):` date_list = tuple(date_list) Then I pass it into the form field as such: booking_date = forms.ChoiceField(choices=date_list, required=True) This gives me an error of cannot unpack non-iterable datetime.date object And now am I stumped...how can I do this? I have a feeling i'm on the complete wrong path. Thanks in advance -
Reverse for 'news_tag' with no arguments not found. 1 pattern(s) tried: ['news/tags/(?P<tag_name>[^/]+)/$']
my urls . I have to load the tags in new url but i ended up in this error from django.urls import path from news import views urlpatterns =[ path('create/',views.CreateNewsView.as_view(),name='create_news'), path('<str:category>/',views.NewsCategoryView.as_view(),name='category_news'), path('<str:category>/<int:pk>/<str:slug>/',views.NewsDetailView.as_view(),name='detail_news'), path('tags/<str:tag_name>/',views.view_tag ,name='news_tag'), path('<str:category>/<int:pk>/<str:slug>/comment/',views.create_comment,name='create_comment'), path('<str:category>/<int:pk>/<str:slug>/delete/',views.NewsDeleteView.as_view(),name='delete_news'), path('<str:category>/<int:pk>/<str:slug>/update/',views.NewsUpdateView.as_view(),name='update_news'), ] my views: this view is to load to my news from the tags def view_tag(request,tag_name): tag= Tag.objects.get(pk=tag_name) news= tag.page_set.all() return render(request,'news/tags.html',{"tag_name":tag_name,'news':news}) my models:I have created this models without Taggable Manager() to create tags class Tag(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class News(models.Model): CATEGORY=(("0","Politics"),("1","Sports"),("2","Health"),("3","Business"),("4","International"),("5","Finance")) title=models.CharField(max_length=250) story= models.TextField() count= models.IntegerField(default=0) tags = models.ManyToManyField(Tag) video_url = models.URLField(max_length=270, null=True) #makemigrations garna baki xa category= models.CharField(choices=CATEGORY, max_length=2) slug=models.SlugField(max_length=270,blank=True,null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) cover_image=models.ImageField(upload_to="uploads") author= models.ForeignKey(User, on_delete=models.SET_NULL,null=True) video_image = models.ImageField(null=True) -
How to run on heroku wss?
Everything works on the local server, but no messages are sent to Heroku. I run heroku run bash and python manage.py run_chat_server Server starts without errors. My settings.py CHAT_WS_SERVER_HOST = '0.0.0.0' CHAT_WS_SERVER_PORT = 5002 CHAT_WS_SERVER_PROTOCOL = 'wss' I am using https protocol. In the browser console WebSocket 'connection to wss://0.0.0.0:5002/dfs5k7c05k20w236xxhvelsrfm2adpgo/username' failed: Error in connection establishment: net::ERR_SSL_PROTOCOL_ERROR It may be necessary to start the server with cert.pem? How to do it on heroku? It seems he creates them himself... -
Getting error : Got AttributeError when attempting to get a value for field `profile` on serializer `UserSerializer`
i am new here in django python so pardon me for my silly mistakes, When i try to run api /api/v1/users/ getting error : Got AttributeError when attempting to get a value for fieldprofileon serializer UserSerializer. , here i have placed my whole code, i know i did some little mistake, but i didn't find it yet, can anyone please look my code and help me to resolve this issue ? any help will be really appreciated, thanks in advance serializers.py from rest_framework import serializers from .models import Songs from .models import UserProfile from django.contrib.auth.models import User class SongsSerializer(serializers.ModelSerializer): class Meta: model = Songs fields = ("title", "artist") class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('title', 'dob', 'address', 'country', 'city', 'zip', 'photo') class UserSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer(required=True) class Meta: model = User fields = ('url', 'email', 'first_name', 'last_name', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() UserProfile.objects.create(user=user, **profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.email = validated_data.get('email', instance.email) instance.save() profile.title = profile_data.get('title', profile.title) profile.dob = profile_data.get('dob', profile.dob) profile.address = profile_data.get('address', profile.address) profile.country = profile_data.get('country', profile.country) profile.city = profile_data.get('city', profile.city) … -
How to display object names on a Django Template?
Just Started learning Dango and i got some problems on understanding how to display the name of a object and not it's ID, here I have two tables, one of books and other of i'ts category and in the books table i have a ForeignKey pointing to the category. You can see my codes: My models.py #class for making the book table on the db class Books(models.Model): ... category_cod_category = models.ForeignKey( 'Editora', on_delete = models.CASCADE ) ... class Meta: db_table = 'Books' # class for the category tables class Category(models.Model): name_category = models.CharField( max_length = 45 ) class Meta: db_table = 'category' My forms.py class BooksForm(forms.ModelForm): class Meta: model = Books fields = [ ... ,'category_cod_category',] The view.py that i'm struggling to understand def book(request): if request.method == 'POST': form = BooksForm(request.POST or None) print(form.errors) if form.is_valid(): try: form.save() return redirect('/show') except: pass else: print("form not valid") else: form = BooksForm() return render(request, 'index.html', {'form':form}) And the Template index.html that should show the category name but it only returns the ID <form method="POST" class="post-form" action="/livro"> {% csrf_token %} <!-- not pasting working forms --> <div class="form-group row"> <label class="col-sm-2 col-form-label">Books's Category:</label> <div class="col-sm-4"> {{ form.category_cod_category }} </div> </div> <div class="form-group … -
is there any difference between while using url and path in django web development
is there any difference between while using url and path in django web development from django.conf.urls import url url(r'^about/', views.home, name='blog.about') and from djano.urls import path path('about/', views.home, name='blog.about') ? -
Is it possitble to execute a python(django) function immediately on vs code?
I want to execute a python function in vs code directly when I set a breakpoint when debugging. Just like Immediate window on Visual Studio -
Django REST Framework Multiple OR'd Custom Permissions' Message Not Shown
I'm trying to write a RetrieveUpdateDestroyAPIView where the permission classes are set as follows: permission_classes = (IsUserCat | CanDogsRetrieveObject,) permissions.py: class IsUserCat(IsAuthenticated): def has_object_permission(self, request, view, obj): return super().has_object_permission(request, view, obj) and request.user.species == SPECIES_CAT def has_permission(self, request, view): return super().has_permission(request, view) and request.user.species == SPECIES_CAT class IsUserDog(IsAuthenticated): def has_object_permission(self, request, view, obj): return super().has_object_permission(request, view, obj) and request.user.species == SPECIES_DOG def has_permission(self, request, view): return super().has_permission(request, view) and request.user.species == SPECIES_DOG class CanDogsRetrieveObject(IsUserDog): message = "Some custom message." def has_permission(self, request, view): return super().has_permission(request, view) def has_object_permission(self, request, view, obj): return super().has_object_permission(request, view, obj) and obj.expiry_date >= timezone.now().date() So basically, the first permission class checks if the user is a cat, if so, the user can retrieve the object; if not, the second permission class checks if the user is a dog and if the object in question is expired. If it's expired, a custom error message must be displayed, but it doesn't. If I don't OR them, and instead just use CanDogsRetrieveObject then the issue gets resolved. Why is this the case? -
How to filter and count query set in django template?
I have this model: class Application(Model): is_paid = BooleanField(default=False) and this view: def my_view(request): template_name = 'my_template.html' context = {} applications = Application.objects.all() context.update({'applications': applications,}) return render(request, template_name, context) and have this template: <body> All: {{ applications.count }} <!-- Paid: I want to show the count of paid applications in here. --> <!-- UnPaid: I want to show the count of unpaid applications in here. --> </body> What I want to do is that filter the applications based on the is_paid field and count them. I do not want to do it in the view. I want to do it in the template to avoid making view complicated and big. How should I do it?