Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Class View vs def view Django
Hello I have a simply question about Django Web Framework. I am curious what should i use. Function view or class view and try to change all the function views to the class view? What are differences cons and pros? -
Retrieve all related objects of objects in a queryset
Asked another question yesterday. Unfortunately, the answer did not solve the problem so I thought I narrow the question down and ask again. I have a Category model which is hierarchial(using django-treebeard). When I run example_category.get_descendants() the result I get is a MP_NodeQuerySet like the following <MP_NodeQuerySet [<Category: shoes>, <Category: Sneakers>, <Category: laced_sneakers>]> Out of this queryset I want to fetch every product related to each category and display in a view(DetailView). My best bet has been def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["products_in_category"] = Category.objects.prefetch_related( Prefetch("products", queryset=self.object.get_descendants())) return context Which results in the error "Cannot resolve keyword 'category' into field. Choices are: depth, description, id, numchild, path, products, slug, title" I guess I for some reason get the category back and not its products and I don't really know how to solve it. Check out the old question for more context or just ask away! -
Simple django filter is includes all users’ data rather than that of the logged-in user
I’m new to Django and have built a basic filter that does not filter according to the logged-in user’s data but rather all users’ data, which is incorrect. The filter is for an Automation class, which has a many:many relationship with the Message class (and funnily enough the exact same happens with the message filter). Views.py: @login_required(login_url='login') @allowed_users(allowed_roles=['admin', 'customer'], own_account_only=True) def automation_list(request, pk): account = Account.objects.get(id=pk) automations = account.automation_set.all() filter = AutomationFilter(request.GET, queryset=automations) automations = filter.qs context = {'account': account, 'automations': automations, 'filter': filter} return render(request, 'automations/automation_list.html', context) Filters.py: class AutomationFilter(django_filters.FilterSet): start_date = DateFilter(field_name='date_joined', lookup_expr='gte') end_date = DateFilter(field_name='date_joined', lookup_expr='lte') class Meta: model = Automation fields = '__all__' exclude = ['account', 'date_created'] Models: class Automation(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=200) account = models.ForeignKey(Account, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) messages = models.ManyToManyField(Message, blank=True) def __str__(self): return self.name class Message(models.Model): name = models.CharField(max_length=100) subject = models.CharField(max_length=128) text = models.TextField() account = models.ForeignKey(Account, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) automations = models.ManyToManyField('automations.Automation', blank=True) def __str__(self): return self.name Why is the filter not just filtering according to the logged-in user? I’d have thought that I’m only passing in the user’s data via this line: filter = AutomationFilter(request.GET, queryset=automations) Thanks -
Getting 504 Gateway Time-out for Django on Ubuntu
I deployed a Django app on Ubuntu 20.04 with Digital Ocean. The app has a Python package called howdoi that does some web scraping of google search results. I upgraded howdoi with pip from 2.0.16 to 2.0.17. Once I did that, the website stopped working and shows this error: 504 Gateway Time-out nginx/1.18.0 (Ubuntu) But if I downgrade the package to 2.0.16 the website works. The issue only happens on the production server. On localhost, the web app works fine. I am not sure what is the correct command to see the errors. I tried this command: sudo journalctl -u gunicorn -f and that returns these logs (I removed UTC times from the logs to make them more readable here): Aug 27 11:00:05 django-s-1vcpu-2gb-nyc1-01 gunicorn[469603]:[INFO] Worker exiting (pid: 469603) Aug 27 11:00:06 django-s-1vcpu-2gb-nyc1-01 gunicorn[469545]:[WARNING] Worker with pid 469603 was terminated due to signal 9 Aug 27 11:00:06 django-s-1vcpu-2gb-nyc1-01 gunicorn[469665]:[INFO] Booting worker with pid: 469665 Aug 27 11:08:10 django-s-1vcpu-2gb-nyc1-01 gunicorn[469545]:[CRITICAL] WORKER TIMEOUT (pid:469665) Aug 27 11:08:10 django-s-1vcpu-2gb-nyc1-01 gunicorn[469665]:[INFO] Worker exiting (pid: 469665) Aug 27 11:08:11 django-s-1vcpu-2gb-nyc1-01 gunicorn[469545]:[WARNING] Worker with pid 469665 was terminated due to signal 9 Aug 27 11:08:11 django-s-1vcpu-2gb-nyc1-01 gunicorn[469920]:[INFO] Booting worker with pid: 469920 I also tried this: … -
Hot to make a user profile view?
Since I am new to django, this is my first time trying to create a user profile. And I don't know how to make a profile view with a link to it. Could you please give me an example models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length = 40, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) slug = AutoSlugField(populate_from = 'username', null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() class Meta: verbose_name = 'Пользователь' verbose_name_plural = 'Пользователи' def __str__(self): return self.email def get_absolute_url(self): return reverse('profile', args=[str(self.slug)]) class UserProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete = models.CASCADE, null = True, db_constraint=False) avatar = ProcessedImageField( upload_to = 'avatar', format = "JPEG", default = "avatar/empty_avatar.jpg", processors = [ResizeToFit(250, 200)], options = {'quality': 90}, blank = True, null = True, ) description = models.TextField(default = '', blank = True, null = True) slug = AutoSlugField(populate_from = 'user', null=True) class Meta: verbose_name = 'Профиль' verbose_name_plural = 'Профили' @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=CustomUser) def save_user_profile(sender, instance, **kwargs): try: instance.userprofile.save() except ObjectDoesNotExist: UserProfile.objects.create(user=instance) forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email', 'username',) class CustomUserChangeForm(UserChangeForm): class Meta: model = get_user_model() fields … -
Django / DRF - Invalid syntax in a Response object
everyone. Sorry for dumb question. I follow this guide: https://www.youtube.com/watch?v=4Uy8NZsUfF0&t=3341s&ab_channel=JayCoding Here I have a Response object: https://youtu.be/4Uy8NZsUfF0?t=3352 return Response('test': self.get_serializer(test, context={'request': self.request}).data, 'last_question_id':last_question) And I get "Invalid syntax" on colons. But in video it works. When I change string to this: return Response(self.get_serializer(test, context={'request': self.request}).data, last_question) It works well. What should I change to make it work? Thank you. -
Persistent slug in Django
In my Django web application, each user has a randomly generated token generated for purposes beyond the scope of this question. This is the relevant Profile model models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,max_length=30) verified_account = models.BooleanField(default=False) verify_token = models.SlugField(max_length=15, blank=True, null=True, unique=True) def __str__(self): return self.user.username def get_absolute_url(self): return reverse('user:profile', kwargs={'pk': self.pk}) def generate_token(self): #important from django.utils.crypto import get_random_string self.verify_token = get_random_string(length=15) return self.verify_token def save(self, *args, **kwargs): # also important self.slug = slugify(self.user.username) self.generate_token() # issue is here super().save(*args, **kwargs) So basically, whenever a Profile object is created (on the creation of the User model), a token is randomly generated. However, whenever the Profile model is updated, so is the verify_token. Below is the code for my @receiver that handles user creation @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) else: instance.profile.save() I have tried to insert the following code below the Profile.objects.create(user=instance) line in order to try and get it to only generate the token when the Profile is created Profile.objects.filter(user=instance).generate_token() But this gives me the following error 'QuerySet' object has no attribute 'generate_token' What is the best way to ensure that the slug is not changed after every update of it's Profile model? Thank … -
AttributeError: 'NoneType' object has no attribute 'nace_classes'
Hej! I get an the Error: AttributeError: 'NoneType' object has no attribute 'attribute'. There error occurs when I try to save an institution in the django admin area. All other fields work totally fine. The function where I get the error is a @classmethod in my models.py # class StringFactory: @classmethod def construct_string(cls, something) value = set() value2 = set() for klass in something.attribute.all() # here is the error value.add(klass.code_str()) value2.add(klass.some_str()) return " ,".join(value) if I print my something it is None. Therefor the NoneType error. I am new to classes and classmethods. Can anyone help me where I should look whats going wrong and why it can't find my 'something' or why it is None? I call the class in a function in another class in a django admin.py So I guess the error comes from there. # class SomethingForm(forms.ModelForm): def construct_initial_string(self, somethingelse): return StringFactory.construct_string(somethingelse) I am a bit lost with the classes and tried to name all given somethings (something, somethingelse) the same, but nothing changed. If you want I can post more code but it's very much and in different files. Thanks for your help! -
bcrypt return TypeError Unicode-objects must be encoded before checking
I am trying to create login and Signup using django. All the database are stored in MySql. def signup(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username and password: Myobject = adminUser() Myobject.username = username Myobject.password = bcrypt.hashpw(password.encode('utf8'),bcrypt.gensalt()) Myobject.save() print("User Created Successfully") else: messages.WARNING("Username and Password can not be blank") return render(request,'signup.html') Using this signup function I am able to stored the username and hashed password in database. if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username is not None and password is not None: user=adminUser.objects.get(username=username) hashed_password = user.password is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password) print(is_check) return render(request,'login.html') During the login, I am getting this TypeError. I have already encoded the password. -
Outputting database items to a pdf document
I have currently generated a Trial Balance with Pastel Database items on a web page as per the below image. I need to add a button that will be able to download the exact same thing onto a pdf document. trb.html: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous"> {% extends "main/base.html"%} {% block content%} <h1>Kyle Database Trial Balance</h1> <br> <br> <div class="container"> <div class="row mb-0"> <div class="col"> <h3>Account</h3> <br> {% for accountNo in accountNo %} <p style="font-size:10px">{{ accountNo }}</p> {% endfor %} <br> <b><p style='font-size:11px' style='font'>Totals</p></b> </div> <div class="col-5"> <h3>Description</h3> <br> {% for description in description %} <p style="font-size:10px">{{ description }}</p> {% endfor %} </div> <div class="col"> <h3>Debit</h3> <br> {% for debit in debit %} <p style="font-size:10px">{{ debit }}</p> {% endfor %} <br> <b><p style="font-size:11px">{{ totalDebit }}</p></b> </div> <div class="col"> <h3>Credit</h3> <br> {% for credit in credit %} <p style="font-size:10px">{{ credit }}</p> {% endfor %} <br> <b><p style="font-size:11px">{{ totalCredit }}</p></b> </div> </div> </div> {% endblock %} Views.py: def Kyletrb(request): desc = "SELECT Description FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" cursor = cnxn.cursor(); cursor.execute(desc); description = [tup[0] for tup in cursor.fetchall()] accNo = "SELECT Account FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" cursor.execute(accNo); accountNo = [tup[0] for tup in cursor.fetchall()] deb = "SELECT Debit … -
Django Heroku Channels Live Chat Fail
I've deployed my app on Heroku and everything works fine EXCEPT the live chat (used websockets for this). I'm not sure what is going on. The live chat feature works perfectly fine in development. I have not setup the postgres database or AWS S3 yet for file storage, but that doesn't have much to do with why the chat isn't working I suppose. Here are my files related to heroku and the live chat: settings.py: CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } Profile: web: gunicorn reddix.wsgi --log-file - There is an error that says I need to use wss (it doesn't say this if I use http) so I already how to fix that issue. The bigger issue is that the live chat does not work on either ws/http or wss/https. It keeps saying: WebSocket connection to 'ws://myapp-test.herokuapp.com/pathtochat/' failed Here are my requirements.txt: aioredis==1.3.1 asgi-redis==1.4.3 asgiref==3.4.1 async-timeout==3.0.1 attrs==21.2.0 autobahn==21.3.1 Automat==20.2.0 backports.entry-points-selectable==1.1.0 bleach==4.0.0 boto3==1.18.30 botocore==1.21.30 cffi==1.14.6 channels==3.0.4 channels-redis==3.3.0 constantly==15.1.0 cryptography==3.4.8 daphne==3.0.2 distlib==0.3.2 Django==3.2.6 django-bleach==0.7.2 django-ckeditor==6.1.0 django-cleanup==5.2.0 django-crispy-forms==1.12.0 django-js-asset==1.2.2 django-model-utils==4.1.1 django-notifications-hq==1.6.0 django-storages==1.11.1 djangorestframework==3.12.4 filelock==3.0.12 gunicorn==20.1.0 hiredis==2.0.0 hyperlink==21.0.0 idna==3.2 incremental==21.3.0 jmespath==0.10.0 jsonfield==3.1.0 msgpack==1.0.2 msgpack-python==0.5.6 packaging==21.0 Pillow==8.3.1 platformdirs==2.2.0 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.20 pyOpenSSL==20.0.1 pyparsing==2.4.7 python-dateutil==2.8.2 python-decouple==3.4 pytz==2021.1 redis==2.10.6 s3transfer==0.5.0 service-identity==21.1.0 six==1.16.0 sqlparse==0.4.1 swapper==1.1.2.post1 … -
The form validation returning False in Django
views.py def student_login(request): form = StudentLoginForm() if request.method == 'POST': form = StudentLoginForm(data=request.POST) print(form.is_valid()) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') print(username) user = authenticate(username=username,password=password) if user is not None: login(request,user) return redirect('index') else: messages.error(request,'Invalid username or password!') else: messages.error(request,'Invalid username or password!') context = {'form':form} return render(request,'student_login.html',context) models.py class Student(models.Model): name = models.CharField(max_length=100) username = models.CharField(max_length=100,unique=True,default=None) mobile = models.CharField(max_length=8) email = models.CharField(max_length=200,unique=True) password = models.CharField(max_length=200,default=None,unique=True) total_books_due = models.IntegerField(default=0) def __str__(self): return self.name forms.py class StudentLoginForm(forms.ModelForm): class Meta: model = Student fields = ['username','password'] widgets = { 'password':forms.PasswordInput(), } student_login.html {% extends 'base.html' %} <!-- {% load crispy_forms_tags %} --> {% block content %} <div class="container"> <br> <h2>Student Login Form</h2> <br> <form method="POST" action=""> {% csrf_token %} {% if messages %} {% for message in messages %} <div class="alert alert-danger" role="alert"> {{ message }} </div> {% endfor %} {% endif %} <br> {% for field in form %} <p>{{ field.label }} </p> <p>{{ field }} </p> <br> {% endfor %} <br> <input type="submit" class="btn btn-primary" value="Login"> </form> </div> {% endblock %} I have been trying to change again and again but form.is_valid() is still returning False. I could not figure out the reason that the form is not valid … -
how to implement httponly jcookies with simple jwt django rest framework
is it possile to include httponly cookies in simple jwt django rest framework ? Serializers.py class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): # The default result (access/refresh tokens) data = super(CustomTokenObtainPairSerializer, self).validate(attrs) # Custom data you want to include data.update({'email': self.user.email}) data.update({'id': self.user.id}) data.update({'status':"success"}) # and everything else you want to send in the response return data Vies.py class CustomTokenObtainPairView(TokenObtainPairView): # Replace the serializer with your custom serializer_class = CustomTokenObtainPairSerializer -
How to create two models at once in django
I am making an API using DRF. Here I have a model called Blog and a model that refers to a Blog called Comment. When I create a Blog, I want to create several comments at the same time. Here's my current code. serializers.py class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' class BlogSerializer(serializers.Serializer): ... comments = serializers.ListField(child=serializers.DictField()) ... def create(self, validated_data): blog_validated_data = validated_data.copy() blog_validated_data.pop('comments') qs = Blog.objects.create(**blog_validated_data) comments = validated_data.get('comments') serializer = CommentSerializer(data=comments, many=True) serializer.is_valid(raise_exception=True) serializer.save() return qs models.py class Blog(models.Model): ... class Comment(models.Model): ... blog = models.ForeignKey(Blog, on_delete=models.CASCADE) ... How can I solve this code using queryset alone? -
Django Password Reset Confirm error (custom user model); update
I am not that experienced writing Python/Back-end, but trying to improve. In development/localserver I am trying to create a password reset form... but I got the following error when accessing the link from the forgot password email - and before that the password was not saving: init() missing 1 required positional argument: 'user' forms.py (almost copy/paste from Django's form; minor changes) class ResetPasswordForm(SetPasswordForm): error_messages = { 'password_mismatch': static_textLanguage['page_user_passwordReset_alert_passwordNotMatch'], 'password_empty': static_textLanguage['global_alert_mandatoryField'], 'minimum_length': static_textLanguage['global_alert_minCharacters_password'], } new_password1 = forms.CharField( required=False, widget=forms.PasswordInput(attrs={ 'id': 'page_userPasswordReset_content_form_input_passwordA', 'maxlength': '25', 'class': 'global_component_input_box' }), ) new_password2 = forms.CharField( required = False, widget=forms.PasswordInput(attrs={ 'id': 'page_userPasswordReset_content_form_input_passwordB', 'maxlength': '25', 'class': 'global_component_input_box' }), ) def __init__(self, user, *args, **kwargs): self.user = user super(ResetPasswordForm, self).__init__(user, *args, **kwargs) def clean_new_password1(self): password1 = self.cleaned_data.get('new_password1') if password1 == '' or password1 is None: raise forms.ValidationError(self.error_messages['password_empty'], code='password_field_empty') elif len(password1) < 8: raise forms.ValidationError(self.error_messages['minimum_length'], code='password_too_short') return password1 def clean_new_password2(self): password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if password2 == '' or password2 is None: raise forms.ValidationError(self.error_messages['password_empty'], code='password_field_empty') if password1 and password2: if password1 != password2: raise ValidationError(self.error_messages['password_mismatch'], code='password_mismatch') password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user views.py class UserPasswordResetView(auth_views.PasswordResetConfirmView): template_name = '../frontend/templates/frontend/templates.user/template.page_passwordReset.html' form_class = ResetPasswordForm post_reset_login = True success_url = reverse_lazy('page_userLoginPrivate') def … -
From UML diagram to Django model and schemas
I am confused here to convert this uml diagram into django models/schemas. Can anyone help me out there? -
how to convert single array list form multiple array [duplicate]
how to convert single array list form one multiple array list in django For example x = [[1,2,3],[4,5,6],[6,7]] I need result like this x = [1,2,3,4,5,6,6,7] -
How to load chart in Django Template
I have an Altair chart which I want to render in a Django Template. The chart is converted into a json object in the views. Here is the code views.py def home(request): if request.method=='POST': year = request.POST['year'] df, cus_dict = generate_df(year) bar_obj = barGraphAltair(year, df) bar_obj = json.loads(bar_obj.to_json()) print(bar_obj) context = {'bar': bar_obj} return render(request, 'index.html', context=context) return render(request, 'index.html') template <div id='altair-viz'> {% if bar %} {{ bar|safe }} {% endif %} </div> This just prints the json in the template. I know I have to use Vega to render the graph but I am not sure how to do that in jinja syntax A temp solution One way I got this to work, is by creating a different view and calling that view in the template as follows views.py def renderAltair(request): df, cus_dict = generate_df('2017') bar_obj = barGraphAltair('2017', df) bar_obj = json.loads(bar_obj.to_json()) return JsonResponse(bar_obj) template <script> vegaEmbed('#altair-viz', "{% url 'altair' %}") </script> This works, but as you can see from the original code, I get the year by submitting a form and passing that to the function for generating the graph. So I need the graph to be created in the home view -
How to change the language based on user choice?
I translated my site using Rosetta. I have two languages; en and tr. I created a language field in my UserProfile model, and I created a button in navigation bar for changing user's language choice. What I want is; User's language choice will be the language of the website. For example; When user click the TR button, re_path turns http://127.0.0.1:8000/tr/ or user click EN button re_path turns http://127.0.0.1:8000/en/ in every page. How can I do that? urls.py urlpatterns += i18n_patterns( re_path('', include('customer.urls')), re_path('', include('register.urls')), re_path('', include('approvals.urls')), ) models.py class UserProfile(AbstractUser, UserMixin): username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) ... language = models.CharField(max_length=250) -
Reverse for 'edit-expense' with no arguments not found. 1 pattern(s) tried: ['edit\\-expense/(?P<id>[0-9]+)$'] - Django
Trying to display a Page to update record but receiving following error. ERROR NoReverseMatch at /edit-expense/2 Reverse for 'edit-expense' with no arguments not found. 1 pattern(s) tried: ['edit\\-expense/(?P<id>[0-9]+)$'] Request Method: GET Request URL: http://127.0.0.1:8000/edit-expense/2 Django Version: 3.2.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'edit-expense' with no arguments not found. 1 pattern(s) tried: ['edit\\-expense/(?P<id>[0-9]+)$'] Exception Location: C:\Users\Ideation\AppData\Roaming\Python\Python39\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Program Files\Python39\python.exe Python Version: 3.9.5 Python Path: ['C:\\xampp\\htdocs\\Projects\\Ideation\\Ideation', 'C:\\Users\\Ideation\\AppData\\Roaming\\Python\\Python39\\site-packages\\_pdbpp_path_hack', 'C:\\Program Files\\Python39\\python39.zip', 'C:\\Program Files\\Python39\\DLLs', 'C:\\Program Files\\Python39\\lib', 'C:\\Program Files\\Python39', 'C:\\Users\\Ideation\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\Ideation\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32', 'C:\\Users\\Ideation\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32\\lib', 'C:\\Users\\Ideation\\AppData\\Roaming\\Python\\Python39\\site-packages\\Pythonwin', 'C:\\Program Files\\Python39\\lib\\site-packages'] Server time: Fri, 27 Aug 2021 05:30:22 +0000 views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .models import Category, Expense @login_required(login_url = "login") def expense_edit(request, id): expense = Expense.objects.get(pk=id) context = { 'expense': expense, 'values': expense, } if request.method == 'GET': return render(request, 'expenses/edit_expense.html', context) # if request.method == "POST": else: messages.add_message(request, messages.INFO, 'Handling post form') return render(request, 'expenses/edit_expense.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('add-expense', views.add_expense, name="add-expense"), path('edit-expense/<int:id>', views.expense_edit, name="edit-expense"), ] edit_expense.html {% extends 'base.html' %} {% block content %} <div class="container mt-4"> <h2>Edit Expense</h2> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="{% url 'index' %}">Expenses</a></li> <li … -
Select2 Django Multi-Select Select a valid choice. x is not one of the available choices
I currently am making my first form with Select2 that I am tying into a django form it throws me this error every time more than one item is selected Select a valid choice. ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'] is not one of the available choices. This is the exact error I get if I choose all options but if I choose two options I will only receive those 2 numbers in the list My current code for this form regarding this issue is as follows: forms.py class Meta: model = WebOrder fields = [ ... "overdenture_connections", ... ] ... OVERDENTURE_CONNECTIONS = (('2','2'),('3','3'), ('4','4'),('5','5'),('6','6'),('7','7'),('8','8'),('9','9'), ('10','10'),('11','11'),('12','12'),('13','13'),('14','14'), ('15','15'),('18','18'),('19','19'),('20','20'),('21','21'), ('22','22'),('23','23'),('24','24'),('25','25'),('26','26'), ('27','27'),('28','28'),('29','29'),('30','30'),('31','31')) overdenture_connections= forms.ChoiceField(choices=OVERDENTURE_CONNECTIONS,widget=s2forms.Select2MultipleWidget) models.py class WebOrder(models.Model): ... overdenture_connections = models.CharField(db_column="OverdentureConnections", max_length=128, null=True, blank=True) ... class Meta: db_table = 'WebOrders' htmlfile.html <form> {% csrf_token %} ... <div class="grid-x grid-padding-x" > <div class="cell small-12"> {{form.overdenture_connections.label_tag}}{{form.overdenture_connections}} </div> </div> ... </form> -
Removing labels from dynamic django crispy formset
I have a dynamic formset to allow users to add a variable number of entries. This is implemented using https://github.com/elo80ka/django-dynamic-formset, and outlined below This currently displays as:  And when a user adds another row as:  I would however like the labels to either be 1. removed entirely, or 2. only be present for the first row or 3. be within the entry box as opposed to above it? models.py class Patient(TimeStampedModel): # get a unique id for each patient - could perhaps use this as slug if needed patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) class PastMed(TimeStampedModel): medication = models.CharField( “Medication”, max_length=20, default=‘unspecified’) dose = models.IntegerField("Dose (mg)", default=0) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) forms.py PastmedFormSet = inlineformset_factory( Patient, PastMed, fields=(“medication”, “dose”), extra=1) views.py class PatientAddView(LoginRequiredMixin,TemplateView): model = Patient template_name = "../templates/add.html" def get(self, *args, **kwargs): pastmed_formset = PastmedFormSet(queryset=PastMed.objects.none()) return self.render_to_response({'pastmed_formset': pastmed_formset}) add.html <script type="text/javascript" src="{% static 'js/jquery/dist/jquery.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/jquery.formset.js' %}"></script> <script type="text/javascript"> $(function() { $('#pastmeds_table tbody tr').formset({ prefix: 'pastmed_set' }) }); </script> <div class="form-group"> <table id="pastmeds_table" border="0" cellpadding="0" cellspacing="5"> <tbody> {% for form in pastmed_formset %} <tr id="{{ form.prefix }}-row"></tr> <td> {% for fld in form.hidden_fields %}{{ fld }}{% endfor %} {% if form.instance.pk %}{{ form.DELETE … -
Getting KeyError when using request.session['role_type'] in django 3.0
urls.py urlpatterns = [ re_path(r'^jobs/week/$',login_required(JobWeekView.as_view()),name="job_week"), ] views.py class JobWeekView(View): def get(self, request): if request.session['role_type'] in [ClientUserRole.ROLE_JOBWORKER,ClientUserRole.ROLE_JOBWORKER_WITH_DOCS]: return redirect('crm:job_view') But I am getting error KeyError: 'role_type' . Here is full error traceback.Anyone pls help help me where I am wrong Traceback (most recent call last): File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/home/harika/lightdegreerespos/mcam/server/mcam/crm/views.py", line 9569, in get x = self.request.session['role_type'] File "/home/harika/lightdegree/lib/python3.7/site-packages/django/contrib/sessions/backends/base.py", line 64, in __getitem__ return self._session[key] KeyError: 'role_type' -
Delete an image completely in django gets SuspiciousFileOperation
I have a model with an ImageField and when the user changes the image I want the old image to be deleted from the media/ folder, it's from another answer on stackoverflow: def _delete_file(path): """ Deletes file from filesystem. """ if os.path.isfile(path): os.remove(path) @receiver(models.signals.post_delete, sender=User) def delete_file(sender, instance, *args, **kwargs): """ Deletes image files on `post_delete` """ if instance.image: _delete_file(instance.image.path) I also tried to delete old_image when new form is submitted: old_image = user.image old_image.delete(save=False) and this: fss = FileSystemStorage() fss.delete(old_image.url) I get SuspiciousFileOperation at / The joined path is located outside of the base path component How can I remove the image completely? -
django: no primary or candidate keys in the referenced table 'tcReports_global_users' that match the referencing column list in the foreign key 'fk
Here's my models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import UserManager class TcreportsGlobalApps(models.Model): appid = models.AutoField(db_column='appID', primary_key=True) # Field name made lowercase. path = models.TextField() name = models.TextField() stableversion = models.CharField(db_column='stableVersion', max_length=10) # Field name made lowercase. devversion = models.CharField(db_column='devVersion', max_length=10) # Field name made lowercase. apptype = models.CharField(db_column='appType', max_length=100, blank=True, null=True) # Field name made lowercase. appdepartment = models.CharField(db_column='appDepartment', max_length=100, blank=True, null=True) # Field name made lowercase. islive = models.BooleanField(db_column='isLive', blank=True, null=True) # Field name made lowercase. description = models.TextField(blank=True, null=True) class Meta: db_table = 'tcReports_global_apps' class TcreportsGlobalLog(models.Model): id = models.BigAutoField(primary_key=True) log = models.TextField() created_at = models.DateTimeField() class Meta: db_table = 'tcReports_global_log' class TcreportsGlobalPermissions(models.Model): appid = models.AutoField(db_column='appID', blank=True, primary_key=True) # Field name made lowercase. userid = models.IntegerField(db_column='userID', blank=True, null=True) # Field name made lowercase. permissions = models.BooleanField(blank=True, null=True) class Meta: db_table = 'tcReports_global_permissions' class CustomUserManager(UserManager): def create_user(self, username, password=None): if not username: raise ValueError('Users must have an username') user = self.model(username=username) user.set_password(password) user.save(using=self._db) user.userid = user.pk user.save() return user def create_superuser(self, username, password, email=None): user = self.create_user( username=username, password=password, ) user.is_superuser = True user.save(using=self._db) user.userid = user.pk return user class TcreportsGlobalUsers(AbstractBaseUser): userid = models.AutoField(db_column='userID', blank=True, primary_key=True) # Field name made lowercase. username = models.CharField(max_length=100, blank=True, …