Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i am submitting a form on page 1,and want to displaydetailed information with the submitted info form page 1 to page 2 how to do that?
I am on page 1,i input a word into a form and hit submit after that i want to be taken to a new page and display information from a database table with the submitted information as key.How do i do that? Below is the code that i tried. VIEWS.PYfile def Professional_Development(request): resources=TheProfessionalResources.objects.order_by('Field') form=forms.FieldForm() user_dit={'user':resources,'form':form} if request.method=='POST': form=forms.FieldForm(request.POST) if form.is_valid(): variable=form.cleaned_data['name'] print(variable) ace=TheProfessionalResources.objects.filter(Field=variable) resources=TheProfessionalResources.objects.order_by('Field') print("EXECUTING FORM") user_dict={'user':resources,'form':form,'ACE':ace,'VARIABLE':variable} return render(request,'first_app/Resources_Professional.html',context=user_dict) print("EXECUTKING PAGE") return render(request,'first_app/Professional_Development.html',context=user_dit) 2nd function in views.py file def Resources_Professional(request): resources=TheProfessionalResources.objects.order_by('Field') form=TheProfessionalResourcesForm() user_dict={'user':resources,'form':form} return render(request,'first_app/Resources_Professional.html',context=user_dict) HTML FILE <!DOCTYPE html> {% extends "first_app/basic_skeleton.html" %} {%block body_block%} <H1>Please sign up here</H1> {%if user%} <ol> {%for person in user%} <li>{{person.Field}}</li> </ol> {%endfor%} {%endif%} <form method="post"> {{form.as_p}} {% csrf_token %} <input type="submit" value="submit"> </form> <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <H1>Please sign up here</H1> {{VARIABLE}} {%if ACE%} <ol> {%for person in ACE%} <li>{{person.Title}}</li> </ol> {%endfor%} {%endif%} {{form.as_p}} </body> </html> URLS.PY in project folder from django.urls import path from first_app import views urlpatterns = [ url(r'^basic_skeleton/',views.basic_skeleton,name='basic_skeleton'), url(r'^Professional_Development/',views.Professional_Development,name='Professional_Development'), url(r'^Personal_Development/',views.Personal_Development,name='Personal_Development'), url(r'^Financial_Development/',views.Financial_Development,name='Financial_Development'), url(r'^first_app/',include('first_app.url')), url(r'^$',views.index,name='index'), url(r'^Resources_Professional/$',views.Resources_Professional,name='Resources_Professional'), path('admin/', admin.site.urls), ] URLS .py file in applications folder from django.conf.urls import url,include from first_app import views app_name='first_app' urlpatterns=[ url(r'^$',views.basic_skeleton,name='basic_skeleton'), url(r'^Personal_Development/$',views.Personal_Development,name='Personal_Development'), url(r'^Financial_Development/$',views.Financial_Development,name='Financial_Development'), url(r'^Professional_Development/$',views.Professional_Development,name='Professional_Development'), url(r'^Resources_Professional/$',views.Resources_Professional,name='Resources_Professional'), ] Or you could … -
How to count products in Django template?
I am getting products according to the category, and I want to display product after the count in this format Showing Products 1-24 of 10 Result, my products are displaying on a category basis, please let me know how I can display the product after the count in that category. it meand if a category have 20 products then it will display 20 product n my product list page. here is my model.py file code... def SubCategorySlugListAPIView(request, subcat_slug): subcategories = SubCategory.objects.all() product = Product.objects.all() if subcat_slug: subcategory = get_object_or_404(SubCategory, subcat_slug=subcat_slug) productlist = product.filter(subcategory=subcategory) paginator = Paginator(productlist, 12) page_number = request.GET.get('page') product = paginator.get_page(page_number) template_name = 'mainpage/cat-products.html' context = {'product': product, 'subcategories': subcategories, 'subcategory': subcategory} return render(request, template_name, context) and here is my cat-products.html file... <div class="search-count"> <h5>Showing Products {{product.count}}</h5> </div> nothing displaying here, plese let me know how i can display the product count here. -
Matching query does not exist when update view is called in django
I have a custom user model from AbstractBaseUser and BaseUserManager. The user model is extended to a model called Employee. The employee model is related with(Foreignkey) two other model named WorkExperience and education. A single template form is designed with Employee, WorkExperience and Education modelform. models.py: class Employee(models.Model): """ Create employee attributes """ employee_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) e_id = models.IntegerField(unique=True, null=True) first_name = models.CharField(max_length=128, null=True) last_name = models.CharField(max_length=128, null=True) gender_choices = ( ('Male', 'Male'), ('Female', 'Female'), ) ...... @receiver(post_save, sender=UserProfile) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Employee.objects.create(employee_user=instance, email=instance.email) instance.employee.save() class WorkExperience(models.Model): """ Stores employee previous work experiences """ employee_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) employee = models.ForeignKey('Employee', related_name='we_employee', on_delete=models.CASCADE, null=True) previous_company_name = models.CharField(max_length=128, null=True) job_designation = models.CharField(max_length=128, null=True) from_date = models.DateField(null=True) to_date = models.DateField(null=True) job_description = models.CharField(max_length=256, null=True) class Education(models.Model): """ Stores employee education background """ employee_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) employee = models.ForeignKey('Employee', related_name='edu_employee', on_delete=models.CASCADE, null=True) institution_name = models.CharField(max_length=128, null=True) degree = models.CharField(max_length=128, null=True) passing_year = models.IntegerField(null=True) result = models.DecimalField(max_digits=5, decimal_places=2, null=True) I have a CreateView of this three models. I have three modelform. I implemented CRUD using this modelforms. My problem is in UpdateView. When I call UpdateView an error is showing stating WorkExperience matching query does … -
Django purchase function
I have model 'Order' that has two fields packs and item_quantity which will contain the stock of a particular item. And I have another model 'Purchase' that will allow a customer to select the number of item quantity and packs he/she would like to purchase in the form. Upon successful purchase, the quantity selected and packs should be subtracted from stock. I'm confused about what will go into my views.py function. models.py class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) shipping_method = models.CharField(max_length = 100, choices = method) packs = models.IntegerField(default='0', blank=True, null=True) item_quantity = models.IntegerField(default='0', blank=True, null=True) class Purchase(models.Model): purchase_quantity = models.IntegerField(default='0', blank=True, null=True) packs_quantity = models.IntegerField(default='0', blank=True, null=True) forms.py class InventoryForm(forms.ModelForm): class Meta: model = Inventory fields = ['purchase_quantity','packs_quantity'] views.py def purchase_success(request, pk): order = Order.objects.get(pk=pk) form = InventoryForm(request.POST or None) if request.method == 'POST': form.save() return redirect('/orderlist/') context = {'form':form, 'order':order, } return render(request, "purchase_success.html", context) -
How to filter product by Category wise in Django?
I am trying to filter according to the category but it's displaying all products on each category page, but I want filter according to the category page, please check my code and let me know how I can do it. here is my models.py file... class ProductFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Product fields = ['saleprice', 'title','veg_non','brand','supplement'] def SubCategorySlugListAPIView(request, subcat_slug): category = Category.objects.all() subcategories = SubCategory.objects.all() product = Product.objects.all() brands=Brand.objects.all() f = ProductFilter(request.GET, queryset=Product.objects.all()) supplement=Supplement.objects.all() featured=Product.objects.filter(featured=True).order_by('-created_at')[0:6] high = Product.objects.all().order_by('-saleprice') if subcat_slug: subcategory = get_object_or_404(SubCategory, subcat_slug=subcat_slug) productlist = product.filter(subcategory=subcategory) paginator = Paginator(productlist, 12) page_number = request.GET.get('page') product = paginator.get_page(page_number) template_name = 'mainpage/cat-products.html' context = {'product': product, 'subcategories': subcategories, 'subcategory': subcategory, 'category': category, 'featured':featured, 'high':high, 'brands':brands, 'supplement':supplement, 'filter':f} return render(request, template_name, context) i know there are need to merge these code f = ProductFilter(request.GET, queryset=Product.objects.all()) and this productlist = product.filter(subcategory=subcategory), using productlist i am getting product according to the category but when I do filter with filter then all products displaying on each category page. please merge both code and give me a correct solution for this. -
Why is my project no longer updating when I write new code?
I have a react / django app. The django side hosts a sqlite database, and react displays its content as the front end. When I run the command python manage.py runserver it is hosted locally on port 8000. My specific problem is manifest when I make edits to my React code. Even after refreshing the page and restarting the server, my front-end still remains as it was before I had edited the code and saved. I have no errors, or warnings. The only way I seem to be able to make it work is by pushing to GitHub and then cloning the repository on my system again. Would anyone be able to help me understand my dilemma? (Please let me know if my question is not to par with the guidelines of Stack Overflow, this is my first time) -
Pass an argument back and forth between two templates in Django
I have an app that returns information from an API request to the user based on their search request. Lets call this template A. They can then click on a link at the bottom of the page which brings them to a "More games like this" page, template B, that uses the same API, but a different endpoint to display similar games. I want the user to be able to then click on any of the suggested game's titles and be brought back to template A, without having to do a search, and the page display the relevant information for the game that was clicked on. I have tried using url routing, such as {% url 'vgSearch' result.name %} in the href of the link to return the user back to template A. Then pass the result.name argument back through the original template A view. But I'm totally stumped on how to have it "catch" that information and display the API results. This is what I have: views.py def search(request, name=None): if request.method == 'POST': raw_result = request.POST.get('search') space_result = raw_result.replace(' ', '-') dot_result = space_result.replace('.', ' ') qmark_result = dot_result.replace('?', ' ') back_result = qmark_result.replace('/', ' ') colon_result = … -
how can i add react into my Last Django project?
I wanna add react into my My Project and use items and models into React app so please help me, this is the link of my project : Project On gitHub -
Django Rest - Create User Password Hash
I'm trying to hash password, once created User and I'm using Django Rest. However i got an errors when trying to create it. { "non_field_errors": [ "Invalid data. Expected a dictionary, but got str." ] } My ModelViewset class UserViewset(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = (filters.DjangoFilterBackend,) def create(self, request, *args, **kwargs): user = User.objects.all() serializer = UserSerializer( user, make_password(request.data['password'])) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) # return HttpResponse(user) Thanks in advance... -
Django change server credential connection string?
I have a website that allows different organizations to sign up for an account. They have the ability to host their own SQL database. On my website, I have a MySQL Database Table that ties the user accounts to their respective MySQL hosts. I would like to be able to retrieve data from different database dynamically. So if User1 logs in, it will check with the table, that says retrieve data from MySqlHost1, User2 from MySqlHost2 etc and so on Is this possible? -
Django insert html code from function into template
I have a python function edited from this post, this creates an html code to display the images in a folder and it works fine ( I run it independently and copy paste the code in the template ) but now I want to make it inside Django so I create a templatetag but I only get plain text. from django import template import os from pathlib import Path register = template.Library() @register.simple_tag def generate_tree(): for file in os.listdir(path): rel = path + "/" + file if os.path.isdir(rel): html += """<button type="button" class="collapsible">%s</button>"""% (file) html +='<div class="content">' html += generate_tree(rel) html += '</div>' else: html +='<div class="col-md-4 d-flex align-items-stretch"> <picture>' x=str(rel)[38:] html += """<img src="{% static "%s" """% ('% s',x) html += """%} " class="lazy card-img-top" >""" html +='</picture> </div>' return html this is how i call my function in the html file: {% load static html_tags %} {% generate_tree 'path' %} and this is a portion of the plain text i get any ideas on how can I get the text like html code? -
Unable to serve static .gz file (MIME type ('application/octet-stream') is not executable)
I have a Django app, with a React frontend. I'm using compression-webpack-plugin to compress my js file. Here is my webpack configuration: const CompressionPlugin = require('compression-webpack-plugin'); module.exports = { entry: path.resolve(__dirname, "./assets/index.js"), output: { path: path.resolve(__dirname, "assets/bundles"), filename: "[name].js", publicPath: "/static/bundles/", }, plugins: [ new CompressionPlugin({ deleteOriginalAssets: true, }) ] }; This generates a file main.js.gz in my /static/bundles/ directory. In my Django settings, I've set the following: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' When I go to /, the following HTML page is served: {% load static %} <!DOCTYPE html> <html> <body> <div id="app"> <!-- React --> </div> </body> <script src="{% static "/bundles/main.js.gz" %}"></script> </html> On my dev environment, I can see main.js.gz being loaded But on my prod environment, the content-type changes to application/octet-stream And in my console I get the error: Refused to execute script from 'https://my-website.com/static/bundles/main.js.gz' because its MIME type ('application/octet-stream') is not executable, and strict MIME type checking is enabled. I'm not sure what steps I can take here for the file to be recognized as a .gz or .js file -
how to Fetch value of the radio button in django
i am making a quiz app this is my html file {% for question in questions %} <p>Q){{question.name}}</p> <input type="radio" value="1" name="{{question.id}}">{{question.option1}} <input type="radio" value="2" name="{{question.id}}">{{question.option2}} <input type="radio" value="3" name="{{question.id}}">{{question.option3}} <input type="radio" value="4" name="{{question.id}}">{{question.option4}} {% endfor %} in my database i have my correct answer store with the name correct_option this can be the code for checking the score {% if question.correct_option == ? %} {% score=1 %} {% endif %} for writing this i need to find out what did user select so what should be written in place of '?' -
django.http.request.RawPostDataException: You cannot access body after reading from request's data stream
I am making an API and i am gettings django.http.request.RawPostDataException: You cannot access body after reading from request's data stream this error I think You cant access data scnd time: Here is my code def get_posts(request): print('Called') print(request.body) data = json.loads(request.body) #Error here user = data['user'] print(user) user_profile = User.objects.all().get(username=user).profile posts = Post.objects.all().filter(user=user_profile) if len(posts) == 0: return JsonResponse({'last':True,'posts':None}) if len(posts) < 4: data_ = PostSerilizer(data=posts,many=True) return Response(data=data_) else: deliverd_count = data['deliverd_count'] posts_to_be_returned = posts[deliverd_count:deliverd_count+4] to_be_returned = { 'posts':posts_to_be_returned, 'last':False, } return JsonResponse(to_be_returned) How can i access data sceond time Here are the reasons for the error but i dont know how to solve When i am using api_view decorator -- which is necessary -- and it access data and since django allows you to acces data only one time, I am not able to access it -
Add Page visit Count is not working properly
I am trying to add the no. of page visits to a post detail view page in Django. I have set the 'django.contrib.sessions.middleware.SessionMiddleware', correctly. I am trying to get the total visits for all users. I have made an attempt to add it in the get_context_data but I had to use self.request which returned the number of visits for the currently logged in user only, I am trying to get the total visit for all users and even guests who didn't log in. Here is the views.py class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post, reply=None).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') reply_id = self.request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create( post=post, user=self.request.user, content=content, reply=comment_qs) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context def Views_Count(request): # Number of visits to this view, as counted in the session variable. num_visits = request.session.get('num_visits', 0) request.session['num_visits'] = num_visits + 1 … -
How to fix User matching query does not exist error in django
I have been working on a follow system on django which is like instagram's one(same functionality I hope). So everything was working good the follow buttons were following a user, the following count on the profile was displaying the number of people a user follows, but there was one thing that was not working and it was the follower count. To add this I created a add_follower definition on a signals.py file but as soon as I did that The follow/unfollow button was not working due to a internal server 500 error, so after some investigation I realized that the 500 error was happening because there is this error DoesNotExist at /accounts/follow/username User matching query does not exist. How can this error be fixed and get this follow sistem to finally work? please I have been with this error for a while and I am getting desperate for not finding a solution. signals.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user = instance) Following.objects.create(user = instance) @receiver(m2m_changed, sender = Following.followed.through) # which list is changed def add_follower(sender, instance, action, reverse, pk_set, **kwargs): followed_users = [] # list of users main (logged ) user have followed logged_user = User.objects.get(username … -
django: filter.values(...) not retrieving the fields requested
Based on the following models, I am trying to query BankingDetail and retrieving information of the account and opportunity, by doing the following filter: Query: bankingLST = BankingDetail.objects.filter(opportunity__opportunity_name__icontains = searchItem) | BankingDetail.objects.filter(account__account_name__icontains = searchItem) | BankingDetail.objects.filter(sfAttachmentID__icontains = searchItem) | BankingDetail.objects.filter(opportunity__external_opportunity_id__icontains = searchItem) | BankingDetail.objects.filter(account__external_account_id__icontains = searchItem).values( 'id', 'opportunity__external_opportunity_id', 'account__external_account_id', 'opportunity__opportunity_name', 'account__account_name', 'account__industry') Models: class AccountDetail(models.Model): external_account_id = models.CharField(max_length=18, unique = True) account_name = models.TextField(unique = False, blank=True, null=True) industry = models.CharField(max_length=18, unique = False, blank=True, null=True) billing_state = models.CharField(max_length=18, unique = False, blank=True, null=True) def __str__(self): return self.account_name class OpportunityDetail(models.Model): account = models.ForeignKey(AccountDetail, on_delete=models.CASCADE, related_name='AccountDetails') external_opportunity_id = models.CharField(max_length=18, unique = True) opportunity_name = models.TextField(unique = False, blank=True, null=True) stage_name = models.CharField(max_length=18, unique = False, blank=True, null=True) def __str__(self): return self.opportunity_name class BankingDetail(models.Model): account = models.ForeignKey(AccountDetail, on_delete=models.CASCADE, related_name='AccountBankingDetails') opportunity = models.ForeignKey(OpportunityDetail, on_delete=models.CASCADE, related_name='OpportunityDetails') sfAttachmentID = models.CharField(max_length=18, unique = True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.account.account_name + ' - (' + self.opportunity.opportunity_name + ')' Current response: [ { "model": "app_banking.bankingdetail", "pk": 2, "fields": { "account": 3, "opportunity": 2, "sfAttachmentID": "175688177w3", "created": "2020-07-20T01:55:20.351Z" } }, { "model": "app_banking.bankingdetail", "pk": 3, "fields": { "account": 4, "opportunity": 3, "sfAttachmentID": "1236547898745632x3", "created": "2020-07-23T00:08:56.863Z" } } ] I dont understand why the fields that I am … -
Images Along With Post Only Applying In Django Admin and Not Regular Form
Like the title says, I'm trying to create a social media app and my users can upload text to their websites. Currently I'm working on adding Image functionality. I can easily add this images in the Django admin page, but whenever I try to do it from the User's create post form, nothing shows up. Here's my post create form: {% extends "social/base.html" %} {% load crispy_forms_tags %} {% block content4 %} <h1>Make Your Post</h1> <p>Write a post / Share an image</p> <br> <div class="container"> <form method="post"> {% csrf_token %} {{form|crispy}} <button type="submit" name="button">Make Post</button> </form> </div> {% endblock content4 %} Here's my views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Posts from django.contrib.auth.forms import AuthenticationForm from .forms import NewUserForm from django.contrib import messages from django.contrib.auth import logout, authenticate, login from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import CreateView from django.contrib.auth.decorators import login_required # Create your views here. def home(request): context = { 'posts' : Posts.objects.all() } return render(request, 'social/social.html', context) def register(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, f"New Account Created: {username}") login(request, user) return redirect ("/social") else: for msg in form.error_messages: print(form.error_messages[msg]) messages.error(request, f"{msg}: … -
In Django, how do you update all objects when creating a new one with generic.CreateView?
I'm trying to create a model with an "order" field that automatically updates whenever a new object is created. (Later, I want to update it when you drag table rows around as well.) I started following this tutorial, but I'm stuck in trying to use the manager to actually create the object. This is my simplified code: # models.py class Entry(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) owner = models.ForeignKey( get_user_model(), on_delete=models.SET_NULL, null=True, blank=True ) order = models.IntegerField(default=1) objects = EntryManager() class EntryManager(models.Manager): def create(self, **kwargs): instance = self.model(**kwargs) with transaction.atomic(): results = self.filter( owner = instance.owner ).aggregate( Max('order') ) current_order = results['order__max'] if current_order is None: current_order = 0 value = current_order + 1 instance.order = value instance.save() return instance #views.py class EntryCreateView(LoginRequiredMixin,generic.CreateView): model = Entry fields = ['name'] def form_valid(self, form): form.instance.owner = self.request.user return super().form_valid(form) success_url = reverse_lazy('home') When I create a new Entry object here, I get something with an empty order field. Do I need to call the manager directly somehow? Thanks in advance! -
Django 3.0, messages framework experiencing troubles
I recently tried to upgrade a django website to the latest Django and messages started to give me an error. It seems as though the wsgi module cannot load the message part of the request. Traceback (most recent call last): File "/home/hm/.local/lib/python3.8/site-packages/django/contrib/messages/api.py", line 21, in add_message messages = request._messages AttributeError: 'WSGIRequest' object has no attribute '_messages' I have already checked messages is installed in the apps part of the settings and middleware_classes contains the sessions middleware and the messages middleware. I have also re-ran the migrations and migrated successfully the database. I am using Django 3.0 and Python3.8. The final error message it throws is django.contrib.messages.api.MessageFailure: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware -
ValueError: Cannot force an update in save() with no primary key
I am trying to link Django and Mongo DB using Djongo. I created an ID with createsuperuser. Also, I checked that the ID passed to MongoDB. However, when I try to log in from the admin page, I get this error. The Django version I am using is 3.0.8 and the Djongo version is 1.3.3. raise ValueError("Cannot force an update in save() with no primary key.") ValueError: Cannot force an update in save() with no primary key. [23/Jul/2020 09:55:37] "GET / HTTP/1.1" 200 16351 [23/Jul/2020 09:55:37] "GET /static/admin/css/fonts.css HTTP/1.1" 304 0 [23/Jul/2020 09:55:37] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 304 0 [23/Jul/2020 09:55:37] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 304 0 [23/Jul/2020 09:55:37] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 304 0 Not Found: /favicon.ico [23/Jul/2020 09:55:37] "GET /favicon.ico HTTP/1.1" 404 1972 [23/Jul/2020 09:55:41] "GET /admin/ HTTP/1.1" 302 0 [23/Jul/2020 09:55:41] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1913 [23/Jul/2020 09:55:41] "GET /static/admin/css/base.css HTTP/1.1" 304 0 [23/Jul/2020 09:55:41] "GET /static/admin/css/login.css HTTP/1.1" 304 0 [23/Jul/2020 09:55:41] "GET /static/admin/css/responsive.css HTTP/1.1" 304 0 [23/Jul/2020 09:55:42] "GET /admin/ HTTP/1.1" 302 0 [23/Jul/2020 09:55:42] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1913 Internal Server Error: /admin/login/ Traceback (most recent call last): File "C:\Users\user\.virtualenvs\connect-mongo-5RkYBEE1\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\user\.virtualenvs\connect-mongo-5RkYBEE1\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File … -
Django Template Engine datetime comparison not working
I'm trying to build a small BBS-like app in Django, and I want to be able to restrict users from deleting posts more than 30 minutes old. However, I can't get the datetime comparison to work in the template engine. Here is a snippet of my views: context = { ... "message_time" : datetime.utcnow() + relativedelta(minutes=-30) } And here is the django template in the html: {% if request.session.userid == post.user.id and post.created_at >= message_time %} <form action="/wall/message/{{ post.id }}/delete" method="POST"> {% csrf_token %} <button type="submit">Delete</button> </form> {% endif %} For some reason, the delete button doesn't appear with this snippet, however it works without it (i.e. the message id/session id functionality is fine). I've tried using different combos of relativedelta +/- 30 minutes, created_at greater/less than message_time, but nothing seems to work. -
Django: prevent readonly forms handling
Is there a way to prevent handling of readonly fields in a Django Form? I need to show the value to the user but if he inspect and change the value it is migrated to database on submit, how can I prevent that? This is the way I create the form (it's a formset actually): NotasFormSet = modelformset_factory(Nota, extra=0, form=FormularioCalificaciones) formset = NotasFormSet(queryset=Nota.objects.filter(materia=materia)) for form in formset: form.fields['trimestre1'].widget.attrs['readonly'] = not cierre_t1 form.fields['trimestre2'].widget.attrs['readonly'] = not cierre_t2 form.fields['trimestre3'].widget.attrs['readonly'] = not cierre_t3 form.fields['nota_final'].widget.attrs['readonly'] = not cierre_nf Template rendering: <form method="POST"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form.instance.alumno.user.get_full_name }} <br> {{ form }} <br><br> {% endfor %} <button type="submit">Calificar</button> </form> -
How to add a link to the current Page in Django to be copied for Sharing
I am trying to add share button to capture the current page link in Django so that the user can use it for sharing, simply when the button is clicked it copies the current link Here is the template for a post page created Copy Link to Share<a href=""><i class="fas fa-share-square"></i></a> Thank you -
Django rest framework pass extra param to User custom manager
I have a CustomUserManager that I use to create different types of users of my app. I want to add the following logic: client sends an extra field containing some info I do something with this info I save the user model (the user model does not contain a field with this name) How do I do this? If I try sending an extra param on the request, the field extra_fields of the method create_user from the custom user manager does not appear to have this field. How do I manage to get it there?