Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Restrict access to reset_password form of Django in PasswordResetView in case the user is already logged in
Currently, I have a user model that can access account related information based on its session. I am using the django auth PasswordResetView. The password reset form is used to reset password if the user has forgotten his/her password. But this django view is also accessed by the user when he is already logged in. How can I restrict the user to access this page. I cannot find solution for this problem, since its a total abstraction and nothing is present in my views.py file. This is how my urls.py file looks like : from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from users import views as user_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('mainapp.urls')), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name="login"), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name="logout"), path('password_reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name="password_reset"), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name="password_reset_done"), path('password_reset_confirm/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name="password_reset_confirm"), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name="password_reset_complete"), path('change_password/', auth_views.PasswordChangeView.as_view(template_name='users/change_password.html', success_url="/"), name="password_change"), # path('password_change_done/done/', auth_views.PasswordChangeDoneView.as_view(template_name='users/password_change_done.html'), name="password_change_done"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) A logged in user should not be able to access password_reset_form since it is only meant when the password is forgotten and when the user is already logged in. It does not make sense for the user to access password_reset.html. … -
How to set apache permissions for a Postgresql in Ubuntu for a Django project?
Ok so I did not set apache permissions for db.sqlite3 as I intend to use postgresql, but I did give permission to my whole django project folder. Now, should I just make a postgresql user and a db and assign the credentials in the settings.py and leave it like that? Also, I'm not really sure what to put in the "HOST" and "PORT" entries if that's the case? DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": 'mydbname_db', "USER": 'myuser', "PASSWORD": 'mypass', "HOST": "", "PORT": "", } } -
User login system in Django, with MongoDB as the primary database
So, here is the thing. I want the best method to log users on my website. I've already made a registration system that registers details of Users in the mongoDB using model forms. I don't understand how to login the user in th website. Do I fetch the user data from the DB and match with the the form data entered by the user to log in, what is the best practice? -
How to make fast the import of an excel file containing more than 5000 lines into sqlite database with django
Import xls file (more than 5000 lines) into my sqlite database takes so long def importeradsl(request): if "GET" == request.method: else: excel_file = request.FILES["excel_file"] #you may put validations here to check extension or file size wb = openpyxl.load_workbook(excel_file) #getting a particular sheet by name out of many sheets worksheet = wb["Sheet 1"] #iterating over the rows and getting value from each cell in row for row in worksheet.iter_rows(min_row=2): row_data = list() for cell in row: row_data.append(str(cell.value)) #Get content fields DerangementCuivre models #Client nd = row_data[0] nom_client = row_data[3] nd_contact = row_data[4] #Categorie code_categorie = row_data[6] acces_reseau = row_data[8] etat = row_data[9] origine = row_data[10] code_sig = row_data[11] agent_sig = row_data[13] date_sig = dt.datetime.strftime(parse(row_data[14]), '%Y-%m-%d %H:%M:%S') date_essai = dt.datetime.strftime(parse(row_data[15]), '%Y-%m-%d %H:%M:%S') agent_essai = row_data[18] try: date_ori = dt.datetime.strptime(row_data[19], '%Y-%m-%d %H:%M:%S') except ValueError as e: print ("Vous", e) else: date_ori = dt.datetime.strftime(parse(row_data[19]), '%Y-%m-%d %H:%M:%S') agent_ori = row_data[20] code_ui = row_data[21] equipe = row_data[22] sous_traitant = row_data[23] date_pla = dt.datetime.strftime(parse(row_data[24]), '%Y-%m-%d %H:%M:%S') date_rel = dt.datetime.strftime(parse(row_data[25]), '%Y-%m-%d %H:%M:%S') date_releve = dt.datetime.strptime(row_data[25], '%Y-%m-%d %H:%M:%S') date_essais = dt.datetime.strptime(row_data[15], '%Y-%m-%d %H:%M:%S') pst = pytz.timezone('Africa/Dakar') date_releve = pst.localize(date_releve) utc = pytz.UTC date_releve = date_releve.astimezone(utc) date_essais = pst.localize(date_essais) date_essais = date_essais.astimezone(utc) code_rel = row_data[26] localisation = row_data[27] cause = … -
How to store multiple images for a single row/object in Django so that I can retrieve them or perform other query operations easily?
I am trying to build an api for a mobile application about house rents. The user may post multiple images of his house while posting an ad. How do I save them? I thought of Creating one-to-many relationship with My Ad class and an Image class, is there anything better? I've given a part of what I am talking about. class RentPost(models.Model): id = models.AutoField() title = models.CharField(max_length = True) description = models.Textarea() class Images(models.Model): post = models.ForeignKey(RentPost, on_delete= models.CASCADE) -
Boto3 deprecation warning on import
I'm trying to use boto3 in a python/django project. I've done this before, but it's throwing me a warning when running localhost -- which is breaking the request I'm trying to run. I'm on python version 3.7. I've seen the issue raised in the GitHub repo for boto3, most referring to errors when running pytest. My issue doesn't seem to fall in line with the latest PR https://github.com/boto/botocore/issues/1615 I'm not too sure where to turn. Any advice is much appreciated. from . import urllib3 File "/Users/neilballard/.local/share/virtualenvs/Volley-ldVCpc8_/lib/python3.7/site-packages/botocore/vendored/requests/packages/urllib3/__init__.py", line 10, in <module> from .connectionpool import ( File "/Users/neilballard/.local/share/virtualenvs/Volley-ldVCpc8_/lib/python3.7/site-packages/botocore/vendored/requests/packages/urllib3/connectionpool.py", line 38, in <module> from .response import HTTPResponse File "/Users/neilballard/.local/share/virtualenvs/Volley-ldVCpc8_/lib/python3.7/site-packages/botocore/vendored/requests/packages/urllib3/response.py", line 9, in <module> from ._collections import HTTPHeaderDict File "/Users/neilballard/.local/share/virtualenvs/Volley-ldVCpc8_/lib/python3.7/site-packages/botocore/vendored/requests/packages/urllib3/_collections.py", line 1, in <module> from collections import Mapping, MutableMapping File "<frozen importlib._bootstrap>", line 1032, in _handle_fromlist File "/Users/neilballard/.local/share/virtualenvs/Volley-ldVCpc8_/lib/python3.7/collections/__init__.py", line 52, in __getattr__ DeprecationWarning, stacklevel=2) DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working I've confirmed that "import boto3" is causing the issue. I've removed boto3, reinstalled, tried different version of boto3 & urllib. -
DJANGO: Cannot start gunicorn from service configuration file
I cannot start gunicorn from the configuration file. it runs perfectly from: gunicorn --bind 0.0.0.0:8000 myproject.wsgi service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=nigsdtm WorkingDirectory=/home/nigsdtm/django_projects/PID/PID_webinterface ExecStart=/home/nigsdtm/django_projects/PID/PID_webinterface/pidvirtualenv/bin/$ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ mysite.wsgi:application [Install] WantedBy=multi-user.target project root(where manage.py is located):/home/nigsdtm/django_projects/PID/PID_webinterface virtual env: /home/nigsdtm/django_projects/PID/PID_webinterface/pidvirtualenv sudo systemctl status gunicorn.socket: gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: active (listening) since Wed 2019-10-16 13:49:57 UTC; 2h 47min ago Listen: /run/gunicorn.sock (Stream) file /run/gunicorn.sock - ok /run/gunicorn.sock: socket sudo journalctl -u gunicorn.socket: Oct 16 12:19:00 nigsdtm systemd[1]: Listening on gunicorn socket. Oct 16 12:22:22 nigsdtm systemd[1]: gunicorn.socket: Unit entered failed state. sudo systemctl status gunicorn: - not ok gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2019-10-16 13:58:04 UTC; 2h 41min ago Main PID: 1038 (code=exited, status=203/EXEC) Oct 16 13:58:04 nigsdtm systemd[1]: Started gunicorn daemon. Oct 16 13:58:04 nigsdtm systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC Oct 16 13:58:04 nigsdtm systemd[1]: gunicorn.service: Unit entered failed state. Oct 16 13:58:04 nigsdtm systemd[1]: gunicorn.service: Failed with result 'exit-code'. Oct 16 14:05:47 nigsdtm systemd[1]: [/etc/systemd/system/gunicorn.service:12] Missing '='. curl --unix-socket /run/gunicorn.sock localhost curl: (56) Recv failure: Connection reset by peer sudo … -
Where complicated template logic should reside?
I am wondering where complicated template logic should reside when using MVC framework like Django. For example, I want to display the list of some models with their children's children's children's models grouping by their category. Grouping some model's children's children's children's model is only for displaying purpose. Embedding this logic is too complicated to implement in Template. However, I think model shouldn't care about how it would be displayed, and controller is not for the place for reusable logic. If I could create middleware between template and controller, that seems right choice, but I can't do that. Where should complicated logic for template resides? -
How to add new field to existing django model postgres
Let's suppose I have the following model: class Test(models.Model): field_one = models.CharField(max_length=80) Now, we have created 2-3 Model objects with field_one field. p1 = Test(field_one="Object1") p1.save() p2 = Test(field_one="Object2") p2.save() Later, I realised that I need to add another field field_two to my Test model. class Test(models.Model): field_one = models.CharField(max_length=80) field_two = models.IntegerField(default=3) Now, Doing makemigrations & migrate and running server. which will prompt the following error django.db.utils.ProgrammingError: column mainapp_test.field_two does not exist I understand that this error occurs due to my 2 existing objects in PostGresDB doesn't have field_two column. Is there any effective way to add the column to my objects with some default value? & How to solve this problem? -
Why is my code not rendering a list of table on my web page?
I have a model D100Generator with an incrementing primary key. I am trying to mimic the Django tutorial pt. 3, substituting a list of table names for the questions that should be rendered on the index.html page. When I run the code, I get a bullet point, but no text. Is my latest_table_list not being populated? Or is it I'm calling the wrong thing? I am very new to Python, web development and Stack Overflow, so forgive me if the formatting and explanation is poor on this. I suspect I'm not calling the table_name field correctly, but nothing I've tried has been able to work. I tried setting the line item for the list as: <li><a href="/generators/{{ d100Generator.d_100_id }}/">{{ d100Generator.table_name }}</a></li> and as: <li><a href="/generators/{{ d100Generator.id }}/">{{ d100Generator.table_name }}</a></li> neither of which will help display as desired. The D100Generator Model class D100Generator(models.Model): d_100_id = models.AutoField(primary_key=True) field_of_interest = models.ForeignKey(FieldOfInterest, on_delete=models.CASCADE) subreddit_post_id = models.ForeignKey(Subreddit, on_delete=models.CASCADE, blank=True, null=True) module_id = models.ForeignKey(Module, on_delete=models.CASCADE, blank=True, null=True) generic_website_id = models.ForeignKey(GenericWebsite, on_delete=models.CASCADE, blank=True, null=True) table_name = models.CharField('table name', max_length=100) system = models.CharField(max_length=150) genre = models.CharField(max_length=250) chart_type = models.CharField('Die used', max_length=15) chart_instructions = models.TextField('Chart instructions & explanation') roll_1 = models.TextField('1', blank=True, null=True) roll_2 = models.TextField('2', blank=True, null=True) roll_3 … -
Difficult queryset for prefetch
I have models: class Inote(IDeclaration): Time = models.DateTimeField(auto_now=True) Author = models.ForeignKey(User, related_name='%(class)ss') __unicode__ = lambda s: str(s.id) + ' (%s)'%(s._meta.model_name) class Article(Inote): Title = models.CharField(max_length=50) The models are linked by multitable inheritance. In my view I try get Articles through prefetch_related in queryset of User: class UserList(ListView): model = User def get_queryset(self): qs = super(UserList, self).get_queryset().prefetch_related('inotes__article') for q in qs: for i in q.inotes.all(): if hasattr(i,'article'): print i.article return qs If I apply prefetch_related('inotes__article') to qs, I get roughly what I want - three queries: SELECT ••• FROM "auth_user" SELECT ••• FROM "testapp_inote" WHERE "testapp_inote"."Author_id" IN ('1', '2', '3', ...) SELECT ••• FROM "testapp_article" INNER JOIN "testapp_inote" ON ("testapp_article"."inote_ptr_id" = "testapp_inote"."id") WHERE "testapp_article"."inote_ptr_id" IN ('1', '2', '3', '4') But I cann't know what inote is article and in this regard I have used if hasattr(i,'article') to distinguish its. And I wanted to solve this problem through Prefetch, but if I do this: prefetch = Prefetch("inotes", Inote.objects.filter(article__isnull=False)) qs = super(UserList, self).get_queryset().prefetch_related(prefetch) then I have many queries for each inote in my db. Then I tried Prefetch("inotes__article", Inote.objects.filter(article__isnull=False), but has FieldError on inotes__article. How to use correctly Prefetch to solve my problem. Could you share examples or links about complex queries in … -
Is It possible login Django admin via PyQt5?
I'd like to know if it's possible to login to django via PyQt5. I have been trying a few things but without much success. Below, I try a solution with PyQt5's QtNetwork. This is my code: import json import sys import requests from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QLineEdit, QMessageBox, QLabel from PyQt5.QtCore import pyqtSlot from PyQt5 import QtCore, QtGui, QtNetwork from django.test import Client from querystring import querystring class AppLogin(QMainWindow): def __init__(self): super().__init__() self.title = 'Login in the Desktop Application' self.left = 500 self.top = 300 self.width = 380 self.height = 180 self.username = None self.password = None self.button = None self.nam = QtNetwork.QNetworkAccessManager() def __call__(self, *args, **kwargs): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) # Create an username textbox self.username = QLineEdit(self) self.username.move(20, 20) self.username.resize(280, 40) self.username.setPlaceholderText('Usuário') # Create a password textbox self.password = QLineEdit(self) self.password.setEchoMode(QLineEdit.Password) self.password.move(20, 80) self.password.resize(280, 40) self.password.setPlaceholderText('Senha') # Create a button in the window self.button = QPushButton('Login', self) self.button.move(20, 140) # connect button to function login self.button.clicked.connect(self.login) self.show() @pyqtSlot() def login(self): # User and passwd in my desktop app user = self.username.text() passwd = self.password.text() # My Django app Url url = "http://127.0.0.1:8000/login" data = {'username': user, 'password': passwd} # Here, I use QtNetWork to takes … -
Is it safe to manually change object id in Django
I have an Inline model in django admin, which appearance is ordered by id. I want to add functionality to change the appearance ordering via changing the id's directly. So I will do something like one = Model.objects.get(id=1) two = Model.objects.get(id=2) one.id, two.id = two.id, one.id one.save() two.save() Which does the trick, but I feel that it is not safe. Might it cause any troubles or issues? Are there a better way to achieve proper ordering in django admin? -
create or update user password in serializers rest_framework django
I want to check if the user exists, update the password(OTP). else create a new User (with one API). Note: My model is customized for mobile and OTP system. views.py: class GetOTP(APIView): def post(self, request, *args, **kwargs): mobile_number = request.data.get('mobile', False) mobile = check_mobile(mobile_number) if not mobile['status']: return Response(mobile) else: mobile = str(mobile['details']) otp = otp_generate(mobile) if otp: print('<------------------> ',otp) temp_data = {'mobile': mobile, 'password': otp} serializer = CreateOrGetUserSerializer(data=temp_data) serializer.is_valid(raise_exception=True) serializer.save() return Response({'status': True, 'details': 'Account created'}) else: return {'status': False, 'details': 'err to send OTP'} serializers.py : class CreateOrGetUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'mobile', 'password', ] def create(self, validated_data): user = User.objects.create_user(**validated_data) return user -
setup server for django application in Windows Server 2012 R2 Standard
I must setup a network computer (running Windows Server 2012 R2 Standard) as a production server for django applications, real quick. This is what I've already done: Installed Python 3.7.4 (64 bits version) Installed nginx 1.17.4 Installed virtualenv Created a virtual environment for hosting my application Have my django project ready and running ok with "manage.py runserver" Where do I go from here? I'm sorry, but I couldn't find instructions simple and atraightforward enough for me so far. I could use IIS or Apache as well, but only if it's simpler than nginx. -
Updateview setting user to null
When using updateview for some reason my user value is being set to null. I have a create view where the user is automatically set to the current user and when I view the database everything works as expected. The issue is that when I use updateview the value is being reset to null. All other values work as expected. Does anyone know how to prevent the value from being reset to null? class model_testform(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="author", null=True, blank=True, on_delete=models.SET_NULL) class view_testform(CreateView): model = model_testform form_class = form_testform template_name = "testform.html" def form_valid(self, form): self.object = form.save(commit=False) self.object.author = self.request.user form.save() return super(view_testform, self).form_valid(form) def get_success_url(self, *args, **kwargs): form = form_testform messages.add_message(self.request, messages.SUCCESS, 'New Block was submitted') return reverse("testform:view_testform") class view_testformUpdate(UpdateView): model = model_testform form_class = form_testform template_name = "testformUpdate.html" def get_success_url(self, *args, **kwargs): form = form_testform messages.add_message(self.request, messages.INFO, 'Block was Updated') return reverse("testform:view_testform") -
Django loaddata from fixture returns error
Hello there i'm trying to move my django project from SQLite to PostgreSQL and in order to do that i need to populate the DB with some initial values. I already have 4 different fixture files with the initial data. These files are inside a fixtures directory inside the app. One per model and one including all initial data that i currently have on my SQLite DB. I already Created the DB in PostgreSQL and made the proper changes to the settings.py file in order to move to the PostgreSQL DB. The problem is that when i use python manage.py loaddata InitialData command it returns an error Traceback (most recent call last): File "/home/seba94/.local/share/virtualenvs/register-page-jYLn8mRO/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "reg_producto" does not exist LINE 1: ...eg_producto"."Name", "reg_producto"."CMS_id" FROM "reg_produ... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/seba94/.local/share/virtualenvs/register-page-jYLn8mRO/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/seba94/.local/share/virtualenvs/register-page-jYLn8mRO/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/seba94/.local/share/virtualenvs/register-page-jYLn8mRO/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/seba94/.local/share/virtualenvs/register-page-jYLn8mRO/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/seba94/.local/share/virtualenvs/register-page-jYLn8mRO/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = … -
In django,how get share the an object between the method of GET and POST
guys! I generate a requests.session() obeject in get method, and i want use it latter in the post method. How can i do it? # views.py import requests class Page(View): session = None def get(self,request): self.session = requests.session() # get an session object return def post(self,request): self.session # I want use the self.session which generate in get methon return # urls.py urlpatterns = [ path(r'page/',views.Page.as_view(),name='page'), ] -
How to skip validation for DRF serialiser FloatField
Problem I need to add the ability to save the minimum_commission as positive number, but None is also available. I have added the serialiser: class RentalTestSerializer(serializers.ModelSerializer): minimum_commission = serializers.FloatField(required=False, min_value=0) class Meta: model = Appartement fields = ( 'minimum_commission', ) But when I pass the empty string from the form(or shell), I see the A valid number is required validation error. In [21]: ser = RentalTestSerializer(data={'minimum_commission': ''}) In [22]: ser.is_valid() Out[22]: False In [23]: ser.errors Out[23]: ReturnDict([('minimum_commission', [ErrorDetail(string=u'A valid number is required.', code=u'invalid')])]) Possible solution At first I have added custom field: BlankableFloatField which convert empty string to the None: class BlankableFloatField(serializers.FloatField): """ We wanted to be able to receive an empty string ('') or 'null' for a float field and in that case turn it into a None number """ def to_internal_value(self, data): if data in ['', 'null']: return None return super(BlankableFloatField, self).to_internal_value(data) and added the custom validation: class RentalTestSerializer(serializers.ModelSerializer): minimum_commission = BlankableFloatField(required=False) class Meta: model = Appartement fields = ( 'minimum_commission', ) def validate_minimum_commission(self, value): if value and value < 0: raise serializers.ValidationError(_("Minimum commission should be greater than 0")) return value For now it works as expected: In [38]: ser = RentalTestSerializer(data={'minimum_commission': ''}) In [39]: ser.is_valid() Out[39]: True … -
Django user sign up doesn't work properly (Users are not registered to DB)
I made the django user registration form with profile picture uploading. By combining default user libraries with profile module. But when I register a user click on submit without registering the user i will be directed to the index.html. When i check in the data base also the user details entered in the sign up form doesn't appear. Im using pycharm for development and django version is 1.9 view.py def signup(request): if request.method == 'POST': form = Signup(request.POST,request.FILES) if form.is_valid(): user = form.save(commit=False) user.refresh_from_db() username = form.cleaned_data.get('username') password1 = form.cleaned_data.get('password1') user.set_password(password1) user.save() user = authenticate(username=username,password=password1) login(request,user) return HttpResponseRedirect('/') else: form = Signup() args = {'form':form} return render(request, 'register.html', args) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) business_reg = models.TextField(max_length=500, blank=True) avatar = models.ImageField(upload_to='avatars/') @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() forms.py class Signup(forms.ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) business_reg = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) avatar = forms.FileField(widget=forms.FileInput(attrs={'class': 'form-control'})) password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'})) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'})) class Meta: model = User fields = ('username','business_reg','avatar','password1', 'password2',) register.html <div class="panel-body"> <form method="post"> {% csrf_token %} <div class="form-group"><label for="formGroupExampleInput">Username</label>{{ form.username }} </div> <div class="form-group"><label for="formGroupExampleInput">Business Registration</label>{{ form.business_reg }} </div> <div class="form-group"><label for="formGroupExampleInput">Profile Picture</label>{{ form.avatar }} </div> <div class="form-group"><label for="formGroupExampleInput">Password</label>{{ form.password1 }} </div> <div class="form-group"><label … -
Correct way to apply gherkin features and scenarios to django views
I am trying to understand practical usage of gherkin features and scenarios using django generic views as an example, because I am familiar with django but not gherkin. In writing gherkin for django views, what would be an example of best practice for separating features and scenarios specific to django generic views, and an example of a terrible one, and why? For example - in a Reports app that has generic views for update, detail and list for a report model. Would there be separate features for update, list and detail or would the reports app be a feature with update, detail and list scenarios? I ask this specifically not only because I am writing a reporting app in django, but because django is a highly structured framework that would seem to easily fall into gherkin and examples of such would be very easy for me to learn to understand gherkin practically. -
redirect() between views in separate apps
I am following a Django tutorial where the blog app and users app are separate. Upon registering as a user I would like the user to be redirected to a view in the blog app. Here is the users app views.py: def register(request): if request.method == 'POST': # if form was submitted w data form = UserCreationForm(request.POST) #instantiate form w post data if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}') return redirect('blog-home') #not working else: form = UserCreationForm() return render(request, 'users/register.html', {'form':form}) and here is the blog app's views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Post # Create your views here. def home(request): posts = Post.objects.all() return render(request, 'blog/home.html', {'posts':posts}) and the url pattern tied to said view: path('', views.home, name = 'blog-home'), When a user submits the form, I get the following error: Reverse for 'home' not found. 'home' is not a valid view function or pattern name. I am not sure why this is, I believe I copied the code word for word and the example in the video is working. -
django model instance method not being called
I want to update my model upon login (to check the authorizations of a person from an external system). The code of my model looks as follow: import json from django.contrib.auth.models import AbstractUser from django.contrib.auth.signals import user_logged_in from django.db import models class Person(AbstractUser): is_dean = models.BooleanField(null=False, blank=False, default=False) is_institute_manager = models.BooleanField(null=False, blank=False, default=False) managed_institutes = models.TextField(blank=True, null=True, default=None) def get_managed_institutes(self): return json.loads(self.managed_institutes) def set_managed_institutes(self, value): self.managed_institutes = json.dumps(value) # Signals processing def check_authorizations(sender, user, request, **kwargs): ... # check if the user is dean is_dean = False # logic to check if the user is dean... user.is_dean = is_dean # Check if the user manages institutes is_institute_manager = False managed_institutes = list() # Logic to check if the user is managing institutes ... user.is_institute_manager = is_institute_manager user.set_managed_institutes = managed_institutes user.save() user_logged_in.connect(check_authorizations) Surprisingly, the boolean flags get set correctly, but the method set_managed_institute never gets called... I am quite convinced this a trivial mistake from my end, but I can't figure it out. -
Call View from another View after modifying request (Rest-Framework)
Book_ViewSet: I have a ViewSet that takes care of all the CRUD operations on a product. Consider Book API, where I can create a book based on title and author. ISBN_View: I have another View that accepts ISBN numbers, looks up the book, gets the title and author and creates the Book from Model. What I want: After parsing ISBN data and getting the book info, I want to create a fresh POST request to the Book_ViewSet with the book data as the body. I tried looking up best way to do this, but people suggested that modifying current request and sending it to different view is a bad practice. ============================================================= class Book_ViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = serializers.BookSerializer def create(self, request, *args, **kwargs): . . . return super().create(request, *args, **kwargs) def retrieve(self, request, *args, **kwargs): . . . return super().retrieve(request, *args, **kwargs) def destroy(self, request, *args, **kwargs): pass def update(self, request, *args, **kwargs): . . . return super().update(request, *args, **kwargs) class ISBN_view(generics.RetrieveAPIView): def get(self, request, isbn=None, *args, **kwargs): isbn, validation_error = self.validated_isbn(isbn) if not isbn: return Response(validation_error) # Here I use ISBN to search up books, and grab data # Here I want to call Book_ViewSet to create the … -
Django use calculated field for ordering_fields
I'm using Django and Django Rest Framework, with PostgreSQL. I need to create a calculated field on the model, and I need to also order by the field. I thought of using @property decorator for the calculated field, but as far as I know, I can't add this 'field' to the ordering_fields array. My question is - what would be the right way to do it? Should be something like (partial): The model- class MyModelViewSet(models.Model): due_date = models.DateField(null=True, blank=True) final_due_date = models.DateField(null=True, blank=True) @property def due_date_diff(self): if self.final_due_date: return self.final_due_date - due_date else: return due_date - date.today() In the View I would like to do something like: class MyModelViewSet(viewsets.ModelViewSet): serializer_class = MyModelSerializer ordering_fields = tuple(serializer_class.Meta.fields + due_date_diff)