Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django nested regroup
I use Django 2.2.12 I have three models: RiskRating is pointing to RiskType which is pointing to RiskCategory with ForeignKeys. class RiskCategory(models.Model): name = models.CharField(max_length=400, blank=True) class RiskType(models.Model): riskcategory = models.ForeignKey(RiskCategory, on_delete=models.CASCADE, related_name="risksforcategory") class RiskRating(models.Model): risktype = models.ForeignKey(RiskType, on_delete=models.CASCADE, related_name="ratingsforrisk") In my view: riskratings = Riskrating.objects.all() I would like to display RiskRating grouped by RiskCategories, i.e. I would like to do a nested regroup as following: {% regroup riskratings by risktype.riskcategory as ratingsbycategory %} How can I do that ? Thanks a lot -
django encrypt files before storage
So I want to encrypt files before storage in django and decrypt them upon retireval. I am using a custom storage class for the same and the cryptography module. import hashlib import os import uuid import django.core.files.storage as storage from cryptography.fernet import Fernet from django.conf import settings from django.core.files import File class DefaultStorage(storage.FileSystemStorage): def __init__(self): super(DefaultStorage, self).__init__() self.encryptor = Fernet(settings.ENCRYPTION_KEY) def _save(self, name, content): encrypted = self.encryptor.encrypt(content.file.read()) content.file.write(encrypted) print(content.file.read() == encrypted) return super(DefaultStorage, self)._save(name, content) def _open(self, name, mode='rb'): encrypted = open(self.path(name), mode).read() return File(self.encryptor.decrypt(encrypted)) def get_available_name(self, name, max_length=None): # we return a hash of the file given, # in case we miss out on uniqueness, django calls # the get_alternative_name method dir_name, file_name = os.path.split(name) file_root, file_ext = os.path.splitext(file_name) file_root = hashlib.md5(file_root.encode()).hexdigest() name = os.path.join(dir_name, file_root + file_ext) return super(DefaultStorage, self).get_available_name(name, max_length) def get_alternative_name(self, file_root, file_ext): # we insert a random uuid hex string into the given # file name before returning the same back return '%s%s%s' % (file_root, uuid.uuid4().hex, file_ext) I am overwritting the _save and _open methods here, but the class doesn't work as expected. Under the save method, I want to encrypt the contents of the file, but when I print this print(content.file.read() == encrypted) It … -
Attribute Error in Django,when using IMDbpy
I am trying to use the IMDbpy library in my django projects,but it raises an Attribute Error. I tried all the solutions available on the internet,but none seem to work,could you please help me with this? The Error: moviesDB = imdb.IMDb() AttributeError: module 'imdb' has no attribute 'IMDb' The code: import imdb moviesDB = imdb.IMDb() movies= moviesDB.search_movie('whatever_movie') id = movies[0].getID() movie = moviesDB.get_movie(id) print(movie) title=movie['title'] rating = movie['rating'] cover=movie['cover url'] print(title,rating,cover) I have been scratching my head the entire day,due to this error,I'm kinda new to this,so please help! I tried reinstalling the imdbpy library,pip3 installed it,renamed it but nothing seems to be working. The code is working in external files,but in the views.py in django,it just doesnt seem to work please help! -
Parts of CSS styles are not loaded when routing between React Components until refreshing the page?
I build a Django project, and using Webpack to create the React bundle rendered in Django template body. I tried to load CSS files either in Django template or in App.js but same results. When I switch between React pages parts of the CSS is not loaded, but when I refresh the page all the CSS and JS files are loaded. {% load i18n %} {% load static %} {% load render_bundle from webpack_loader %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="OneUIUX HTML website template by Maxartkiller. Bootstrap UI UX, Bootstrap theme, Bootstrap HTML, Bootstrap template, Bootstrap website, multipurpose website template. get bootstrap template, website"> <meta name="author" content="Maxartkiller"> <link rel="stylesheet" href="{% static 'css/swiper.min.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'css/newstyle.css' %}"> <script src="{% static 'js/jquery-3.3.1.min.js' %}"></script> <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/jquery.cookie.js' %}"></script> <script src="{% static 'js/masonry.pkgd.min.js' %}"}></script> <script src="{% static 'js/swiper.min.js' %}"></script> <script src="{% static 'js/main.js' %}"></script> </head> <body> <div id='reactify-django-ui'> {% render_bundle 'main' %} </div> </body> </html> And my Webpack config file const path = require("path"); const host = process.env.HOST || 'localhost'; const devPort = 3000 var webpack = require('webpack'); … -
How to securely store OAuth2 access and refresh tokens in Django
I'm trying to implement the Azure AD OAuth authentication for our Django app and I would be doing that with Azure AD as an OAuth provider. So now I wanted to know how securely we can store the OAuth access/refresh tokens in the DB that we receive from Azure AD or any OAuth provider. I want to store the user's access token in DB because we have a feature in our web app where users can send an email with their email ID and we have a periodic job that runs every half an hour and it's gonna fetch user's mails based on a specific subject line. This we're gonna do with the help of Microsoft's Graph API and in order to call Microsoft Graph API, the web app should store the user's access token may be in the DB. But my concern is once we receive the access and refresh token, it shouldn't be accessed by anyone once we store it in the DB. So how securely or in an encrypted way we can store the OAuth2 access tokens in Django. I have gone through a few articles, QnA, and forums on this concern but wanted to hear from … -
Django field that can be either IntegerField or DecimalField
In one of my Django model, I have a field that can be either an IntegerField or a DecimalField based on the user. When the value of the record is an integer, the form should only display/edit it without trailing digits. When the value of the record has decimals, all decimals should be displayed/edit on the form. I have tried defining this field as a DecimalField and play with the form, but the challenge is that I use django-crispy-forms to render my forms so I cannot use the floatformat filter in my template. As a result, 5 as an integer, for instance, is displayed as 5.00000000 in my form. Is there a way around this? -
Django - models design issue
I'm struggling designing my models on Django (using PostgreSQL). The goal is to create a system of groups where a user can arrange items in them. An item must be unique in my database. I created a user item group (UserItemGroup) that belong to a user (User). Then, I created an item model (UserItem). This model represents an item which the user can arrange into groups. Items can belong to multiple groups at the same time but must be unique! I used 2 ForeignKey in the UserItem model but it seems very weird... See below: class UserItemGroup(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False, null=False) slug = models.CharField(max_length=200, blank=False, null=False) class UserItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(UserItemGroup, on_delete=models.CASCADE) Items can be arranged like so: user_x ------group_a ------------item_1 ------------item_2 ------------item_3 ------group_b ------------item_1 ------------item_4 Hope I'm clear, thanks in advance for help. -
Why does response content change when I write to a file?
I'm trying to work with XML obtained from http://video.google.com/timedtext that contains closed caption data of YouTube videos. As I'm fairly new to both Django and XML, I tried to directly output the XML - i.e. the response's content to the webpage - as the first step, by passing it directly in the context while rendering it as a 'p' element in the template. This worked fine. The XML displayed as a byte string. I then used the Python module 'xmltodict' to convert the XML to a more workable format. This worked too, but I got an error message: [19/Jan/2021 17:48:07] "GET /_hpvE1jjdxY/ HTTP/1.1" 200 2744 [19/Jan/2021 17:48:09] "GET /favicon.ico HTTP/1.1" 301 0 Internal Server Error: /favicon.ico/ Traceback (most recent call last): File "D:\Dev\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Dev\Project\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Dev\Project\src\lt_player\views.py", line 26, in player parsed_cc_data = xmltodict.parse(cc_data)['transcript']['text'] File "D:\Dev\Project\venv\lib\site-packages\xmltodict.py", line 327, in parse parser.Parse(xml_input, True) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 2, column 11 [19/Jan/2021 17:48:10] "GET /favicon.ico/ HTTP/1.1" 500 75167 I looked up why this error could've popped up and I noticed some reasons such as the placing of a misplaced '&' character or some other … -
Django Conflicts Error When use ManyToManyField
I have two model like given in bellow; class userPages(models.Model): page_name=models.CharField(max_length=30) parent_id=models.IntegerField(blank=True, null=True) def __str__(self): return self.page_name class userProfile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,related_name="profile") user_pages=models.ManyToManyField(userPages) def __str__(self): return self.user.username When I want to add data like this; . . . p1 = userPages(page_name='Login') p1.save() user_profile = userProfile(user=new_user) user_profile.save() user_profile.user_pages.add(p1) I got "syntax error at or near "ON"". LINE 1: ... ("userprofile_id", "userpages_id") VALUES (1, 1) ON CONFLIC... -
Django Paginator - all pages objects action
Folks, I'm currently developing a web application using Django and need to replicate a feature that currently exists in the admin section of Django. Namely, there is an option to select objects on all pages and take same action on all these. I have a Paginator on my page, but not sure what would be the best way to tell the server I want to perform an action on all objects, not only these being currently shown. Please advise! Cheers! -
University Appointment Based System: Django (Backend,sqlite), ReactJS(Frontend)
Hi guys im a university student embarking on a project and need some initial guidance as to the appropriate course of action to take. Basically Im creating an appointment based systems which allows students to book appointments with the teacher. The application must be able to consolidate both their timetables and only highlight the days when both the teacher and student are "free" so that the student can book the consultation slot. Im planing to use Django for backend and reactJS for front end. I just seek initial opinion/direction of as to how i can begin by constructing this system and more importantly what algorithm that I can use to consolidate the timetables of both the teacher and the student so that the system only highlights the duration and date where both parties are free Will greatly appreciate any form of feedback you can provide. Thank You -
Django contact e-mail form does not render/show up in home.html
I have a forms.py - file in the "portfolio" - app with the following content: from django import forms class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) # From docs: https://docs.djangoproject.com/en/3.1/topics/forms/#more-on-fields cc_myself = forms.BooleanField(required=False) In my views.py I have the following relevant part: from .forms import ContactForm # import module from same parent folder as this script import General.Misc.general_tools as tools # custom module to import special-print function def contactView(request, admin_email='blaa@blaaa.com'): if request.method == 'GET': sendemail_form = ContactForm() else: sendemail_form = ContactForm(request.POST) if sendemail_form.is_valid(): # * Retrieve data and set up e-mail (subject, sender, message) subject = sendemail_form.cleaned_data['subject'] from_email = sendemail_form.cleaned_data['from_email'] message = sendemail_form.cleaned_data['message'] # From docs: https://docs.djangoproject.com/en/3.1/topics/forms/#more-on-fields cc_myself = sendemail_form.cleaned_data['cc_myself'] recipients = [admin_email] if cc_myself: recipients.append(from_email) # * Send email try: # General Django docs: https://docs.djangoproject.com/en/3.1/topics/email/#send-mail # NOTE on passed list as 4th parameter: recipient-list ## i) How to set up an email contact form - docs: https://learndjango.com/tutorials/django-email-contact-form send_mail(subject, message, from_email, recipients, fail_silently=False) # * Exceptions * # # NOTE on scope: security except BadHeaderError: return HttpResponse('Invalid header found.') # General exception to be printed out except Exception as e: tools.except_print(f"ERROR:\n{e}") # Return success (if this code is reached) return redirect('success') # Send the completed … -
how to create a multiple database in app? [closed]
We have a research project in school which is a website that store all student informations. And we are currently using django. We would like to make it login by campus location (We need to create an app for many campuses ). What should we do to make the app have a different data inside and will be base by the campus location of the user that login? -
Why is it throwing an Django- Reverse query name SystemCheckError?
I am a newbie to Django, While running the django application using python3 manage.py runserver Because of the way I have created the model I am getting an error like django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: database.LeadsStatus.company_id: (fields.E305) Reverse query name for 'LeadsStatus.company_id' clashes with reverse query name for 'LeadsStatus.companies'. HINT: Add or change a related_name argument to the definition for 'LeadsStatus.company_id' or 'LeadsStatus.companies'. database.Users.id: (fields.E007) Primary keys must not have null=True. HINT: Set null=False on the field, or remove primary_key=True argument. System check identified 2 issues (0 silenced). This is how I've created model. class LeadsStatus(models.Model): id = models.IntegerField(primary_key=True, auto_created=True) company_id = models.ForeignKey('Companies', null=False, db_index=True, on_delete=models.CASCADE) status = models.CharField(max_length=120) users_id = models.IntegerField() assign_date = models.DateTimeField() companies = models.OneToOneField('Companies', on_delete=models.CASCADE) I believe the error might be because of the way I have created a OneToOneField. How do I solve this error. Please help me understand. Thanks -
Unit testing in Django for CreateView
I have a CreateView with which I create new blog posts, I want to test it in order to check if everything is ok but something is wrong with my test and I can't understand what exactly. it gives me 2 errors, for the first method I get this error: Traceback (most recent call last): File "C:\Users\Bularu Lilian\Desktop\EcoMon\blog\tests\test_views.py", line 73, in test_post_create_view_GET self.assertEquals(response.status_code, 200) AssertionError: 302 != 200 and for the second one is this error: File "C:\Users\Bularu Lilian\Desktop\EcoMon\blog\tests\test_views.py", line 78, in test_post_create_view_POST_success post = Post.objects.get(title=self.post['title']) File "C:\Users\Bularu Lilian\Desktop\Environments\ecomon\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Bularu Lilian\Desktop\Environments\ecomon\lib\site-packages\django\db\models\query.py", line 429, in get raise self.model.DoesNotExist( blog.models.Post.DoesNotExist: Post matching query does not exist. This is my Test class: class TestPostCreateViews(BaseTest): def test_post_create_view_GET(self): response = self.client.get(self.add_post_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'blog/add_post.html') def test_post_create_view_POST_success(self): response = self.client.post(self.add_post_url, self.post, author=self.user, format='text/html') post = Post.objects.get(title=self.post['title']) self.assertEquals(response.status_code, 302) self.assertEquals(post.title, 'test post') my CreateView: class PostCreateView(LoginRequiredMixin, IsSuperuserOrStaffMixin, CreateView): template_name = 'blog/add_post.html' form_class = PostCreateForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) my url path: path('new/post/', PostCreateView.as_view(), name='add-post'), my form: class PostCreateForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(), max_length=200) content = forms.CharField(widget=forms.Textarea(attrs={'rows': 25, 'cols': 50})) class Meta: model = Post exclude = ['author', 'slug', 'published_date', 'updated_date'] and my model: class … -
How to redirect to previous page in custom DeleteView?
I have the following custom DeleteView: class CarDeleteView(LoginRequiredMixin, DeleteView): model = Car context_object_name = 'car' template_name = 'cars/car_confirm_delete.html' success_message = "%(name)s is pending removal" def get_success_url(self): return reverse('car-list') def delete(self, request, *args, **kwargs): self.object = self.get_object() name = self.object.name owner = self.object.owner if owner != self.request.user: messages.error(request, f'You don't have permissions to remove {name}') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # DO Stuff return redirect(reverse('car-list')) I'm trying to redirect to previous entry point when user isn't the owner (so he can't delete). But HttpResponseRedirect(request.META.get('HTTP_REFERER')) gives me the URL of the current page (car_confirm_delete.html) and not the previous one. How can I make it go to previous one? -
Deleting a Foreign Key model?
I'm trying to delete a Foreign Key model, however after I delete it and try and save the model I get a ValueError: save() prohibited to prevent data loss due to unsaved related object 'orderassigned'. What I'm trying to achieve is delete the orderassigned Foreign Key model itself. Below is this deletion code in views.py: ordertocancel = Order.objects.get(orderid=orderid, orderassigned__user=self.request.user) ordertocancel.orderassigned.delete() # This references a Foreign Key ordertocancel.status = "ordered" ordertocancel.save() This is the Foreign Key: orderassigned = models.ForeignKey('Assigned', null=True, blank=True, on_delete=SET_DEFAULT, default=None) Any help would be greatly appreciated, thank you! -
I'm getting ModuleNotFoundError: No module named '<anyproject>'
To generate some fake data i used "djnago_populator" as fakers.py and when I run code getting something related to "DJANGO_SETTINGS_MODULE". I searched in stackoverflow regarding this and saw there to use "set DJANGO_SETTINGS_MODULE=admin.settings" and didnt generated fakedata but i ran "set DJANGO_SETTINGS_MODULE=ecom.settings" where ecom is my project name. and so this generated fake data. and now i'm able to runserver command and able to visit localhost. but when I go admin site below error is getting Error at /admin/ Incorrect padding Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 2.1.7 Exception Type: Error Exception Value: Incorrect padding Exception Location: G:\Install\Python 3.8\lib\base64.py in b64decode, line 87 Python Executable: G:\Install\Python 3.8\python.exe Python Version: 3.8.2 Python Path: ['E:\\Workspace\\Atom_Wrksc\\django\\ecom', 'E:\\Workspace\\Atom_Wrksc\\django\\ecom', 'C:\\Program Files\\JetBrains\\PyCharm ' '2020.3.2\\plugins\\python\\helpers\\pycharm_display', 'G:\\Install\\Python 3.8\\python38.zip', 'G:\\Install\\Python 3.8\\DLLs', 'G:\\Install\\Python 3.8\\lib', 'G:\\Install\\Python 3.8', 'G:\\Install\\Python 3.8\\lib\\site-packages', 'G:\\Install\\Python 3.8\\lib\\site-packages\\django_misaka-0.2.1-py3.8.egg', 'G:\\Install\\Python 3.8\\lib\\site-packages\\pygments-2.7.3-py3.8.egg', 'G:\\Install\\Python ' '3.8\\lib\\site-packages\\houdini.py-0.1.0-py3.8-win32.egg', 'C:\\Program Files\\JetBrains\\PyCharm ' '2020.3.2\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Tue, 19 Jan 2021 10:53:17 +0000 Traceback Switch to copy-and-paste view G:\Install\Python 3.8\lib\site-packages\django\contrib\sessions\backends\base.py in _get_session return self._session_cache ... ▶ Local vars During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: G:\Install\Python 3.8\lib\site-packages\django\core\handlers\exception.py in inner i uninstalled django and installed again and tested. but samee error i'm getting. I also started a … -
how to add field to userchangeform?
I have extended the abstract user class but the fields I added is phone number but this field did not appear in user change form how would I add this field to user change form ? -
Django: Modify database object on click using a ListView
I have a ListView that I use to display a list of products. On the right of every product/row, I want a "archive" button that, when clicked-on, will change the "archived" field of the product in the database from True to False. I'd like to do this using only Django and I think this is possible but I have a hard time finding out how. I'm trying to do it using a form, but I don't know how I can send the pk of the current object (in the loop) back to the view to make the change. Here's my template (the relevant part): {% for product in product_list %} <tr> <th scope="row">{{ product.pk }}</th> <td> <a href="{% url 'accounts:products_edit' pk=product.pk %}"> {{ product.title }}</a > </td> <td class="d-flex justify-content-between"> <form action="" method="POST"> {% csrf_token %} <button type="submit"><i class="fas fa-trash" style="color: grey"></i></button> </form> </td> </tr> {% endfor %} Here's my view: class ProductsListView(ListView, LoginRequiredMixin): template_name = "accounts/products/products_list.html" model = Product def get_context_data(self, **kwargs): # ... return context def post(self, request, *args, **kwargs): # modify object from pk here return HttpResponseRedirect(self.request.path_info) I've seen several post with similar situations, but didn't find a solution that works completely for my case. Any help … -
Enumeration types in Django
I am trying to use enumeration types in Django but fell like I am not doing the right thing... I am building an ebay-like webapp where my Listings are saved in the database with a .category attribute. class Listing(models.Model): class Category(models.TextChoices): TOY = "TO", _("Toys") FASHION = "FA", _("Fashion") ELECTRONICS = "EL", _("Electronics") HOME = "HO", _("Home") OTHERS = "OT", _("Others") title = models.CharField(max_length=64) category = models.CharField( max_length=2, choices=Category.choices, default=Category.OTHERS, ) I referred to Django's documentation for the use of Enumeration types but there are some grey areas, as far as my understanding goes. When I render a template to display a Listing, how do I pass the string value associated with the .category of my Listing? I tried something like this: return render(request, "auctions/listing.html", { "listing": listing, "category": Listing.Category[listing.category].label, }) Or can I access it through the "listing" variable? What I would like is for the browser to display Home for a listing with listing.category = "HO". -
Django test database objects
I created custom database migration for creating new user in database like below: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("core", "0179_merge_20210104_1353"), ] db_user_name = 'database_new_user' db_password = 'database_new_user_password' create_db_user = f""" DO $$ BEGIN CREATE ROLE {db_user_name} WITH NOSUPERUSER NOCREATEDB NOCREATEROLE LOGIN PASSWORD '{db_password}'; EXCEPTION WHEN DUPLICATE_OBJECT THEN RAISE NOTICE 'not creating {db_user_name} -- it already exists'; END $$ """ delete_db_user = f""" DROP ROLE IF EXISTS {db_user_name}; """ grant_read_permissions = f""" DO $$ BEGIN GRANT USAGE ON SCHEMA public TO {db_user_name}; GRANT SELECT ON ALL TABLES IN SCHEMA public TO {db_user_name}; END $$ """ revoke_read_permissions = f""" REVOKE USAGE ON SCHEMA public FROM {db_user_name}; REVOKE SELECT on ALL TABLES IN SCHEMA PUBLIC FROM {db_user_name}; """ operations = [ migrations.RunSQL(create_db_user, delete_db_user), migrations.RunSQL(grant_read_permissions, revoke_read_permissions), ] This migration essentially creates new user in database and grant SELECT for all tables. Reverse options revoke permissions and drop user accordingly. Migration is deployed and working as expected. Problem is that when I try to revert (in local machine) this migration by typing: python manage.py migrate core 0179_merge_20210104_1353 Django says: django.db.utils.InternalError: role "database_new_user" cannot be dropped because some objects depend on it I inspected database and saw that django created test_database (when … -
NoReverseMatch error while adding slug in url path
i'm building a blog app in django. In the blog list page after preview of each button i've added Read More link to read the blog in details. I'm trying to add slug in the blog detail page but it gives the NoReverse error. I get this error: This is my urls.py of blog_app and i've included in main project url.py: app_name = 'blog_app' urlpatterns = [ path('', views.BlogList.as_view(), name='blog_list'), path('write/', views.CreateBlog.as_view(), name='create_blog'), path('details/<slug:slug>/', views.blog_details, name='blog_details'), ] This is the views.py: def blog_list(request): return render(request, 'blog_app/blog_list.html', context={}) class BlogList(ListView): context_object_name = 'blogs' model = Blog template_name ='blog_app/blog_list.html' class CreateBlog(LoginRequiredMixin, CreateView): model = Blog template_name = 'blog_app/create_blog.html' fields = ('blog_title', 'blog_content', 'blog_image') def form_valid(self, form): blog_object = form.save(commit=False) blog_object.author = self.request.user title = blog_object.blog_title blog_object.slug = title.replace(' ', '-') + '-' + str(uuid.uuid4()) blog_object.save() return HttpResponseRedirect(reverse('index')) def blog_details(request, slug): blog = Blog.objects.get(slug=slug) return render(request, 'blog_app/blog_details.html', context={'blog':blog}) This is models.py: class Blog(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author') blog_title = models.CharField(max_length=264, verbose_name='Assign a Title') slug = models.SlugField(max_length=264, unique=True) blog_content = models.TextField(verbose_name="What's on your Mind") blog_image =models.ImageField(upload_to='blog_images', verbose_name="Blog Image") published_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-published_date'] def __str__(self): return self.blog_title This is blog_details.html: {% extends 'base.html' %} {% block title … -
Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4 error in python django
You see I am getting this incredibly weird error related to the no of characters in a string I guess. I am a bit new to django and I have never see such an weird error. I checked a few threads and according to that this is about encoding and decoding something which I really do not know how to resolve. Here is my code: Request Method: GET Request URL: http://127.0.0.1:8000/profiles/myprofile/ Django Version: 2.1.5 Python Version: 3.9.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts', 'profiles'] 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\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\sessions\backends\base.py" in _get_session 190. return self._session_cache During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\PROJECTS\social\src\profiles\views.py" in my_profile_view 6. profile = Profile.objects.get(user=request.user) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py" in get 390. clone = self.filter(*args, **kwargs) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py" in filter 844. return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py" in _filter_or_exclude 862. clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py" in add_q 1263. clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py" … -
Django register user
Hi i want to connect normal user using UserCreationForm and my own Creation when i post it with button my postgre auth_user and auth_users_register nthing add to database when i click on button my code: forms.py class RegisterForm(ModelForm): class Meta: model = Register fields = ['date_of_birth', 'image_add'] widgets = { 'date_of_birth': DateInput(attrs={'type': 'date'}) } class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] models.py def validate_image(image_add): max_height = 250 max_width = 250 if 250 < max_width or 250 < max_height: raise ValidationError("Height or Width is larger than what is allowed") class Register(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE) date_of_birth = models.DateField( max_length=8, verbose_name="date of birth") image_add = models.ImageField( upload_to="avatars", verbose_name="avatar", validators=[validate_image]) views.py class RegisterPageView(View): def get(self, request): if request.user.is_authenticated: return redirect('/') user_form = CreateUserForm(request.POST) register_form = RegisterForm(request.POST) return render(request, 'register.html', {'user_form': user_form, 'register_form': register_form}) def post(self, request): if request.method == 'POST': user_form = CreateUserForm(request.POST) register_form = RegisterForm(request.POST) if user_form.is_valid() and register_form.is_valid(): user_form.save() register_form.save(commit=False) user = user_form.cleaned_data.get('username') messages.success( request, 'Your account has been registered' + user) return redirect('login') user_form = CreateUserForm() register_form = RegisterForm() context = {'user_form': user_form, 'register_form': register_form} return render(request, 'register.html', context)