Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django,I want my user when he Register ,He directly go to to create page, But when I do it ,It never go to create page .Here is my code
Views.py #For Cystomer Registration class CustomerRegistrationView(View): def get(self,request): form = CustomerRegistrationForm() return render(request,'mp/register.html',{'form':form}) def post(self,request): form = CustomerRegistrationForm(request.POST) if form.is_valid(): messages.success(request,'Congratulations Registerd Succesfuly ') form.save() success_url = reverse_lazy('profile') return render(request,'mp/register.html',{'form':form}) #For Creating Profile class ProfileCreate(LoginRequiredMixin,CreateView):#ye hogia hamara upload wala model = Profile fields = ['user_name','user_ethnicity','SelectGender','user_job','user_age','mother_additionalinfo'] success_url = reverse_lazy('profile') def form_valid(self,form): form.instance.user = self.request.user success_url = reverse_lazy('profilecreate') return super(ProfileCreate,self).form_valid(form) Urls.py #for register path('register/',views.CustomerRegistrationView.as_view(),name= 'register'), #for CreateProfile path('profilecreate/',views.ProfileCreate.as_view(),name= 'profilecreate'), Also the Important thing is that when i have not setup the Logout Function then it working,But when i steup,Then this not redirect user to another page and stay at Registration Page. -
How to serialize file field without host
I have a file field class Document(models.Model): generated_document = models.FileField( # документ, который создала Celery из шаблона upload_to='generated_files/', blank=True, null=True ) ... I am serializing this field like this class DocumentSerialize(serializers.ModelSerializer): class Meta: model = Document fields = ["generated_document", ...] I want to have this /media/generated_files/expense_contract_2022-07-17-20-02-51.pdf But I have result with host http://<HOST>/media/generated_files/expense_contract_2022-07-17-20-02-51.pdf I know about SerializerMethodField but what is the proper way to remove host in serializer? In urls.py i am using if settings.DEBUG: urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) -
NoReverseMatch as consequence of a form action
This is my urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.rando, name="rando"), path("wiki", views.index, name="index"), path("create", views.create, name="create"), path("wiki/<str:title>", views.title, name="title"), path("wiki/<str:title>/edit", views.edit, name="edit"), ] This is my views.py: def edit(request, title): if request.method=="POST": content = request.POST.get("content") util.save_entry(title, content) return redirect(f'/wiki/{title}') elif request.method=="GET": if title in util.list_entries(): ge = util.get_entry(title) return render(request, "encyclopedia/edit.html", { "title": title, "ge": ge }) else: return render(request, "encyclopedia/error.html") This is what I want to render (edit.html): {% block body %} <h1>Edit {{title}}</h1> <form action="{% url 'edit' %}" method="post"> {% csrf_token %} <textarea id="ctnt" name="content">{{ge}}</textarea> <br> <input type="submit" value="Submit"> </form> {% endblock %} When I want to send the form above with the current action it gives me: NoReverseMatch at /wiki/CSS/edit but when I remove action it doesn't display any error. Could you please tell me why this happens? Thank You -
Django Database not retrieving username/password
IMage can't be posted some reason but it returns both errors: User does not exist Username OR Password not Valid It seems Django is unable to access the database of users as well as passwords. The password consists of numbers, letters, upper/lowercase and a special character $ Below is my login function for LoginPage under views.py from django.shortcuts import render, redirect from django.contrib import messages from django.db.models import Q from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from .models import Room, Topic from .forms import RoomForm # Create your views here. # # rooms = [ # {'id':1, 'name':'Lets learn Python!'}, # {'id':2, 'name':'Design with me!'}, # {'id':3, 'name':'Front End Devs!'}, #] def loginPage(request): if request.method == 'POST': password = request.POST.get('password') username = request.POST.get('username') try: user = User.objects.get(username=username) except: messages.error(request, 'User does not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Username OR Password not Valid') context = {} return render(request, 'base/login_register.html', context) The Login_Register.html page code - {% extends 'main.html' %} {% block content %} <div> <form method="POST" action=""> {% csrf_token %} <label>Username:</label> <input type="text" value="username" placeholder='Enter Username..' /> <label>Password:</label> <input type="password" value="password" placeholder='Enter … -
How can I send for new model object create in django
I want to send email if user does something and because of his action some entry is made in the db. I want to do the send email function from my models.py. Is it possible?? -
Installing django rest framework kills the server
I work on ubuntu for creating a django app. Everything went well untill i install rest_framework and add this app to allowed apps list in settings.py Once i did this server started to show internal server errors. Somebody could help on it ? -
Is it important to include status in Django?
I am working on project where I'm importing, parsing and showing JSON data on site. I wanted to ask if it's important to add in JsonResponse "status" attribute. For example: return JsonResponse({"details":"Data parsed successfully!"}, safe=False, status=200) Thanks! -
while generating pdf its give me blank pdf
need to generate byte memory but while I'm trying to save my pdf its give me blank file. enter image description here -
fix RelatedObjectDoesNotExist at /agents/ error in django
i am creating a django CRM website but i a have a problem once i want relate the User to an organisation. model.py class User(AbstractUser): pass class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE)# every USER has one profile def __str__(self): return self.user.username class Agent(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE)# every agent has one user organisation = models.ForeignKey(UserProfile,on_delete=models.CASCADE) def __str__(self): return self.user.email # create signal to listen to event in order to create a profile user once a new user is created. def post_user_created_signal(sender,instance,created,**kwargs): if created: UserProfile.objects.create(user = instance) post_save.connect(post_user_created_signal,sender=User) views.py class AgentCreateView(LoginRequiredMixin, generic.CreateView) template_name = "agent_create.html" form_class = AgentModelForm def get_success_url(self): return reverse("agents:agent-list") def form_valid(self, form): agent = form.save(commit=False) agent.organisation = self.request.user.userprofile agent.save() return super(AgentCreateView, self).form_valid(form) once the user try to create an agent this error below is displayed. RelatedObjectDoesNotExist at /agents/ User has no userprofile. Request Method: GET Request URL: http://127.0.0.1:8000/agents/ Django Version: 4.0.6 Exception Type: RelatedObjectDoesNotExist Exception Value: User has no userprofile. Exception Location: C:\Users\LT GM\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\related_descriptors.py, line 461, in get Python Executable: C:\Users\LT GM\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.4 Python Path: ['F:\DJANGO', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages\win32', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages\win32\lib', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages\Pythonwin'] Server time: Sun, 17 Jul 2022 18:54:40 +0000 -
Django LoginView won't log in user
I have an app that is just meant to authenticate a user with Django's generic authentication views. The problem is that I can't log in a user even with the correct username and password. I keep getting an incorrect username or password error. The email and password are always simple such as, "email@email.com" and "123" as password so there's no way I'm messing up the spelling. I'm using Django's built in LoginView, a custom User model, and a custom AuthenticationForm. I've done this project before pretty much the same way with no issues but I can't find the difference between this project and my older project. This is my code. Thank you for your time. Views from .models import MyUser from .forms import MyUserLogin class Login(LoginView): template_name='loginapp/login.html' authentication_form=MyUserLogin success_url='/loginapp/home models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser class MyUser(AbstractBaseUser): fname=models.CharField(max_length=30) lname=models.CharField(max_length=30) email=models.EmailField(max_length=100, unique=True) phone=models.CharField(max_length=12) password=models.CharField(max_length=200) USERNAME_FIELD='email' forms.py from django.forms import ModelForm from django.contrib.auth.forms import AuthenticationForm from django.forms.widgets import TextInput from .models import MyUser class MyUserLogin(AuthenticationForm): class Meta: model=MyUser fields=['email', 'password'] ... login.html ... <div> <form method='post'> {% csrf_token %} <ul> <li><p>Email</p></li> <li>{{form.username}}</li><br> <!-- using "Email" as the label instead of "Username" --> <li>{{form.password.label}}</li> <li>{{form.password}}</li> </ul> <input type='submit' name='submit' class='submit' … -
How to properly implement Django form session wizard
I've been attempting to construct a multi-step form using the Django session wizard for hours, but I keep getting the error, AttributeError: 'function' object has no property 'as_view'. I'm not sure why this mistake occurred. Any ideas? views from django.shortcuts import render from formtools.wizard.views import SessionWizardView from .forms import WithdrawForm1, WithdrawForm2 class WithdrawWizard(SessionWizardView): template_name = 'withdraw.html' form_list = [WithdrawForm1, WithdrawForm2] def done(self, form_list, **kwargs): form_data = [form.cleaned_data for form in form_list] return render(self.request, 'done.html', {'data': form_data}) forms from django import forms from .models import Investment, Withdraw from .models import WithdrawStepOne, WithdrawStepTwo class WithdrawForm1(forms.ModelForm): class Meta: model = WithdrawStepOne fields = ['investment_id',] class WithdrawForm2(forms.ModelForm): class Meta: model = WithdrawStepTwo fields = [ 'proof_of_address', 'user_pic' ] urls from django.urls import path from .forms import WithdrawForm1, WithdrawForm2 from . import views urlpatterns = [ path('withdraw/', views.WithdrawWizard.as_view(), name='withdraw'), ] -
404 and 500 Errors in JSON
I am trying to fetch data from the JSON that I made but am receiving the following errors: network.js:26 POST http://127.0.0.1:8000/edit/2 404 (Not Found) network.js:18 GET http://127.0.0.1:8000/edit/2 500 (Internal Server Error) I want to fetch the objects from my Django models so that I can allow the user to edit a post which they had previously made through a Django form when the user presses the edit button. models.py class User(AbstractUser): followers = models.ManyToManyField("self", related_name="users_followers", symmetrical=False) following = models.ManyToManyField("self", related_name ="who_user_is_following", symmetrical=False) def serialize(self): return{ "followers": self.followers, "following": self.following } class Post(models.Model): post = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE, default="") likes = models.IntegerField(default=0) date_and_time = models.DateTimeField(auto_now_add=True) def serialize(self): return{ "id": self.id, "post": self.post, "user": self.user, "likes": self.likes, "date_and_time": self.date_and_time } views.py def edit(request, post_id): if request.method == "POST": edited_post = request.POST.get('post') try: post = Post.objects.get(pk=post_id) post.post = edited_post post.save() except: return JsonResponse({"error": "Editing the post did not work."}, status=404) if request.method == "GET": return JsonResponse(post.serialize()) else: return JsonResponse({"error": "Need a GET request."}, status=404) javascript document.addEventListener('DOMContentLoaded', function(){ const editButtons = document.querySelectorAll('.edit_button'); for (const button of editButtons) { id = button.value; button.addEventListener('click', () => edit_email(id)); } }); function edit_email(id){ console.log("edit button is clicked") console.log(id) document.querySelector('#post_itself').style.display = 'none'; document.querySelector('#date_and_time').style.display = 'none'; document.querySelector('#likes').style.display = … -
Django Rest Framework doesn't correctly changes requests text to json
I got below code: from django.contrib.auth import authenticate from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import AllowAny from rest_framework.response import Response from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def login(request): print(request.data) username = request.data.get("username") password = request.data.get("password") if username is None or password is None: return Response({"error": "Please provide both username and password"}, status=HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) if not user: return Response({"error": "Invalid Credentials"}, status=HTTP_404_NOT_FOUND) token, _ = Token.objects.get_or_create(user=user) return Response({"token": token.key}, status=HTTP_200_OK) When I am sending below request at http://localhost:80/api/user/login { "password":"#%RFzv@2BLYM&#jNh6o@46*74f38SV4q", "username":"kamil1234" } I am getting as a request.data below values: <QueryDict: {'_content_type': ['application/json'], '_content': ['{\r\n "password":"#%RFzv@2BLYM&#jNh6o@46*74f38SV4q",\r\n "username":"kamil1234",\r\n}']}> I am not sure what I am doing wrong in here. Since when I use curl everything works correctly. curl --location --request POST 'http://localhost:80/api/user/login' \ --header 'Content-Type: application/json' \ --data-raw '{ "password": "#%RFzv@2BLYM&#jNh6o@46*74f38SV4q", "username": "kamil1234" }' Thank you in advance for the help. -
Django-Allauth equivalent for Django Ninja?
I am developing a REST API for web application in Django Ninja and one of our project's assumptions is possibility of using Google SSO for authentication. Is there any equivalent of Django-Allauth for Django-Ninja? I haven't found anything similar and to be honest I have no idea on how to process that in Django Ninja. Thanks in advance. Kind regards -
Uploading image from aiogram bot in BytesIO format to Django ImageField using aiohttp post method
I'm receiving an image from aiogram bot and I'm saving it in BytesIO format to be able to send to my REST API with post method of aiohttp ClientSession. However, when I try to do that with the following code: import io import aiohttp from aiohttp import FormData # inside aiogram message handler image_in_bytes_io = io.BytesIO() await message.photo[-1].download(destination_file=image_in_bytes_io) formdata = FormData() formdata.add_field(name="image", value=image_in_bytes_io.read()) async with aiohttp.ClientSession() as session: async with session.post(url, data=formdata) as response: print(response.status) print(await response.read()) I'm getting status: 400 and error message: 'File extension \xe2\x80\x9c\xe2\x80\x9d is not allowed.' from my REST API. Can you show where I'm making a mistake? If this solution is wrong, can you show the correct way of uploading an image from aiogram bot to ImageField that is in REST API endpoint? Thanks :) -
MYSQL 0.0.2 package is not installing when running pip install -r requirements.txt
I am trying to install the 'mysql' package ( Version 0.0.2) , using pip install -r requirements.txt But I am facing the following error: Collecting mysql==0.0.2 Using cached mysql-0.0.2.tar.gz (1.9 kB) Preparing metadata (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/pwiwdipw/virtualenv/ITC/3.6/bin/python3.6_bin -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-sbgj4igk/mysql_4feada7a9dca4cc6b8bf0981676447ec/setup.py'"'"'; __file__='"'"'/tmp/pip-install-sbgj4igk/mysql_4feada7a9dca4cc6b8bf0981676447ec/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup;setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-yaqwy2z8 cwd: /tmp/pip-install-sbgj4igk/mysql_4feada7a9dca4cc6b8bf0981676447ec/ Complete output (28 lines): WARNING: `mysql` is a virtual package. Please use `%s` as a dependency directly. running egg_info creating /tmp/pip-pip-egg-info-yaqwy2z8/mysql.egg-info writing /tmp/pip-pip-egg-info-yaqwy2z8/mysql.egg-info/PKG-INFO Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-sbgj4igk/mysql_4feada7a9dca4cc6b8bf0981676447ec/setup.py", line 42, in <module> url="https://github.com/valhallasw/virtual-mysql-pypi-package", File "/home/pwiwdipw/virtualenv/ITC/3.6/lib/python3.6/site-packages/setuptools/__init__.py", line 153, in setup return distutils.core.setup(**attrs) File "/opt/alt/python36/lib64/python3.6/distutils/core.py", line 148, in setup dist.run_commands() File "/opt/alt/python36/lib64/python3.6/distutils/dist.py", line 955, in run_commands self.run_command(cmd) File "/opt/alt/python36/lib64/python3.6/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/home/pwiwdipw/virtualenv/ITC/3.6/lib/python3.6/site-packages/setuptools/command/egg_info.py", line 292, in run writer(self, ep.name, os.path.join(self.egg_info, ep.name)) File "/home/pwiwdipw/virtualenv/ITC/3.6/lib/python3.6/site-packages/setuptools/command/egg_info.py", line 656, in write_pkg_info metadata.write_pkg_info(cmd.egg_info) File "/opt/alt/python36/lib64/python3.6/distutils/dist.py", line 1106, in write_pkg_info self.write_pkg_file(pkg_info) File "/home/pwiwdipw/virtualenv/ITC/3.6/lib/python3.6/site-packages/setuptools/dist.py", line 188, in write_pkg_file license = rfc822_escape(self.get_license()) File "/opt/alt/python36/lib64/python3.6/distutils/util.py", line 474, in rfc822_escape lines = header.split('\n') AttributeError: 'list' object has no attribute 'split' ---------------------------------------- WARNING: Discarding … -
In Django, how to temporatily store consecutive user inputs in the backend within 60s?
I am having trouble storing user inputs temporarily in Django backend (like 60 seconds for a game. Once the game is over, it should delete all user input records). To make it clear: I want to develop a website game using python and Django as backend languages, where it takes user input (one word as one input) and counts how many words a user can give in 60 seconds. The website should remain the same after each submission, but the game records each user input in the backend and counts on it while the game is still running. I think that I should use a session in Django but I'm still not sure about how should I approach this problem. As the picture shows, the input box can only take 1 word for each submission, and continue taking user inputs until the timer ends. So, how should I save these temporary user inputs using Django? -
Why does a non required field in a serializer serialize the field?
Say I have a serialiser like class DumbSerializer(serializers.Serializer): field_one = serializers.CharField(required=False, allow_null=True) And I do something like asdf = DumbSerializer(data={}) asdf.is_valid() >>> True asdf.data >>> {'field_one': None} asdf.validated_data >>> OrderedDict() Why is the serialization of {} represented as {'field_one': None} and not {}, given that field_one is not a required field? The python internal representation is an empty dict as I would expect -
Django error: null value in column of relation violates not-null constraint
I have a simple Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE, null=True) description = models.TextField() MEETING_PLACES = [ ('Zoom', 'Zoom'), ('WhatsApp Call', 'WhatsApp Call'), ('Skype', 'Skype'), ('Other', 'Other'), ] meeting_place = models.CharField( choices=MEETING_PLACES, max_length=255 ) other_meeting_place = models.CharField(max_length=255, verbose_name='Other', blank=True, null=True) My focus was having the other_meeting_place input only be visible when ('Other', 'Other'), was selected. The html in my templates: <select name="meeting_place" id="meetingPlace" required=""> <option value="" selected="">---------</option> <option value="Zoom">Zoom</option> <option value="WhatsApp Call">WhatsApp Call</option> <option value="Skype">Skype</option> <option value="Other">Other</option> </select> <input type="text" name="other_meeting_place" id="other" maxlength="255" style="display: none;"> Using javascript: let meetingPlace = document.getElementById('meetingPlace') let other = document.getElementById('other') other.style.display = 'none' meetingPlace.onchange = () => { if (meetingPlace.options[meetingPlace.selectedIndex].text === 'Other') { other.style.display = 'block' } else if (meetingPlace.options[meetingPlace.selectedIndex].text !== 'Other') { other.style.display = 'none' } } Now when I submit to create a new group I get this error in the terminal: return self.cursor.execute(sql, params) django.db.utils.IntegrityError: null value in column "other_choice" of relation "chaburah_chaburah" violates not-null constraint I made migrations and migrated and didn't see an error, only when I try and create a Group. I've seen a people answer questions regarding not-null constraints, but there's a lot of answers to choose from and I couldn't find one that applied to … -
How to add and configure VSCode launch.json in Django project already containing docker-compose and dockerfile
I have a Django project with the following folder configuration: Apache Backend (git submodule) django_backend apis (contains urls.py, views.py, etc) django_backend manage.py docker dockerfile dockerfile-dev local dockerfile Frontend (git submodule) docker-compose.yml docker-compose.deploy.yml docker-compose.dev.yml It doesn't have a launch.json file to debug it, and I want to add a launch.json file to be able to debug it using VSCode and attach it to the running container. How should I configure the launch file? -
How can I get my Django server to reload when I change the HTML in dev mode without clicking the refresh button?
I'm working on a Django project. Right now (if you're the dev) you can make changes to the HTML pretty easily. i'm not having any issues with that, i just want to know how to get the server to reload when the HTML changes. here's the github. https://github.com/jeffcrockett86/django-unchained -
Getting error in django-import-export | ValueError: Field 'id' expected a number but got ''
I am using Django-import-export for importing data but facing an error given below. code for Django-import-export is given below: class MemberResource(resources.ModelResource): Brand=Field() class Meta: model = model fields=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat') export_order=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat') def dehydrate_Brand(self, obj): return str(obj.Brand.title) class modelAdmin(ImportExportModelAdmin): resource_class = MemberResource list_display=['id','title','Model_code','Chipset','chipset_description','Brand','categories'] search_fields = ['title','Model_code','Chipset',] fields=('title','Model_code','Chipset','chipset_description','image','Brand','Cat') admin.site.register(model,modelAdmin) I am getting below error Line number: 1 - Field 'id' expected a number but got ''. 2, f9, sd, gf, kjkj, images/sample_3pahsfV.jfif, 1, 1 Traceback (most recent call last): File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 187, in get rel_obj = self.field.get_cached_value(instance) File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'Brand' During the handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields_init_.py", line 1988, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 707, in import_row diff = self.get_diff_class()(self, original, new) File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 241, in init self.left = self._export_resource_fields(resource, instance) File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 262, in _export_resource_fields return [resource.export_field(f, instance) if instance else "" for f in resource.get_user_visible_fields()] File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 262, in return [resource.export_field(f, instance) if instance else "" for f in resource.get_user_visible_fields()] File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 919, … -
AssertionError: No templates used to render the response
I solved the problem while writing this question but I wanted to post it so maybe someone needs this answer Hello my friends. i am new to django testing. while i'm testing my views i faced this error in some views. This is my views.py: def all_programs(request): programs = Program.objects.all() return render(request, 'orders/all_programs.html', {'programs': programs}) def checkout(request, slug): if request.method == 'POST': # get data from form and save it program = get_object_or_404(Program, slug=slug) dates = ProgramDate.objects.filter(program=program) return render(request, 'orders/checkout.html', {'program': program, 'dates': dates}) This is urls.py: from django.urls import path from django.views.generic import RedirectView from .views import * app_name = 'orders' urlpatterns = [ path('', RedirectView.as_view(url='https://www.another-website.net')), path('tests/', all_programs, name='all_programs'), path('checkout/<str:slug>/', checkout, name='checkout'), path('checkout/return_page/', ReturnPage.as_view(), name='return_page'), ] And this is test_views.py: from django.test import TestCase from django.shortcuts import reverse class TestViews(TestCase): def test_all_programs(self): response = self.client.get(reverse('orders:all_programs')) self.assertTemplateUsed(response, 'orders/all_programs.html') def test_checkout(self): # error id here response = self.client.get(reverse('orders:all_programs', kwargs={'slug': 'test'})) # I tried this # response = self.client.get('http://127.0.0.1:8000/checkout/test/') #and this self.assertTemplateUsed(response, 'orders/checkout.html') -
When I use django seed, is it possible to create the next value of the dictionary by referencing the value inside the dictionary?
I am working on creating virtual data using django_seed. What if I randomly scatter the "check_in" date and try to create a random "check_out" date based on the previously generated "check_in" date? The "check_out" date must be after the "check_in" date. … import random from datetime import datetime, timedelta from django.core.management.base import BaseCommand from django_seed import Seed from reservations import models as reservation_models from users import models as user_models from rooms import models as room_models SEED_NAME = "reservations" class Command(BaseCommand): help = "This command creates {SEED_NAME}" def add_arguments(self, parser): parser.add_argument( "--number", default=2, type=int, help="How many {SEED_NAME}?" ) def handle(self, *args, **options): number = options.get("number") seeder = Seed.seeder() users = user_models.User.objects.all() rooms = room_models.Room.objects.all() seeder.add_entity( reservation_models.Reservation, number, { "status": lambda x: random.choice( ["pending", "confirmed", "canceled"] ), "check_in": lambda x: datetime.now(), "check_out": lambda x: datetime.now() + timedelta(days=random.randint(3, 25)), "guest": lambda x: random.choice(users), "room": lambda x: random.choice(rooms) }, ) seeder.execute() self.stdout.write(self.style.SUCCESS(f"{number} {SEED_NAME} created!")) -
Cannot load translation catalog for Django I18n on Google App Engine Standard
I've set up I18n for my Python3 Django4.0 app and it runs locally without problems. When I deploy it to GAE standard the translated text isn't shown. The active language changes, but the text does not change. The catalog files exist, but it looks like they are not being loaded. I am aware that GAE-standard only allows access to tmp/ directory. Could this be the reason? Are there particular cache requirements? Any advice or examples would be super useful.