Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Obtaining full requested url address
I'm looking to obtain the full requested url within python/django. I'm wondering what package might help me do this. For example, if someone goes to example.com/my-homepage, I want to capture the string 'example.com/my-homepage' in python. Thanks! -
Updating a list within a class
Is it possible to update a list within a class based on instance details? I would like to do something like this: from formtools.wizard.views import SessionWizardView class ContactWizard(SessionWizardView): form_list = [ # a list of forms used per step (S1, Q1), (S2, Q2), (S3, Q3), ] def form_updater(self): if self.get_cleaned_data_for_step("0") != None: form_list.append((S3, Q3),) return form_list However, I get thrown an error when I try to make the following call: ContactWizard.form_updater(ContactWizard) ## error: get_cleaned_data_for_step() missing 1 required positional argument: 'step' Any help or guidance that you can provide would be VERY greatly appreciated. -
URL pathfinder in Django - any workaround when it keeps redirecting me to main view?
Sorry for being an embarrassing noob, but I have managed to complete like 99% of the Django Girls tutorial only to realize that there is one essential function in my basic blog site that's not working - the post titles on the main view don't link to their respective post views, even though the code seems alright to me... Guess I am really missing a glaringly obvious mistake! I was considering to switch from pk to slug, could that be an effective workaround? views.py from django.shortcuts import render, get_object_or_404 from django.shortcuts import redirect from django.utils import timezone from .models import Post from .forms import PostForm def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) def post_edit(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm(instance=post) return render(request, 'blog/post_edit.html', {'form': form}) urls.py … -
{% for post in posts %}} in home.html not rendering anything Django
Im following Corey Schafers tutorial: https://www.youtube.com/watch?v=qDwdMDQ8oX4&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&index=3&ab_channel=CoreySchafer This is my home.html file: <!DOCTYPE html> <html> <head> <title></title> </head> <body> {% for post in posts %} <h1>{{ post.title }}</h1> <p>By {{ post.author }} on {{ post.date_posted }}</p> <p>{{ post.content }}</p> {% endfor %} asdf </body> </html> I know its the one being used because "asdf" is being rendered: But the title, content, and nothing really renders here. I have been following this tutorial doing everything the way he does. This is my views.py file: from django.shortcuts import render posts = [ { "author": "JohnsMS", "title": "Blog Post 1", "content": "First post content", "date_posted": "August 27, 2017" }, { "author": "John Doe ", "title": "Blog Post 2", "content": "Second post content", "date_posted": "June 27, 2018" } ] def home(request): context = { "post": posts } return render(request, "blog/home.html", context) def about(request): return render(request, "blog/about.html") I even added a print statement in the home function, and the context was correct. This is how it should render (from the tutorial): This is my directory structure: . ├── blog │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ ├── admin.cpython-39.pyc │ │ ├── apps.cpython-39.pyc │ │ … -
Django rest framework documentation JSONParser().parse(request) doesn't work
I followed official documentation tutorial and in POST method JSONParser().parse(request) didn't work so i just replaced it with request.POST then it worked. Is anything wrong with it? Why should i use JSONParser().parse(request) instead of request.POST? @csrf_exempt def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) #<------------ This line serializer = SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @csrf_exempt def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = request.POST #<---------- To this line serializer = SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) -
Django REST Filter Nested Objects
I have a Student model which has a Many-To-Many relationship with an Assignments model. The Assignments model has a foreign key relationship with a Scores model. This Scores model also relates to the Student to identify who the score belongs to. How would I filter my GET request so that it only returns the score for that specific user? MODELS class Rubric(models.Model): possibleScore = models.IntegerField(default=0) description = models.CharField(max_length=200,default="Correct") assignment = models.ForeignKey(Question,related_name='rubric',on_delete=models.CASCADE,blank=True,null=True) class StudentScore(models.Model): student = models.ForeignKey(to="accounts.Student",related_name="studentScore",on_delete=models.CASCADE,blank=True,null=True) rubric = models.ForeignKey(Rubric,related_name="studentScores",on_delete=models.CASCADE,blank=True,null=True) studentScore = models.IntegerField(default=0) class Assignment(models.Model): name = models.CharField(max_length=100) maxNumberOfPoints = models.IntegerField(default=100) studentsPoints = models.IntegerField(default=0) course = models.ForeignKey(Course,related_name='gradeable',on_delete=models.CASCADE) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) studentID = models.CharField(max_length=100,unique=True) Courses = models.ManyToManyField(Course) Assignment = models.ManyToManyField(Gradeable) Views class StudentView(APIView): permission_classes = [permissions.IsAuthenticated, ] def get_object(self, request): try: # Get requesters token and identify matching student object requestToken = request.META['HTTP_AUTHORIZATION'].split(' ')[1] userObj = Token.objects.get(key=requestToken).user studentObj = Student.objects.filter(user=userObj)[0] # If requester token does not match user return permission denied if(self.request.user != userObj): raise PermissionDenied() return studentObj except Student.DoesNotExist: raise Http404 def get(self, request, format=None): student = self.get_object(request) serializer = StudentSerializer(student) return Response(serializer.data) Serializers class StudentScoreSerializer(serializers.ModelSerializer): class Meta: model = StudentScore fields = ('studentScore',) class RubricSerializer(serializers.ModelSerializer): studentScores = StudentScoreSerializer(many=True,required=False) class Meta: model= Rubric fields=('possibleScore','description','studentScores',) class AssignmentSerializer(serializers.ModelSerializer): class Meta: … -
Python Django Projects scaffolding boilerplate automation
I have django-cms project and i will use it as boilerplate, like when i got a project, i just run a command, it should generate initial setup/copy existing project with different name and changing some contenxt. For example, i have wsgi.py file """ WSGI config for mysite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings.dev") application = get_wsgi_application() So currently the project name is mysite but when i re-genrate the same project for another client/project, the project name should be different, like it will mywebsitepro I mean, some text/code should be replaced into my given one. Anyone has idea of how i can get it done? like when we run django command django-admin startproject <projectname> You may notice, everywhere of the first generated files name is same as what we given in command argument. What is the possible solution of this? is there any tools like this? -
Django integration with a python script
I have a python script that open and mantein a websocket (socket.io) with a remote server and a django instance. For my purpose I want the script to start and stop with the django server. I would also like to exchange data between the two. In praticular django needs to be notified whenever the remote server goes offline and keep this information globally. The tricky points for me are: Start and stop django and the script at the same time. Store globally the state of the script in the django application Is there a good way to implement this? -
How should I structure my database entities with invites and recipients for e-signing web app in Django?
I am interested in implementing the following requirements for my e-signature web application. A user can create a new signing contract. That contract can include multiple users to sign. The contract creator needs to provide emails of the recipients. Every recipient will have additional data assigned, like signing details, instructions and etc. However, the invited user can still be not present in the system. This is the trickest part. Right now my following implementation is the following: I create a contract, then check if a user is present in the system by making a filter by email. If the user exists, I create a many-to-many entity ContractRecipientEvent using through intermediate table with additional data, which is assigned to the contract. I create it many-to-many because the same user can be assigned to multiple contracts. If the user is not present I create the Invitation model, set all recipient's specific data, and send an email. Then the user is registered, I run the query of all Invitations records with that email and create ContractRecipientEvent, by copying data from the Invitation model. What I don't like with my approach are the following things: Many-to-many field. I would like to just use plain … -
Django Python Error: 'dict' object has no attribute 'status_code'
Dear people i have a problem i can't solve. I get the following error after a post: 'dict' object has no attribute 'status_code' I'm using django 3.1.7 and python 3.8. Can anyone help me with this problem? I'm new to this stuff and can't seem to solve it alone. Part of the program: *body = ET.tostring(envelope, pretty_print=True) response = requests.post(url,data=body,headers=headers, auth=(gebruiker, wachtwoord)) root = ET.fromstring(response.text.encode('ascii','ignore')) if response.status_code == 200: status = 0 else: status = 1 Verwerking.objects.create(omgeving=omgnaam, Status=status, bericht=body, antwoord=ET.tostring(root, pretty_print=True).decode()) return HttpResponse()* Reponse: Internal Server Error: /woningbeheer/syncPCAind/532698 Traceback (most recent call last): File "C:\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python38\lib\site-packages\django\utils\deprecation.py", line 116, in call response = self.process_response(request, response) File "C:\Python38\lib\site-packages\django\middleware\common.py", line 106, in process_response if response.status_code == 404: AttributeError: 'dict' object has no attribute 'status_code' [20/Mar/2021 21:35:30] "GET /woningbeheer/syncPCAind/532698 HTTP/1.1" 500 65748 Thanks in advance and if there is more information needed let me know. -
Saving Queryset data to a model from a slider
I am trying to make a tinder like app where a hiring manager can search for specific IT candidates and then like or dislike them based on their qualifications. This app is acting as a frontend for an IT staffing company and uses their ZOHO database without showing any sensitive information for the candidates. Basically, the app calls the ZOHO API, fills the candidate model with data and I have a search form that uses a Queryset to display that data. I was able to put that data into a bootstrap carousel and scroll through each candidate but now I want to make a like button that will save a candidate to whatever user is currently logged in. I made a model for this called "UserChoice" but now I am unsure how to get the Queryset data into the new model and how to tie the button to each candidate the user wants to save. Currently, the buttons on the carousel just slide to the next candidate. Any help would be appreciated I am still pretty new to Django development. views.py(match app) number_of_candidates = len(database["response"]["result"]["Candidates"]["row"]) for P in range(0, number_of_candidates): #Clean slate for a new candidate. candidate_Pkey = "" candidate_Fname … -
how to use onkeyup javascript to django inlineformset fields
there i'm trying to add onKeyup() event to my django inlineformset fields , but i dont know how to achieve it this is my models.py class Main(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) company = models.ForeignKey(Companies,on_delete=models.CASCADE) items = models.ManyToManyField(Item,through='Child') invoice_number = models.IntegerField() class Child(models.Model): main = models.ForeignKey(Main,on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) quantity = models.IntegerField() price = models.IntegerField() function counting(result) { document.getElementById("total").value= result; } counting(0); function totalSumField () { let inp = document.querySelectorAll("#allInp > .inp"); let result=0; for(let i=0;i<inp.length;i++){ let nrx=inp[i].getElementsByClassName("price")[0].value; let dana=inp[i].getElementsByClassName("quantity")[0].value; inp[i].getElementsByClassName("totalSumField")[0].value=(price*quantity); } function totalSum () { let inp = document.querySelectorAll("#allInp > .inp"); let result=0; let qarz=0; for(let i=0;i<inp.length;i++){ let price=inp[i].getElementsByClassName("price")[0].value; let qnt=inp[i].getElementsByClassName("quantity")[0].value; [0].value; result+=(qnt*price); } counting(result) totalSumField() } {% extends 'base.html' %} {% load widget_tweaks %} {% block content %} <form method="POST">{% csrf_token %} {{items.management_form}} <div class="flex w-8/12 lg:w-9/12"> <div class=""> invoice number : </div> <div class="w-10/12 ml-8 border-b border-gray-600 border-dotted"> {{form.invoice_number | add_class:'bg-transparent w-full text-center focus:outline-none' }} </div> </div> <div class="w-full md:w-11/12 mx-auto realative p-2 bg-gray-200 invoice"> <!-- table --> <div class="mt-1 border border-black" style="direction: rtl;"> <!-- header --> <div class="flex flex-wrap grayBG text-sm text-white"> <div class="w-2/12 border-r text-center"> item </div> <div class="w-2/12 border-r text-center"> price </div> <div class="w-2/12 border-r text-center"> quantity </div> <div class="w-2/12 border-r text-center"> total price </div> </div> … -
Can I install PostgreSQL & PostGIS AFTER installing Django & GeoDjango?
I started following this tutorial2 after I failed with this one, tutorial1. I am trying to build this: Django is running after Django & GeoDjango installation. I am cautiously optimistic that I may have successfully installed GDAL v3.2.2, GEOS, and PROJ (worried that it is NOT PROJ.4). Next, I need to install PostgreSQL and its PostGIS extension. However, a lot of the instructions online warn that sequence of installation is important. I'm afraid to install PostgreSQL because I think it will break. This is the farthest I have gotten with the installation thus far and am afraid that I am building a house of cards that can fall at any time (due to my own lack of understanding). Do I proceed? Or should I just start over again from the start with a PostgreSQL installation and build fresh from there? Having learned that most of the trouble stems from those GIS packages, there is hope that I could now succeed. Hope is tenuous. Maybe I could just abandon PostgreSQL and run SQLite (except that appears to also require PROJ.4). The specs here say that I need PROJ4 (not PROJ) to work with PostgreSQL. But, PROJ might be the newer version … -
Django category model used in multiple models (belongs_to)
I have one Category model that I'd like to use in other models instead of creating different models for each case. Each model (Page, Article,...) has its own set of categories. Ex. Category model Page model with belongs_to category (page cat 1, page cat 2) Article model with belongs_to category (article cat 1, article cat 2) I can't use a polymorphic relationship since I don't have to store the id. So how can I represent that in my models? -
User authentication will not work in django
I have been trying to add user authentication to my social media/blog app in django. This code returns an error "UNIQUE constraint failed: auth_user.username". Can someone please tell me what I am doing wrong? Any helpful advice would be great. from django.shortcuts import render from django.http import HttpResponse from .forms import SignUpForm from django.contrib.auth.models import User def sign_up(request): context = {"form": SignUpForm} if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): username = form.cleaned_data.get("username") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = User.objects.create(username=username, email=email, password=password) user = form.save(commit=False) else: form = SignUpForm() return render(request, "sign_up/sign_up.html", context) -
Django custom login form will not validate against is_valid()
Summary: My custom login form is failing to validate against .is_valid(). I have been able to confirm the email & password values are being passed through to views.py as print(request.POST.get('') returns both the email (required for login) and the password. I think my issue is different from other similar questions because they all seem to address missing required fields. I tried excluding every field I could think of from .is_valid but the form won't validate. I click the button and nothing happens. I am using Django 3.7. accounts/forms.py class LoginForm(forms.Form): email = forms.EmailField(label='email', max_length='255') password = forms.CharField(label='password') def __init__(self, request, *args, **kwargs): self.request = request super(LoginForm, self).__init__(*args, **kwargs) def form_valid(self, form): form.save() return super(LoginForm, self).form_valid(form) accounts/views.py I can't access anything inside the "form.is_valid" if statement. I pop out on the else: side. def login_page(request): if request.method == 'POST': #create form instance / populate form = LoginForm(request.POST) context = { "email": "email", "password": "password", "first_name": "first_name", "last_name": "last_name", "is_active": "is_active", "form": form } if form.is_valid(): username = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(request, username=username, password=password) form.save() if user is not None: if user.is_active: login(request, user) print(request.is_authenticated()) context['form'] = LoginForm() return redirect('/') else: pass else: pass else: '''This is where I … -
Adding django-modeltranslation to existing project ruins tests
I have existing project and I decided to add translations options. I installed django-modeltranslation, added languages to settings, models to translation.py and added models in admin.py. from modeltranslation.translator import translator, TranslationOptions from .models import GameTask class GameTaskTranslationOptions(TranslationOptions): fields =('name', 'description', 'button_text') translator.register(GameTask, GameTaskTranslationOptions) @admin.register(GameTask) class GameTaskAdmin(TranslationAdmin): model = GameTask But as I mentioned I added it to existing project. So I have to move my existing data to created fields. So after makemigrations but before migrate I added to my migration file: def populate_function(apps, schema_editor): management.call_command("update_translation_fields") class Migration(migrations.Migration): dependencies = [ ('pages', '0054_auto_20210105_1041'), ] operations = [ ........., migrations.RunPython(populate_function, migrations.RunPython.noop), ] After that I run python manage.py migrate pages migrate_file. And it works. I have my database updated and my data aren't lost, they are moved to default language field set in settings. But after running my test I get: django.db.utils.ProgrammingError: column pages_gametask.button_text_pl does not exist. LINE 1: ..._text_pl" = "pages_gametask"."button_text" WHERE ("pages_gam... ^ HINT: Perhaps you meant to reference the column "pages_gametask.button_text". So to sum up, I have what I wanted - I have fields for my languages in my database, data aren't lost, but look like during test, the default database can't create due to language's fields. Can … -
AH01630: client denied by server configuration error
I am running Django in production and I have problem when visitors fills out a form in my website and an email is sent in to me in the backend. There is no problem when running in development mode, and the problem only arises in production. I am using apache2 together with mod_wsgi. Below is a snippet of my error_log [Sat Mar 20 18:36:52.693566 2021] [authz_core:error] [pid 63623:tid 140495391864576] [client 66.249.69.150:50390] AH01630: client denied by server configuration: /etc/wsgi-port-80/htdocs/cgi-bin [Sat Mar 20 18:46:20.822928 2021] [authz_core:error] [pid 63623:tid 140495391598336] [client 66.249.75.187:51831] AH01630: client denied by server configuration: /etc/wsgi-port-80/htdocs/cgi-bin [Sat Mar 20 18:49:18.121736 2021] [authz_core:error] [pid 63600:tid 140495390799616] [client 66.249.77.27:61325] AH01630: client denied by server configuration: /etc/wsgi-port-80/htdocs/cgi-bin [Sat Mar 20 18:49:25.616719 2021] [wsgi:error] [pid 63599:tid 140495337584384] [remote 52.175.223.195:7872] Not Found: /wp-includes/js/wp-emoji-release.min.js [Sat Mar 20 18:50:25.165286 2021] [wsgi:error] [pid 63599:tid 140494956918528] Exception in thread Thread-7: [Sat Mar 20 18:50:25.165357 2021] [wsgi:error] [pid 63599:tid 140494956918528] Traceback (most recent call last): [Sat Mar 20 18:50:25.165373 2021] [wsgi:error] [pid 63599:tid 140494956918528] File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner [Sat Mar 20 18:50:25.165832 2021] [wsgi:error] [pid 63599:tid 140494956918528] self.run() [Sat Mar 20 18:50:25.165847 2021] [wsgi:error] [pid 63599:tid 140494956918528] File "/usr/lib/python3.8/threading.py", line 870, in run [Sat Mar 20 18:50:25.166139 2021] … -
GET request in python with "requests" lib to a CloudFlare protected site returns Error 1020 "Please enable cookies"
I'm making a request like this: import requests s = requests.Session() r = s.get('http://<endpoint-url>') print(r.text) It returns an HTML page, and I can see these lines: Please enable cookies.</div> ... <span data-translate="error">Error</span> <span>1020</span> When I print s.cookies.get_dict() I'm getting this: {'__cfduid': 'd06702291bb6520f2 ...'} It works when I open the URL in the browser and I can see it sets this cookie. The problem is when I try to make the request from python. I looked in the response library docs, doesn't mention how to "enable cookies". Couldn't find anything useful on error 1020, or in the target website's API docs. What should I do? -
Authenticating Custom User Model for Login Django
I created my custom user model in my Django project. My user registering works properly. However, my login is not. This is my custom user model: from django.db import models import datetime from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.utils import timezone from django.utils.translation import gettext_lazy as _ class NewUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=150, primary_key = True) firstName = models.CharField(max_length=150) lastName = models.CharField(max_length=150) nombreArtistico = models.CharField(max_length=150, default=None, null=True, unique=True) #Validacion create_superuser last_login = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) #Info de la suscripcion_form activa = models.BooleanField(default=False) fecha_creacion = models.DateField(default=None, null=True) fecha_actualizacion = models.DateField(default=datetime.date.today) disponibilidad_de_reproducciones = models.IntegerField(default=3) # objects = CustomAccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['firstName', 'lastName'] def __str__(self): return self.username This is my Authentication Login Form: from django.forms import ModelForm from django import forms from usuarios.models import NewUser from django.contrib.auth.forms import UserCreationForm from django.conf import settings from django.contrib.auth import get_user_model User = get_user_model() class Register(forms.Form): username = forms.CharField(label="username", max_length=150) firstName = forms.CharField(label="First Name", max_length=150) lastName = forms.CharField(label="Last Name", max_length=150) password = forms.CharField(label="Password", max_length=150, widget=forms.PasswordInput) class AuthenticationForm(forms.Form): username = forms.CharField(label="username", max_length=150) password = forms.CharField(label="Password", max_length=150, widget=forms.PasswordInput) This is what I am trying in my login view. def login_view(response): if response.method == "POST": print(response.POST['username']) form = … -
Why are my django modelformsets being prepopulated after user uploads data?
So, I have a django modelformset for allowing the user to upload multiple listings on a fake ecommerce site. When the user first accesses the "upload page" the forms are clear and there's no problem. After the user uploads some items, though, it seems like django is prepopulating the forms with the information the user submitted earlier. I don't want this, and I have no clue how to prevent it. Here is the forms.py: class ProductModelForm(forms.ModelForm): class Meta: model = Product fields = [ "product_name", "product_description", "product_price", ] class ProductImageModelForm(forms.ModelForm): class Meta: model = ProductImage fields = [ "product_image", ] ProductModelFormSet = modelformset_factory( Product, fields=( "product_name", "product_description", "product_price", ), extra=3, ) ProductImageModelFormSet = modelformset_factory( ProductImage, fields=( "product_image", ), extra=3, ) and here's the view that handles it: @login_required def product_upload_view(request): if request.method == "POST": product_form_set = ProductModelFormSet(request.POST) product_image_form_set = ProductImageModelFormSet(request.POST, request.FILES) if (product_form_set.is_valid() and product_image_form_set.is_valid()): for obj, obj_image in zip(product_form_set.save(commit=False), product_image_form_set.save(commit=False)): obj.product_seller = request.user obj.product_pub_date = timezone.now() obj.product_image = obj_image obj_image.save() obj.save() return HttpResponseRedirect("somewhere/else/") product_form_set = ProductModelFormSet() product_image_form_set = ProductImageModelFormSet() return render(request, "products/upload.html", { "product_form_set": product_form_set, "product_image_form_set": product_image_form_set, }) Now, I don't know if I'm even explaining my problem right because I can't seem to find an answer online but … -
Why is Django rendering one of my app's templates as plain text
I am working on a blog development in Django and there are different categories of posts or articles on category_list.html which have been created using ORM library and to each category i have added some articles using ORM library with the help of category slug which are rendered on category_view.html and problem is that list of categories are shown perfectly on category_list.html after adding from admin panel of django and when I click on any category name(contains get_absolute_url link), it takes me perfectly to category_view.html page but on category_view.html, data is shown in the form of text means renders the complete content of category_view.html in the form of plain text. All other templates are getting rendered by django perfectly but what is the reason that category_view.html is getting rendered as plain text? Please help me def category_list(request,category_slug=None): category=None categories=CategoryList.objects.all() # article=Article.objects.all() return render(request,'category_list.html',{'categories':categories}) def category_view(request,category_slug): category=get_object_or_404(CategoryList,slug=category_slug) article=Article.objects.filter(category=category) return render(request,'category_view.html',{'category':category},{'article':article}) My url.py contains the following urls: path("",views.index), path('category',views.category_list, name='category_list'), path('<slug:category_slug>',views.category_view, name='story_by_category'), This is link in category_list.html which takes me to category_view.html <div class="row py-3"> {%for c in categories%} <div class="col-lg col-12 homeimg" id="img1"> <h5><a href="{{c.get_absolute_url}}">{{c.name}}</a></h5> <img class="secimg border-info" src="{{c.image_url|default_if_none:'#'}}" alt="gameplay videos"> </div> {%endfor%} </div> -
Django 3.0: django-notifications-hq, admin have a notification when Product has created by seller
Hi there i'm new in django-notification ,and i'm looking for a method to notify admin when a product or Order has created (i develop an E-commerce whith django and bootstrap4) help please -
Django using Celery not performing my task
I have been trying for the past 3 days to get django to perfom asynchronous tasks on a periodic schedule. Came across Celery which seemed like a perfect match for my problem but the more I read online the more problems there seemed to exist that I had prepared. Anyway I was able to vaguely glue up together pieces of information to finally come up with a "somewhat solution" because there were so many deprecated modules and methods it was hard to find a working example from start to finish. So I am trying to create a task which will create a certain model object periodically (let's say 30 seconds for sake of the argument). So I installed redis as the "broker", (so I saw fit in other discussions) and managed to set up my task up and running but the problem is that even when it executes, no new model is created, I suspect that it might be cause of maybe a misconfiguration between the local and the settings time-zone but frankly I'm not sure, supposedly it should be able to create new instance when run through django-celery-beat tables in the admin panel my init.py: from __future__ import absolute_import, … -
Failure to authenticate User with AuthenticationForm
I'm attempting to create a TemplateView where each subclass renders an AuthenticationForm; subclassing it and naming it UserLoginForm. This gives the User the opportunity to login with their credentials on any page they visit and be redirected to that same page after being successfully authenticated. When validating UserLoginForm, it fails to authenticate when it reaches form.clean() and raises self.get_invalid_login_error(). The TestCase used to simulate this scenario creates a User, then a POST request with the same credentials is sent. What's causing the UserLoginForm to invalidate the data passed to it and not finding the User? https://github.com/django/django/blob/main/django/contrib/auth/forms.py#L197 class TestTopicListMainPage__003(TestCase): '''Verify that an anonymous user is logged into their User account''' @classmethod def setUpTestData(cls): user = User.objects.create_user("User", 'secretcode') cls.data = { 'username': "User", 'password': "secretcode" } def test_topics_listing_login_user(self): response = self.client.post( reverse("topics:listing"), data=self.data ) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "topics/listing.html") self.assertContains(response, "Logout") class AbstractListingView(TemplateView): template_name = "topics/listing.html" def get_context_data(self): context = super().get_context_data() context['topics'] = Topic.objects.all() context['search_form'] = SearchForm() context['login_form'] = UserLoginForm return context def post(self, request): context = self.get_context_data() form = context['login_form'](request, data=request.POST) if form.is_valid(): resolver = resolve(request.path) login(request, form.user_cache) return HttpResponseRedirect(reverse(resolver.url_name)) return self.render_to_response(context) class TopicsMainPage(AbstractListingView): extra_content = { 'heading': 'Questions', 'query_links': ['interesting', 'hot', 'week', 'month'] } def get(self, request): query = request.GET.get('tab', None) …