Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
djstripe admin cannot view synced plans or products
I have a problem when I use django admin to view products and prices in djstripe. I have synced everything on Stripe portal. I get an error Exception Type: TypeError at /admin/djstripe/plan/ Exception Value: 'NoneType' object is not subscriptable How do I solve this? Been stuck here -
anyone with the right solutions--Auto mail send to student for upcoming lesson date and time, but issue here is that i have to make changes on my view
The issue here is that i have to change something from the code before the mail sent to respective subscriber schedule for that date, and not that it is sent to many of them but only one person recieved that email, maybe something the loop or my views, below is my views.py, the update is expected to run when the message delievered successfully the code works but, i have to make a change on the views before it finally sent. thanks substatus = SubscribeEmailModel.objects.filter(topic__startdate=today, sent_mail=False) print(substatus) recipient_list = {} for recipient in substatus: recipient_list[recipient.topic] = recipient.email print(recipient_list) for course in substatus: print(course.topic) top = course.topic if top != "": subject = 'Lesson Notification' from_email = 'example<example@example.com>' message = f'{course.topic} will be available online on {course.topic.startdate} starting from {course.topic.starttime} for more info reach out to your lecturer' send_mail(subject, message, from_email, [recipient_list[recipient.topic]], fail_silently=False) substatus.update(sent_mail=True) model = SubscribeEmailModel context_object_name = 'substatus' template_name = 'auto-send.html' -
Expecting property name enclosed in double quotes: line 1 column 2 (char 1) when converting Stringify to JSON [closed]
I am receiving a stringify object in Django. I am trying to convert it back to json using json.loads but getting error: Expecting property name enclosed in double quotes: line 1 column 2 (char 1). I also make sure that I am using double quotes "" instead of single quotes '' as mentioned in one of stackoverflow post but still getting it. This is the json: { "journey": { "id": 1, "name": "Test Jour", "journey_location": [ { "id": 2, "name": "2", "photo": "https://p2.png/", "sublocation": [] } ] } } This is stringify: {\"journey\":{\"id\":1,\"name\":\"Test Jour\",\"journey_location\":[{\"id\":2,\"name\":\"2\",\"photo\":\"https:\/\/p2.png\/\",\"sublocation\":[]}]}} -
I cannot send a variable to template in django
I am new to django so i would really appreciate some help.. I try to send data (for start a variable with some text) to an .html template and I cannot make it work, although I don't get any error. Here is my code.. views.py context = {'patient': 'abcde'} return render(request, 'examtable.html', context)``` examtable.html '''<div class="row d-flex align-items-center"> <div class="col-9"> <h3 class="f-w-300 d-flex align-items-center m-b-0"> <i class="feather icon-arrow-up text-c-green f-30 m-r-10"></i>$ <p>{{patient}}</p></h3> </div>''' urls.py '''urlpatterns = [ # The home page path('', views.index, name='home'), path('insert_patient',views.insert_patient,name='insert_patient'), path('nurse_patient',views.nurse_patient,name='nurse_patient'), path('examtable',views.exam_table,name='examtable'), # Matches any html file re_path(r'^.*\.*', views.pages, name='pages'), ] ''' The html file loads but the field {{patient}} is blank not showing the 'abcde'. Thank you in advance -
Problem with registrating new Django user
Can't register new user in Django, because when I try to do it the error that "user is already used" appears. Info that I put into form The result of the previous action Code (views.py) Urls.py and everything else is ok, the problem is with code. This code was taken from the youtube course and I've compared the code of the author and mine hundred times and still have this error. P.S. The admin panel is clear, there're no users apart from admin (superuser) Admin panel -
Add google maps coordinate in a database sqlite with react and django wagtail
I would like to store in a database(sqlite) some places (i.e restaurants,banks, bars and so on). Also, I would like to use the location of the user to show him/her the locations near and far from his/her location. I hope , I am clear enough . Thanks in advance, -
Can't get uuid value in email body in django
I have authentication app with email verification in it. I send an email like this: If registration form is valid then we save the form(create user) and set his token to uuid.uuid4. class customer_register(CreateView): model = User form_class = CustomerSignUpForm template_name = 'authentication/customer_register.html' def form_valid(self, form): user = form.save() user.token = str(uuid.uuid4) subject = 'Verify your account | Zane' message = f"http://127.0.0.1:8000/verify/{user.token}/" send_mail( subject, message, 'from@example.com', ['to@example.com'], fail_silently=False, ) In my mailtrap.io email arrives but it has some weird body: http://127.0.0.1:8000/verify/<function uuid4 at 0x103f32040>/ -
Deploying a dockerized Django app on a NAS
I’m very new to Docker and trying to run a simple Django app on my Asustor NAS following this guide https://docs.docker.com/samples/django/. But I can’t figure out what should I do with the ports to access the app. The NAS is connected to the Internet via a router. Apache web server is running on port 80 on the NAS. There also is a virtual host which already hosts 2 Wordpress websites. Example1.com redirects to /Web/example1 and example2.com redirects to /Web/example2. I also have an example3.com domain, which redirects to /Web/example3. So, I upload my app to /Web/example3 and start it with "docker-compose up". It starts successfully and the containers appear in Portainer in the NAS admin panel. Docker-compose.yml command is “python manage.py runserver 0.0.0.0:9000”. I tried setting ports in docker-compose.yml to “9000:9000” and “9000:80”. In both cases accessing NAS-local-ip:9000 returns the "server isn’t responding" error. Example3.com displays Apache “Index of/“ page with a list of files and folders of my app. How should I configure the ports to access the app both within the local network and outside of it? Any help will be appreciated. -
error: Dinucleotides matching query does not exist
I am trying to fetch specific rows from table on the basis of user input in forms. on pressing submit button, getting the following error. Error: DoesNotExist at /search/ Dinucleotides matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/search/ Django Version: 4.0.6 Exception Type: DoesNotExist Exception Value: Dinucleotides matching query does not exist. Exception Location: C:\ssrdb\lib\site-packages\django\db\models\query.py, line 496, in get Python Executable: C:\ssrdb\Scripts\python.exe Python Version: 3.10.5 Python Path: ['C:\ssrdb\Scripts\chick', 'C:\python310.zip', 'C:\DLLs', 'C:\lib', 'C:\', 'C:\ssrdb', 'C:\ssrdb\lib\site-packages'] Server time: Wed, 14 Sep 2022 07:08:27 +0000 views.py from django.shortcuts import render from django.views.generic import TemplateView, ListView, DetailView from ssr.models import Dinucleotides from ssr.forms import InputForm # Create your views here. def homepage(request): return render(request,'index.html') def searchpage(request): if(request.method == 'GET'): form=InputForm() return render(request,'search.html',{'form':form}) else: print(request.POST) if(request.POST['Motiff']): obj1=Dinucleotides.objects.get(SSRtype='Motiff') return render(request,'result.html',{'obj1':obj1}) -
Django - forloop to show/filter a value to show only once the entrys
I have a model (Restrictie) in which those who voted (participanti) and those who voted (votant) are registered. If I forloop in the templates, I can see who voted for whom, but one line is displayed for each record. How can I make a forloop or query in which participants are displayed only once and next to all the voters for example: name participanti - (name votant 1, name votant 2, ....) Below my code models.py class Participanti(models.Model): campanievot = models.ForeignKey(Campanie, on_delete=models.CASCADE) nume_participant = models.CharField(max_length=200, verbose_name='nume') dep_participant = models.CharField(max_length=200, verbose_name='departament') votes = models.IntegerField(default=0) def __str__(self): return self.nume_participant class Meta: verbose_name = 'Participanti' verbose_name_plural = 'Participanti' class Restrictie(models.Model): participanti = models.ForeignKey(Participanti,on_delete=models.CASCADE, verbose_name='Votat') votant = models.ForeignKey(UserVot,on_delete=models.CASCADE) def __str__(self): return str(self.participanti) class Meta: verbose_name = 'Voturi efectuate' verbose_name_plural = 'Voturi efectuate' views.py def rezultate(request): cineavotat = Restrictie.objects.all() ....... I tried this but it's show all entries like : name 1 = voters 1, name 1 = voters 2 ... {% for p in cineavotat %} {{ p.participanti }} - {{ p.votant}} {% endfor %} Please help me with a solution. Thank you! -
multiple deletion in django rest framework
I am working upon User model, So I need an urgent help on how to delete multiple users by getting id of users in views. I have tried with this in views but does'nt works: class UserDeleteView(APIView): permission_classes = (IsAdminUser,) def get_object(self,id): try: return User.objects.get(id=id) except User.DoesNotExist: raise Http404 def delete(self,request,id,format=None): userData=self.get_object(id=id) if userData: for usr in userData: usr.delete() -
Danger of DEBUG = True in production [closed]
I've read all about Django's DEBUG = True and some of the effects, but it never states WHY you should not use DEBUG = True in production, only that you shouldn't. I've also read that DEBUG=True remembers every query you make which will increase in memory over time. Recently though, I've found out you can just change the technical_500.html, technical_404.html (and maybe even the technical_500.txt) in .venv/Lib/site-packages/django/views/templates or the functions themselves in .venv/Lib/site-packages/django/core/handlers/exception.py and get no traceback and data dump whenever you get a 404 or 500 response. So my question is: is there any real danger in setting DEBUG to True and changing the html's (or functions) mentioned above, if you also have no queries? P.S I know this may be bad practice, just curious. -
Error: A bytes-like object is required, not 'list'
I am developing a small project that aims to enable to the user to submit a zip file. The system should read the file, extract it and save its contents to the database. I am having this error : a bytes-like object is required, not 'list' because I tried to use BytesIo. without it, the error said :" fpin.seek(0, 2) AttributeError: 'list' object has no attribute 'seek'" My code looks like this files = request.FILES.getlist('document[]') with zipfile.ZipFile(io.BytesIO(files), "r")as archive: for zippedFileName in archive.namelist(): with archive.open(zippedFileName) as myfile: with io.BytesIO() as buf: buf.write(myfile.read()) buf.seek(0) file = File(buf, zippedFileName).decode('utf-8') rbe = UploadedFile.objects.create(document=file) rbe.user= request.user rbe.save() return render(request, 'uploader/index.html', {'files': files}) -
Which one is better option to choose as a Primary key for Cart in Django? UUID or Session Key?
So, I have been working on a DRF eCommerce project. As, using the auto incrementing id field in the cart model isn't ideal. I chose to use UUIDField for it. I can achieve the same with session key too. But, I was wondering if there is any approach that meets the industry standard? Please suggest me the more appropriate primary key choice with a explanation from a industry point of view. class Cart(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) skey = models.CharField(max_length=250, null=True) total_price = models.PositiveIntegerField(editable=False, blank=True, null=True) date_added = models.DateField(auto_now_add=True) def __str__(self): return self.skey -
How to use simplify data access in django using context caching
class SampSerializer(CustomModelSerializer): user = serializers.SerializerMethodField() user_id = serializers.IntegerField(source="user.id", read_only=True) role = serializers.SerializerMethodField() a = serializers.SerializerMethodField() b = serializers.SerializerMethodField() c = serializers.SerializerMethodField() d = serializers.SerializerMethodField() e = serializers.SerializerMethodField() f = EscapedCharField() g = EscapedCharField(source="user.referred_by", read_only=True) h = serializers.SerializerMethodField() i = serializers.SerializerMethodField() class Meta: model = UserOverview fields = ( "id", "user", "user_id", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", ) def get_user(self, obj): print(len(connection.queries)) if obj.user: return obj.user.display_name().strip() else: return "" When I call the api linked to the above serializer? It prints the length of the connection queries as 14 and thus becomes slow. How do I speed up the query using context caching -
How can I connect zappa to local database sqlite in django application? [closed]
I got an error while using zappa to connect with local database sqlite in django. -
I would like to send a html as a popup in django admin
Admin is not sending the html page in the form of popup its displaying in window admin.py def RESTORE(self,obj): url = f'/system/displayer/' opensrt = f"window.open({url},'width=600,height=400')" return format_html('<a href="{url}"onclick="{opensrt}">RESTORE</a>', opensrt=opensrt,url=url) views.py def display(request): if request.method=='POST': print("HI POST") output=request.POST.get('output') if output=='YES': pass return render(request, "abc.html",{'form':UserForm}) -
How to find all objects as objects in the list in django?
i have 1 model like this class SomeModel(models.Model): data = models.JSONField(null=False) SomeModel's data is like id:1, data:{'one': ['1', '2', '3'], 'two': ['2', '3'], ...} id:2, data:{'one': ['1', '2'], 'two': ['2'], ...} id:3, data:{'one': ['1', '3'], 'two': ['3'], ...} I want to filter all objects got '2'. i need some help :( -
How can I use AWS dynamo db local and postgresql in a single django project?
I have a django project in which I need both postgresql and AWS dynamo db.I had configured postgresql and it is working well but I cant find a way to configure dynamo db. settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432 } } How can I configure dynamo db in this project? -
My pagination in Category pages is not working
I made a blog app in which I want to add pagination both on home page and category page. but after a lot of efforts I didn't get how to use it in the category page. I use 2 parameters in category view and I don' know how to fix it now. whenever I click on category "That page number is not an integer" displays. views.py: def allpost(request): postData = Post.objects.all() paginator = Paginator(postData, 5) # Show 5 contacts per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'posts.html', {'page_obj': page_obj}) def CategoryView(request, cats='category__title'): category_posts = Post.objects.all() paginator = Paginator(category_posts, 5) # We don't need to handle the case where the `page` parameter # is not an integer because our URL only accepts integers try: category_posts = paginator.page('cats') except EmptyPage: # if we exceed the page limit we return the last page category_posts = paginator.page(paginator.num_pages) return render(request, 'categories.html', {'category_posts': category_posts}) urls.py: path('category/<str:cats>/', views.CategoryView, name ="category"), categories.html {% extends 'base.html' %} {%block content%} <h1> Category: {{ cats }} </h1> {% for post in category_posts %} <div class="container mt-3"> <div class="row mb-2"> <div class="col-md-6"> <div class="card flex-md-row mb-4 box-shadow h-md-250"> <div class="card-body d-flex flex-column align-items-start"> <strong class="d-inline-block mb-2 text-primary">{{ post.category }}</strong> … -
Reverse for 'delete_reply' with arguments '(7, '')' not found
I am a new for Django and need some help. I want to make a 'delete' function regarding comments, but when I clicked the deletion button, I got the error Reverse for 'delete_reply' with arguments '(7, '')' not found. 1 pattern(s) tried: ['boards/(?P<board_pk>[0-9]+)/reply/(?P<reply_pk>[0-9]+)/delete/\Z'] I guess that there is no pk for the reply_pk, so I tried to give the pk into the url. However, I couldn't get the answer what I want. I spend lots of time to find solutions on google and here, but all wonderful answers couldn't help me to fix it. I attached my code here and please help me model.py class ReplyBoard(core_models.TimeStampedModel): reply = models.TextField(default="") user = models.ForeignKey(user_models.User, related_name = "reply", on_delete = models.CASCADE) board = models.ForeignKey("Board", related_name = "reply", on_delete = models.CASCADE, null = True) view.py class Board_detail(View): def get(self, *args, **kwargs): pk = kwargs.get("pk") try: form = forms.ReplyForm() board = board_models.Board.objects.get(pk=pk) return render(self.request, "boards/board_detail.html", {"board": board, "form": form}) except board_models.Board.DoesNotExist: raise Http404() def create_reply(request, board_pk): form = forms.ReplyForm(request.POST) if request.method =="POST": board = board_models.Board.objects.get(pk=board_pk) if form.is_valid(): reply = form.save() reply.board = board reply.user = request.user reply.save() messages.success(request, "creted the comment.") return redirect(reverse("boards:board_detail", kwargs={"pk": board.pk})) @login_required() def delete_reply(request, board_pk, reply_pk): try: reply = board_models.ReplyBoard.objects.get(pk=reply_pk) if … -
Is there any way to make my model only take input which is an x-ray image?
I am a newbie here in ML. I have a CNN model which predicts between 2 classes i.e. Pneumonia and Normal x-ray images.. It was great until I found that it also processes any image other than x-rays like Given a picture of a dog, it would still predict pneumonia or normal randomly. Is there any way to make it accept only x-ray images. or some workaround in Django to make it work? -
How do I solve the problem of " 'mssql' isn't an available database backend or couldn't be imported" on windows?
I ran into this problem when trying to deploy some django project on a Windows 10 computer. Every time I try to access localhost, it displays this error: Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\programdata\anaconda3\lib\site-packages\django\db\utils.py", line 113, in load_backendreturn import_module("%s.base" % backend_name) File "c:\programdata\anaconda3\lib\importlib\__init__.py", line 127, in import_modulereturn _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 961, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 1014, in _gcd_importFile "", line 991, in _find_and_load File "", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mssql' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\XXX\AppData\Roaming\Python\Python38\site-packages\wfastcgi.py", line 791, in mainenv, handler = read_wsgi_handler(response.physical_path) File "C:\Users\XXX\AppData\Roaming\Python\Python38\site-packages\wfastcgi.py", line 633, in read_wsgi_handlerhandler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\Users\XXX\AppData\Roaming\Python\Python38\site-packages\wfastcgi.py", line 600, in get_wsgi_handlerhandler = __import__(module_name, fromlist=[name_list[0][0]]) File "C:\inetpub\wwwroot\ScenarioAnalysis\ScenarioAnalysis\wsgi.py", line 16, in application = get_wsgi_application() File "c:\programdata\anaconda3\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_applicationdjango.setup(set_prefix=False) File "c:\programdata\anaconda3\lib\site-packages\django\__init__.py", line 24, in setupapps.populate(settings.INSTALLED_APPS) File "c:\programdata\anaconda3\lib\site-packages\django\apps\registry.py", line 116, in populateapp_config.import_models() File "c:\programdata\anaconda3\lib\site-packages\django\apps\config.py", line 269, in import_modelsself.models_module = import_module(models_module_name) File "c:\programdata\anaconda3\lib\importlib\__init__.py", line 127, in import_modulereturn _bootstrap._gcd_import(name[level:], package, level) File "c:\programdata\anaconda3\lib\site-packages\django\contrib\auth\models.py", line 3, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "c:\programdata\anaconda3\lib\site-packages\django\contrib\auth\base_user.py", … -
Django admin.py fieldsets: How to add a field from a ManyToMany field inside listdisplay?
I have these 2 models: class Size(models.Model): _id = models.AutoField(primary_key=True, editable=False) size = models.CharField(max_length=50, null=True, blank=False) SIZE_TYPES = ( ('XS', 'XS'), ('S', 'S'), ('M', 'M'), ('L', 'L'), ('XL', 'XL'), ('XXL', 'XXL'), ) size_type = models.CharField(max_length=10, choices=SIZE_TYPES, null=True, blank=True) GENDERS = ( ('M', 'Male'), ('F', 'Female'), ('U', 'Unisex'), ) gender = models.CharField(max_length=50, choices=GENDERS, null=True, blank=False) def __str__(self) -> str: return f'{self.size} ({self.size_type}) - {self.gender}' and: class Product(models.Model): _id = models.AutoField(primary_key=True, editable=False) user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True) size = models.ManyToManyField(Size) (... other attributes) and on my admin.py I want that ProductAdmin had the Size's attributes on listdisplay, but it doesn't work so I have my ProductAdmin like this: @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ['_id','name', 'brand', 'price', 'stock', 'category','rating','user','size'] But I can't get it to work, I've tried also size__size, also doesn't work. What I need: For list_display, I just want that the admin could see the product's size as a column on the Product's table in admin panel. The Product table should look like this: id name (...) size 1 Jordan sneakers (...) 7.5 (US) - M -
I am trying to connect to mysql on django app but i am facing this error and cannot find solution online
and the pacakge i used is mysql-connector-python and the error that i am facing is