Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I don't want drf ValidationError response to be textual. How to do that?
I'm using django rest framework. How to change the drf ValidationError detail not to be textual. for this: raise ValidationError(detail={"some_thing": True} response: { "something": "True" } expected response: { "something": true } -
How to generate one time password when creating user and send the same to users mail id in Django?
I am trying to send a random one-time password to the user when I create a new user and make him change the password when the user login for the first time. -
Creating models objects to load to load to database using text file in Django
I have a file full of english words and I am trying to add them to my postgres database via python shell. I am currently getting this error for the first word: ValueError: invalid literal for int() with base 10: 'AA' I think it is because a primary key isn't being considered because after migrating my models to postgres I see that the tables looks like this Table "public.boggle_word" Column | Type | Collation | Nullable | Default --------+-------------------------+-----------+----------+----------------------------------------- id | integer | | not null | nextval('boggle_word_id_seq'::regclass) word | character varying(1024) | | not null | and Python is complaining about int() models.py class Word(models.Model): word = models.CharField(max_length=1024) code snippet: from boggle.models import Word with open('files/dictionary.txt') as wfile: line = wfile.readline().strip() word = Word(word) word.save() -
Why does LDAPBackend.authenticate() store user info in custom user model in Django
I'm new to LDAP authentication and going through some of the StackOverflow questions and django-auth-ldap documentation I was able to implement LDAP authentication in my django project. I have a custom user model to store the user information. But my question here is that when we do authenticate using user_id and password why does authenticate store the user info in the custom user model. It also stores the hashed password. I have used LDAPBackend as my authentication backend in settings.py file like this AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend' ] and for example when we perform the below operation auth = LDAPBackend() user = auth.authenticate(request, username=user_id, password=user_password) the user object is stored in the custom user model. My requirement is here not to store any user information when authenticate happens and not to store any password(be it hashed password). There are some pre-checks I need to do before storing it into user info to the custom user model. But LDAPBackend.authenticate() stores user info as it authenticates. Can anyone please help me on this and clarify what's going on here. Thanks -
How to navigate to sharefolder from view in Django?
I am trying to set button url, so it will open a folder. But there is still some problem. If I try to open URL on my own, or just paste it into file explorer, it works fine. Can someone please help me? I tried to set link on text, this is not working and nothing really happens. <a href="\\servername\Users\tom\cd\">Documentation</a> I also tried to set it on button. Now the button is clickable but will navigate to url in browser and will not open a folder. <button type="button" onclick="window.location.href = '\\server\Users\tom\cd\';">Navigate to folder</button> -
Django - upload just picture in model with a POST request
I would like to upload a profile picture with ajax. But even if I don´t send the image with ajax, it doesn´t work. I have the following code in my website: <form action="{% url 'update_profile_pic' %}" method="post"> {% csrf_token %} <input name="profilePic" type="file" accept="image/*"/> </form> The profilePic should be saved in the model: class UserProfile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, ) profilePic = ProcessedImageField( upload_to=generate_random_filename, processors=[ResizeToFill(150, 150)], format='JPEG', options={'quality': 60}, ) ... The url.py has the correct entry: ... path('update_profile_pic/', views.UpdateProfilePic.as_view(), name='update_profile_pic'), ... The form is like this: class ProfilePicForm(forms.ModelForm): class Meta: model = UserProfile fields = ('profilePic',) And the view should also be correct: class UpdateProfilePic(View): def post(self, request): form = ProfilePicForm(self.request.POST, self.request.FILES) if form.is_valid(): request.user.userprofile.profilePic = form.cleaned_data['profilePic'] request.user.userprofile.save() return JsonResponse({ image_url : request.user.userprofile.profilePic.url }) else: raise Http404(form.errors) But I always get the error "profilePic This field is required.", when I upload a picture. This error comes from the raise Http404(form.errors), so the form is not valid. When I look at the headers in the network tab in google chrome, it shows me this: csrfmiddlewaretoken: sbyaJ8J7COSdC0OUYr4p8ToaarjFrIniDKLT3Lr36PVeTUlc9MEafr77exYVvkXL profilePic: fr.cc38d01b0b77.gif What do I do wrong here? -
how to edit form which have single or multiple MultichoiceFields
I have a form with MultipleChoiceField. I am able to save the data correctly. Now, if a user wants to edit that form he/she should see already selected items in the dropdown along with remaining all the other option. I want this as a function-based view. eg. I have 5 products in the dropdown and at the time of form submission, I selected products 1 and 2. Now, when I click on edit I should be able to see products 1 and 2 selected along with the other 3 products as unselected.Just help me with the edit view of this form models.py class Product(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class DemoForm(models.Model): name = models.CharField(max_length=100) area = models.CharField(max_length=50) opted_products = models.ManyToManyField(Product,related_name='selected_products') def __str__(self): return self.name -
Unable to import 'django.http'pylint(import-error)
I am getting this problem in visual studio code 2019 i hope anyone can help to solve this problem this problem occuring with pip new version and django 2.2+ version and python latest 3.7 version for information please help to solve this problem Need Help -
Django. Revert previous page
I have an image_delete django-controller. I use it on several pages. I need that after deleting the image, the controller returns me to the previous page. but I get an error. what is the problem? How to fix it? views.py class ImageDelete(DeleteView): model = Picture template_name = 'adminapp/pet/pet_image_delete.html' @method_decorator(user_passes_test(lambda x: x.is_superuser)) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_success_url(self): return HttpResponseRedirect(request.META.get('HTTP_REFERER')) urls.py path('delete/image/<int:pk>/', adminapp.ImageDelete.as_view(model=Picture), name='image_delete') Error -
Django Viewflow: Quick Start says to include formpack. What is a formpack?
I'm trying to use django viewflow to style some forms to keep a page consistently styled within an django app using materialize. In the viewflow documents, it recommends to include formpack javascript and styles into your database. What is a formpack and where could I find one for Materialize? -
How can i serialize Django View object?
I want to serialize my context data, but i get this error: TypeError: < tests.views.ExamView object at 0x7f8e18873668 > is not JSON serializable Here is my code: from django.template.loader import render_to_string context = self.get_context_data() html = render_to_string('difficult_test.html', context) if self.request.is_ajax(): return http.JsonResponse({"html":html, 'context':context}) return response -
Pycharm underlines absolute import, but it works fine
I have path server->api(folder), manage.py. Pycharm underlines my absolute import from api.views import create_user but it works! If i type like from server.api.views import create_user pycharm does not underline, but it doesn't work -
How to use django SESSION_COOKIE_AGE dynamically
In my django application I want to make this session cookie age dynamic.For example the default session is for two weeks in django .If i wanted to change into 1 weeks i can change by changing the setting in django but for this i need to go in the project settings.py file. Is there any solutions so that later after some time if i needed to change my SESSION_COOKIE_AGE i can change this with the admin panel butnot going in the projects settings.py file settings.py SESSION_COOKIE_AGE = 1209600 # I want to make this dynamic ANY HELP WOULD BE GREAT -
Django website for Subscriptions with paypal integration
Anyone help me on django with website for Subscription of two plans and integrate paypal payment gateway Thanks In advance -
(Django) Reverse dynamic urls with multiple arguments using Django Views
I am trying to pass two arguments to make a dynamic URL for each post of a blog app I'm working on. I get it to work if I pass the id, but don't know what's the syntax when using +1 arguments (nor if I'm doing things right). I want to make urls be 'post/<int:pk>/<slug:slug>/' but can only make it work with the id: 'post/<int:pk>/ Here's how I have it now: URLS.PY urlpatterns = [ ... path('post/<int:pk>/<slug:slug>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/<slug:slug>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/<slug:slug>/delete/', PostDeleteView.as_view(), name='post-delete'), ... ] VIEWS.PY class PostDetailView(DetailView): model = Post I am calling this in the template: <ul class="secondary-menu menu-list"> <li class="menu-item"><a href="{% url 'post-update' object.slug %}">Edit Post</a></li> <li class="red-button"><a href="{% url 'post-delete' object.slug %}">Delete</a></li> </ul> And have this function to retrieve the path to any specific instance in MODELS.py def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk, 'slug':slug}) I get the following error during template rendering Reverse for 'post-detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)/$'] -
unable to apply search on multiple fields Django
def search(request): if request.method == 'POST': srch = request.POST['title'] if srch: match = Post.objects.filter(title__icontains=srch,email__icontains=srch) # match = Post.objects.annotate(search=SearchVector('title', 'email'),).filter(search=srch) if match: return render(request,'post/index.html',{'sr':match}) else: messages.add_message(request,messages.INFO,' No result found ') else: return redirect('post') return render(request,"post/index.html") -
Django regex url parsing to calling wrong view
I have a Django 2.2 project (using the rest framework) where I need to call a view function with a url of the following format: /class/students?date=07092019 and I've set up the following url route to handle this url:re_path(r'^class/students%3Fdate%3D(?P<date>\w+)/$',StudentsInClassView.as_view() ,name='student'). The corresponding view function has the following definition: class StudentsInClassView(APIView): def get(self, request, date,format=None): For some reason, whenever I go to url, it gets converted to /class/students/?date=07092019 and a different view, with the url path('nba/students/',StudentsView.as_view() ,name='students'), gets called instead. If I remove the "?date=" from the url and just include the actual date, the StudentsInClassView is called as expected. I've escaped both the question mark and the equal sign but doing so doesn't seem to make a difference. How can I get the "?date=" slug to remain in the url as it is used to call the StudentsInClassView? Is there a different regex that could be used to match the whole url? -
How can I display a list in tabs or pagination in django?
I am currently working on a django project where in from views.py, I am calling a function to render my HTML page and I am passing an argument which is list of lists. I want to display these lists in tabs or pagination where only first list is active and others are in pagination, how can I do that? And the list of lists I am passing may have different number of items in it. -
a superior user can change other user's password
as an assignment, i need to create this simple web app using django as the admin, I'll create a "low level" username + password. the salesmanager will then give this username and password to his salespersons. this is a "read-only" username. that means, the salespersons can only read/see the data available on this company webapp, simultaneously using just this one username. this username can't change the password. if one of the salespersons resigns, the password will need to be changed. because the salesperson turnover is rather high, I want the salesmanager to be able to change the password for this username, so i don't have to do it myself everytime. the salesmanager himself will use a different username + password as he has more permissions. how do i use django's change password to work in this situation? thank you -
Serializer Validate() method not invoking in serializer DRF
In DRF the serializer validate() method is not calling by default. i am using the serializer like this: class SampleListView(ListAPIView): queryset = Sample.objects.all() serializer_class = SampleSerializer def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) return Response(sorted_result) class SampleSerializer(serializers.ModelSerializer): custom_data = serializers.SerializerMethodField() class Meta: model = SampleModel fields = ('field_1', 'field_2') def validate(self, data): return data Execution not enter into the validate() method in serializer. Anyone have an idea about this? -
Password reset email not sending with the addition of a custom template
Trying to get my custom template to display with my password reset email, but it's not working. The email sends, but the custom email template does not render. path('accounts/password-reset/', auth_views.PasswordResetView.as_view( template_name='password_reset.html', html_email_template_name='password_reset_email_template.html', subject_template_name='password_reset_subject.txt' ), name='password_reset'), password_reset_email_template.html: <html> <tr> <td style="color:#333333; font-family: Helvetica, sans-serif;text-align:left; font-size:14px; line-height:20px; padding-bottom:18px;text-align:left;"> {% load i18n %} {% autoescape off %} You're receiving this e-mail because you requested a password reset for account. {% endautoescape %} <p>Follow the link below to reset:</p> <a href="https://domain{% url 'password_reset_confirm' uidb64=uid token=token %}"> Reset Password </a> </td> </html> -
set() argument after * must be an iterable, not NoneType in Django
I have recently implemented a system where users can only submit 3 tags on their posts, and it will tell them that they can't if they try to upload more than 3. (Thanks for helping me do this @minglyu). Whilst this does work, I get this error after trying to resubmit the form with the right amount of tags set() argument after * must be an iterable, not NoneType I am using django-taggit at the moment for tags by the way Here is my forms.py class PostForm(forms.ModelForm): class Meta(): model = Post fields = ['title','text','group','image','file','tags','spoiler','NSFW'] widgets = { 'title':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'textareaclass editable'}), } def clean_tags(self): tn = self.cleaned_data.get('tags', []) if len(tn) > 3: raise ValidationError('Invalid number of tags') def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['image'].required = False self.fields['file'].required = False The issue is coming from the clean_tags method. Here is the views.py class PostListView(SelectRelatedMixin,TagMixin,ListView): model = Post hit_count = True template_name = 'mainapp/post_list.html' selected_related = ("user","group") paginate_by = 10 context_object_name = 'posts' queryset = models.Post.objects.all() def get(self,request,): posts = Post.objects.all().order_by('-published_date') users = User.objects.exclude(id=request.user.id) count= User.objects.all().count() friend, created = Friend.objects.get_or_create(current_user=request.user) friends = friend.users.all() group = Group.objects.all() args = { 'users':users, 'friends':friends, 'posts':posts, 'group':group,'count':count } return render(request, self.template_name, args) def get_queryset(self): return … -
Microsoft login page and Django
enter image description here I want to bring the Microsoft login page like the above picture on my Django project. can anybody help me here how to do it? -
two forloop that generates every item using one table row
I have two loops from my python which generates every item with their respective. \html <table> {% for sensie in teacher %} <tr style='height:19px;'> <th id="703183278R34" style="height: 19px;" class="row-headers-background"> <div class="row-header-wrapper" style="line-height: 19px;">35</div> </th> <td class="s46"></td> <td class="s51" colspan="3">{{sensie.Subjects}}</td> <td class="s51" colspan="4">{{sensie.Employee_Users}}</td> {% endfor %} {% for room in roomsched %} <td class="s51" colspan="6">{{room.Classroom}}-{{room.Day_Name}}</td> </tr> {% endfor %} </table> \views def enrollmentform(request): id = request.GET.get('StudentID') if StudentsEnrollmentRecord.objects.filter(Student_Users=id).exists(): studentenroll = StudentsEnrollmentRecord.objects.filter(Student_Users=id) FeesType = SchoolFeesMasterList.objects.filter(Education_Levels__in=studentenroll.values_list('Education_Levels')) teachers = SubjectSectionTeacher.objects.filter(Education_Levels__in=studentenroll.values_list('Education_Levels')) roomsched = SubjectRoomSchedule.objects.filter(Subject_Section_Teacher__in=teachers) return render(request, 'Homepage/enrollmentrecords.html',{"studentenroll":studentenroll,"SchoolFeesType":FeesType,"teachers":teachers,"roomsched":roomsched}) else: . . . return render(whatever I want) \models class SchoolFeesMasterList(models.Model): Education_Levels= models.ForeignKey(EducationLevel, related_name='grade', on_delete=models.CASCADE,blank=True) Courses = models.ForeignKey(Course, on_delete=models.CASCADE,blank=True) Payment_Types = models.ForeignKey(PaymentType, on_delete=models.CASCADE,blank=True) Display_Sequence = models.IntegerField(blank=True, null=True) School_Fees_Type= models.ForeignKey(SchoolFeesType, on_delete=models.CASCADE,blank=True) Amount = models.FloatField() Amount_Per_Unit = models.FloatField() Effectivity_Date_From = models.DateField(null=True,blank=True) Effectivity_Date_To = models.DateField(null=True,blank=True) Remark = models.TextField(max_length=500,blank=True) def __str__(self): suser = '{0.Education_Levels} {0.Courses}' return suser.format(self) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, on_delete=models.CASCADE,null=True) Education_Levels = models.ForeignKey(EducationLevel, on_delete=models.CASCADE,blank=True) Courses= models.ForeignKey(Course, on_delete=models.CASCADE,null=True,blank=True) Sections= models.ForeignKey(Section, on_delete=models.CASCADE,null=True) Subjects= models.ForeignKey(Subject, on_delete=models.CASCADE,null=True) Employee_Users= models.ForeignKey(EmployeeUser, on_delete=models.CASCADE,null=True) Start_Date = models.DateField(null=True,blank=True) End_Date = models.DateField(null=True,blank=True) Remarks = models.TextField(max_length=500) def __str__(self): suser = '{0.Employee_Users}' return suser.format(self) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='paymenttype', … -
How do I create a separate model for relating primary keys of two models in a single table?
I have a User model and a Position Model, Where Position and User model both has username and position name as unique key. I want to create a separate table(which will be a relation table) where I can associate each user to their position. This is what I have tried : class Profile(models.Model): STATUS_CHOICES = ( (1, ("Permanent")), (2, ("Temporary")), ) GENDER_CHOICES = ( (1, ("Male")), (2, ("Female")), (3, ("Not Specified")) ) user = models.OneToOneField(User, on_delete=models.CASCADE) emp_type = models.IntegerField(choices=STATUS_CHOICES, default=1) contact = models.CharField(max_length=13, blank=True) whatsapp = models.CharField(max_length=13, blank=True) gender = models.IntegerField(choices=GENDER_CHOICES, default=3) avatar = models.ImageField(upload_to='users/images', default='users/images/default.jpg') manager_username = models.ForeignKey(User, blank=True, null=True, to_field='username',related_name='manager_username', on_delete=models.DO_NOTHING) def __str__(self): return self.user.username class Position: name = models.CharField(max_length=20, unique=True) class Emp_position: emp_uname = models.ForeignKey(User, related_name='emp_name', to_field='username', on_delete=models.CASCADE) position_name = models.ForeignKey(Position, related_name='position', to_field='name', on_delete=models.CASCADE) It was working fine until I migrated Position table but when I am adding the relation table i.e Emp_position, I am getting an error : Traceback (most recent call last): File "C:\Users\Himanshu Poddar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\related.py", line 786, in __init__ to._meta.model_name AttributeError: type object 'Position' has no attribute '_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Himanshu Poddar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 381, in …