Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The best way to do an efficient filter query in django
models.py file I am not so good at this aspect in Django. Please can someone help me? I wish to know if there is a more efficient way for the class method already_voted class Vote(TimeStamped): voter = models.ForeignKey(get_user_model(), verbose_name=_("Vote"), on_delete=models.CASCADE) contester = models.ForeignKey(Contester, verbose_name=_("Contester"), on_delete=models.CASCADE, help_text=("The chosen contester"), related_name="votes") ip_address = models.GenericIPAddressField( _("Voter's IP"), protocol="both", unpack_ipv4=False, default="None", unique=True ) num_vote = models.PositiveIntegerField(_("Vote"), default=0) class Meta: unique_together = ('voter','contester') verbose_name = _("Vote") verbose_name_plural = _("Votes") permissions = ( ("vote_multiple_times", "can vote multiple times"), ) .... .... @classmethod def already_voted(cls, contester_id, voter_id=None, ip_addr=None): return cls.objects.filter(contester_id=contester_id).exists() and \ (cls.objects.filter(ip_address=ip_addr).exists() or \ cls.objects.filter(voter_id=voter_id).exists()) -
Django Search Vector throws Mysql error when Postgresql is configured
I'm getting an error when using a Search Vector with Django. The weird things is that the error tells me the query on the MySQL database is incorrect, when I'm using PostgreSQL. I have no clue what's wrong. As I'm using the Search Vector from the postgres contrib module. Django behaves unexpected, how can I solve this error? Error in the browser: Environment: Request Method: POST Request URL: http://test.shop4raad.nl:8000/blog/search/post Django Version: 3.1.2 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.postgres', 'taggit', 'blog.apps.BlogConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/maarten/test/blogexperiment/project/project/templates/base.html, error at line 0 1064 1 : <!DOCTYPE html> 2 : {% load custom_tags %} 3 : {% load static %} 4 : <html lang="en"> 5 : <head> 6 : <title>{% block title %}{% endblock %}</title> 7 : <link href="{% static 'styles/blog.css' %}" rel="stylesheet"> 8 : </head> 9 : <body> 10 : <div id="content"> Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.6/dist-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.6/dist-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/usr/local/lib/python3.6/dist-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/lib/python3.6/dist-packages/MySQLdb/connections.py", line 259, in … -
Decimal numbers in views.py
I am new to Python/Django, so please bear with me! I have simple django views to sum book values: def portfoyozet(request): librarysum = textshare.objects.filter(user_id=request.user.id).aggregate(Sum('bookvalue'))['bookvalue__sum'] or 0 return render(request, 'todo/libsum.html', {'librarysum': librarysum,}) Which is working perfectly but result isn't show decimal values. 4800,30 becomes 4800,00 I dont need to round or something like that here. I just need to show all values with decimal values.It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use. Also found something while googling and change my views.py like: def portfoyozet(request): librarysum = textshare.objects.filter(user_id=request.user.id).aggregate(Sum('bookvalue'))['bookvalue__sum',0.00] or 0 return render(request, 'todo/libsum.html', {'librarysum': librarysum,}) But it doesnt work either. I have to seek help here as a last resort. I really appreciate if someone could help me out. Thank you in advance. -
django template if return True even if variable False
I am beginner in django and most probably i do something wrong. My view : class StartPageIndexView(View): def get(self, request): form = UserLoginRegistrationForm() lorem_ipsum_text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." print("request.user %s", request.user) is_logged_on = False if request.user.is_authenticated: logger.error("User authenticated") is_logged_on = True context = { 'lorem_ipsum': lorem_ipsum_text, 'registration_form': form, 'is_logged_on': is_logged_on, } return render(request, 'startpage/index.html', context=context) my template : {% extends "base.html" %} {% if is_logged_on is True %} {% block sidebar %} {{ is_logged_on }} {% include "inc/_sidebar.html" %} {% endblock %} {% endif %} {% block content %} {{ is_logged_on }} {{ lorem_ipsum }} {% endblock %} In browser i see this . Can you please tell me what i do … -
django.core.exceptions.ImproperlyConfigured: Boardapi_update is missing a QuerySet
Boardapi_update is missing a QuerySet. Define Boardapi_update.model, Boardapi_update.queryset, or override Boardapi_update.get_queryset(). This error occurs. The same error occurred with boardapi_delete. help me!!!!!!!!!!! views.py class Boardapi_update(generic.UpdateView): def update(self, request, *args, **kwargs): pk = { 'pk': self.kwargs['pk'], } data = { 'b_title': requests.POST.get['b_title'], 'b_note': requests.POST.get['b_note'] } url = 'http://localhost:8080/boardapi/'+str(pk['pk'])+'/update/' bupdate = requests.put(url, data=data) print(bupdate) def get_success_url(self): return reverse('board_detail', kwargs={'pk': self.object.board.pk}) class Boardapi_delete(generic.DeleteView): def delete(self, request, *args, **kwargs): datas = { 'pk': self.kwargs['pk'] } url = 'http://127.0.0.1:8080/boardapi/'+str(datas['pk'])+'/delete/' bdelete = requests.delete(url, params=datas) print(bdelete) return redirect(reverse('board')) -
Django Embeded model formset and model form
I'm a newbie in Django. I want to know how to embed multiple model forms and formsets ? how to set default or remove fields based on user permission and insert them into one form and get data from users and update/create objects in multiple model? what views method should I use? class-based views or function-based views? below there is an example of what I want to do. if you need more information please let me know this is a report view that will show the detail of the report that the user sent to the website and the admin can change/update/delete status and looted game items of the report and save it each report belongs to one user and one game account. and each looted game item belongs to a report, user, and game account. sample of my form and there is my models: class GameAccounts(models.Model): name = models.CharField(null=True,blank=True,max_length=400) provider = models.IntegerField(choices=GAME_PROVIDER, null=True) game = models.IntegerField(choices=GAME_NAME, null=True) username = models.CharField(null=True,blank=True,max_length=400) password = models.CharField(null=True,blank=True,max_length=400) def __str__(self): return self.name class GameAccountsHistory(models.Model): gameaccounts = models.ForeignKey(GameAccounts, on_delete=models.CASCADE, ) user = models.ForeignKey(User,on_delete=models.CASCADE,) date_stamp = models.DateField(auto_now=True,null=True) time_stamp = models.DateTimeField(auto_now=True,null=True,blank=True) status = models.IntegerField(choices=GAME_STATUS, null=True) class LootedGameItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, ) gameaccounts = models.ForeignKey(GameAccounts, on_delete=models.CASCADE, ) … -
Klaviyo - Removed download button from image, how can I remove mouse over events?
With this variable {{ emptyURL|add:"#" }} I removed the download button from my image (small download button that appears in bottom right corner when you hover over the image) but when you hover with mouse the pointer becomes hand, how to stop that from happening? -
Is it possible to query wagtail using a value of an orderable field
I have a wagtail page with an orderable field, however, I need to query from the API based on the value of an orderable. So for example, a manufacturer page has a field for products, which is a one to many relationship, and I want to get all manufacturers that make a particular product using the API -
Python microsoft graph API - /callback error
In my Django web application, I need to enable SSO - single tenant - Internal to the organization. Based on ref tutorial: link I was able to copy-paste required code snippets in views.py, urls.py. I also created an oauth_settings.yml file- app_id: {app id} app_secret: {app secret} redirect: "http://localhost:8000/callback" scopes: - user.read authority: "https://login.microsoftonline.com/{tenant}" Yet every time after I submit the O365 credentials, I am facing the same /callback error :- I have identified the issue to be in 'auth_flow' variable which holds entire flow dict. data which is reflected earlier, but fails to be saved in the request.session. Please guide what exactly may be the issue at hand. Thanks. -
Here, I am trying to automatically give data in Customer model of one app from SignUpForm form model in another app in Django. How can I do it?
from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django import forms class SignUpForm(UserCreationForm): password2 = forms.CharField(label='Confirm Password',widget=forms.PasswordInput) class Meta: model = User fields=['username','first_name','last_name','email'] labels = {'email':'Email'} from django.db import models from django.contrib.auth.models import User Create your models here. class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name -
django not sending mail even if password is wrong its showing email sended
I have been struggling to solve this for the last 3 hours but couldn't find it. My problem is that Django is not sending email and even if I enter the wrong username and password it shows successful .It never sends mail. Please tell me what I am doing wrong.Here is my settings.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '******************' EMAIL_HOST_PASSWORD = '********' My urls.py file: path('reset_password_complete',auth_views.PasswordResetCompleteView.as_view(),name='password_reset_complete'), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset_password_sent/',auth_views.PasswordResetDoneView.as_view(),name='password_reset_done'), path('reset_password/',auth_views.PasswordResetView.as_view(),name="reset_password"), I am using the default view of Django but even if my password is wrong or username is wrong it shows me email has been sent but it has not.Please help me. -
Reverse for 'likes' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['datasecurity/likes/<int:pk>'] Like buttton error in django
registration and login page is working properly but mine like button is not working .. I don't know why... Can somebody help me to solve this issue … it will be great help please help Thank you! views.py` from django.shortcuts import render, get_object_or_404 from datasecurity.models import Post from django.urls import reverse from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login required # Create your views here. def datasecurity(request): allPosts= Post.objects.all() context={'allPosts': allPosts} return render(request, 'datasecurity/data.html',context=context) def blogHome(request, slug): post=Post.objects.filter(slug=slug).first() context={"post":post} return render(request, "datasecurity/blogHome.html", context) @login_required def likes(request, pk): post=get_object_or_404(Post, id=request.POST.get('post_id')) post.likes.add(request.user) return HttpResponseRedirect(reverse('datasecurity:blogHome', args=str(pk))) urls.py from django.conf.urls import url from . import views app_name = 'datasecurity' urlpatterns = [ url(r'^$', views.datasecurity, name="datasecurity"), url(r'^datasecurity/(?P<slug>[^/]+)', views.blogHome, name='blogHome'), url(r'^likes/<int:pk>', views.likes, name = "likes"), ] data.html {% extends 'careforallapp/navbar.html' %} {% block body_block %} {% load static %} Welcome to Data Security {% for post in allPosts %} <div class="line-dec"></div> <span >This is a Bootstrap v4.2.1 CSS Template for you. Edit and use this layout for your site. Updated on 21 May 2019 for repeated main menu HTML code.</span > </div> <div class="left-image-post"> <div class="row"> <div class="col-md-6"> <div class="left-image"> {% if post.img %} <img src="{{ post.img.url }}" alt="" /> {% endif %} </div> </div> <div … -
LayoutError at /invoice/ Flowable <PmlTable@0x1D09C899130 7 rows x 5 cols(tallest row 841)> with cell(0,0)
I am trying to print invoice in pdf format in django i used xhtml2pdf to convert html doc to pdf but when i try to run my code it gives me this error : LayoutError at /invoice/ Flowable <PmlTable@0x1D09C899130 7 rows x 5 cols(tallest row 841)> with cell(0,0) containing '<PmlKeepInFrame at 0x1d09b77d670> size=x'(538.5826771653543 x 5893.228346456693), tallest cell 841.9 points, too large on page 2 in frame 'body'(538.5826771653543 x 785.19685039370 this is in my views.py from django.http import HttpResponse from django.views.generic import View from booking.utils import render_to_pdf from django.template.loader import get_template class GeneratePDF(View): def get(self, request, *args, **kwargs): template = get_template('invoice.html') context = { "invoice_id": 1234, "customer_name": "John Cooper", "amount": 1399.99, "today": "Today", } html = template.render(context) pdf = render_to_pdf('invoice.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" %("12341231") content = "inline; filename='%s'" %(filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") and this is my urls.py from django.urls import path from booking.views import GeneratePDF app_name = 'booking' urlpatterns = [ path('invoice/', GeneratePDF.as_view(), name ="invoice"), ] -
How to properly upload files when also sending data to the server
I have implemented an view that is for registering an organization. How do I successfully upload files given the following payload: { "admin":{ "username":"kapyjovu@abyssmail.com", "first_name":"Cindy", "last_name":"Georgia", "password":"password", "email":"kapyjovu@abyssmail.com" }, "org":{ "name":"ARIZONA LAW SOCIETY", "short_name":"ALS", "tag_line":"ALS", "email":"kapyjovu@abyssmail.com", "company_phone": "+2540000000", "po_box": "200", "location":"NAKURU", "first_logo": "https://www.mintformations.co.uk/blog/wp-content/uploads/2020/05/shutterstock_583717939.jpg", "second_logo": "https://www.mintformations.co.uk/blog/wp-content/uploads/2020/05/shutterstock_583717939.jpg", "third_logo": "https://www.mintformations.co.uk/blog/wp-content/uploads/2020/05/shutterstock_583717939.jpg" } } class OrganizationRegistration(generics.CreateAPIView): queryset = Organization.objects.all() permission_classes = (permissions.AllowAny,) serializer_class = OrgRegistrationSerializer """End point to register organization""" def post(self, request, format=None, *args, **kwargs): try: admins = Group.objects.get(name__iexact='admin') admin_role = Role.objects.get(name__iexact="admin") except: # the admin group is admins = Group.objects.create(name="admin") admin_role = Role.objects.create(name="admin") # finally: try: admin = User.objects.create( username=request.data['admin']['username'], email=request.data['admin']['email'], first_name=request.data['admin']['first_name'], last_name=request.data['admin']['last_name'], ) location_name = request.data['org']['location'].upper() location_obj, _ = Location.objects.get_or_create(name=location_name) area_name = location_obj.name except Exception as e: # print(e) return Response(data={"msg":str(e),"success":False, "data": None},status=status.HTTP_400_BAD_REQUEST) # admin.set_password(request.data['admin']['password']) try: # Create Random Password password = User.objects.make_random_password(length=10) admin.set_password(password) admin.save() # add the user creating the Organization to the admin group # admins.user_set.add(admin) admin.groups.add(admins) admin.roles.add(admin_role) first_file_logo = request.data['org']['first_logo'] second_file_logo = request.data['org']['second_logo'] third_file_logo = request.data['org']['third_logo'] org = Organization.objects.create( name=request.data['org']['name'], email=request.data['org']['email'], location=request.data['org']['location'], short_name = request.data['org']['short_name'], tag_line = request.data['org']['tag_line'], company_phone = request.data['org']['company_phone'], po_box = request.data['org']['po_box'], first_logo = first_file_logo, second_logo =second_file_logo , third_logo = third_file_logo ) admin.org_id = org.id admin.save() # add the user creating the Organization to admins by DEFAULT … -
How to access the items inside a list of query sets in django?
I have to display MULTIPLE posts from MULTIPLE users that the logged in user is currently following on a single page using the django templates. This is the function I've written: def following(request, userName): userProfiles = FollowingList.objects.filter(listOwner = request.user) print("userProfile is ", userProfiles) listOfAllPosts = [] #get posts against following for uP in userProfiles: getPosts = Posts.objects.filter(created_by = uP.followingID) print("Value of getPosts is", getPosts) for i in getPosts: listOfAllPosts.append(getPosts.values('created_by', 'postContent', 'dateAndTime')) print("Printing ALL posts", listOfAllPosts) return render(request, "network/following.html", { "listOfAllPosts" : listOfAllPosts }) The result I get from the listOfAllPosts looks like this: [<QuerySet [{'created_by': 12, 'postContent': 'I have hot air balloon rides', 'dateAndTime': datetime.datetime(2021, 1, 30, 4, 21, 3, 192704, tzinfo=<UTC>)}, {'created_by': 12, 'postContent': 'adding second post', 'dateAndTime': datetime.datetime(2021, 2, 1, 7, 2, 51, 734510, tzinfo=<UTC>)}]>, <QuerySet [{'created_by': 11, 'postContent': 'Hello Sifaah', 'dateAndTime': datetime.datetime(2021, 1, 30, 4, 4, 31, 410825, tzinfo=<UTC>)}]>] However, I want the result to look like this so I can easily print it on the HTML page: [<QuerySet[{'created_by': 12, 'postContent': 'I have hot air balloon rides', 'dateAndTime': datetime.datetime(2021, 1, 30, 4, 21, 3, 192704, tzinfo=<UTC>)}, {'created_by': 12, 'postContent': 'adding second post', 'dateAndTime': datetime.datetime(2021, 2, 1, 7, 2, 51, 734510, tzinfo=<UTC>)}, {'created_by': 11, 'postContent': 'Hello Sifaah', 'dateAndTime': … -
Getting to next page via correct user input in Django
i wanted to create some "riddle" page but i got stuck in creating the functionality of the riddle itself. So what I want to do is, I want to have just a plain html page where i can put some text/pictures etc. and at the end of that block there should be a user input prompt with a commit/send button. If the input is the correct answer to the riddle, the user should get to the next riddle stage. If not, he/she should get an info that the answer wasnt correct. As I am learning Django right now I wondered how it should be designed according to it, and therefore I have no sample code or anything. I would really appreciate some help on how to do that, because from what I understand i would need a function that takes the user input, compares it to some kind of a "solution database" and, depending on input, shows the user the specific page. I already found some more sophisticated site protections to mimic this : https://github.com/MaxLaumeister/pagecrypt/tree/master/python but for my causes i think its a bit over the top. Perhaps this topic is interesting for some of you, Thank you! -
Accessing global dictionaries
I don't think there's much explanation to this, the problem is straight forward. I get an error saying Error: "if i in items: NameError: name 'items' is not defined" code: class Cart: items = {} def addToCart(item): global items for i in item: if i in items: items[i] += item[i] else: items.update(item) def removeFromCart(item): global items for i in item: if i in items and items[i] > 1: items[i] -= 1 elif i in items and items[i] <= 1: items.pop(i, None) -
How to Share Files Through Django Channels, now there are incomplete solutions like from S3 buckets and all
I'm developing a chat application in Django and I want to share files through django channels. I just found some solutions that are based on this topic, but all are incomplete. So please help me for figure it out. Now I'm sending messages like the below mentioned code.. document.querySelector('#chat-message-submit').onclick = function(e) { let msg = $('#chat-message-input').val() var messageInputDom = document.querySelector('#chat-message-input'); var message = messageInputDom.value; chatSocket.send(JSON.stringify({ 'command':'new_message', 'message': message, 'from': username, })); messageInputDom.value = ''; } -
How to make Django output PDF from DIV?
I am trying to render PDF from certain DIV (and what is contained within DIV) in Django project. Get a pdf file with contents of "printMe" div.. <div id="dontPrintMe"> content </div> <div id="printMe"> content (including lot of other divs, tables and css) </div> I tried a lot of things.. JSPdf: it would work, but within the DIV i have a lot of tables and JSPdf is giving me errors.. html2canvas: it doesn't work at all, the qualitty is crap xhtml2pdf: this didn't worked at all, no idea why.. Can you recommend me a way, how to output a certain part of a website as a PDF? I think i could do this with Django, but every tutorial i found is about making a pdf from scratch, not converting a current website that is based on template (and html and css) to convert with click of a button to "Download PDF".. for now i am using document.print() and it kinda works, but when saving as PDF it doesn't use generated name for PDF.. And this is actually my first Django project, i just got stucked here.. Maybe it is not possible at all? Thanks! This is what i am using now, … -
Django contact form with user supplied email address without using email delivery service
so my last question was confusing, so I'm hoping this time is better. I want to implement a contact form in django that a user enters their email address into. The one way I've found on how achieve is with an email delivery service like sendgrid, but i want to know if it's possible without an email delivery service. This my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'server.domain.tld' EMAIL_HOST_USER = 'info@domain.tld' EMAIL_HOST_PASSWORD = 'email_password' EMAIL_PORT = 587 EMAIL_USE_TLS = True This is my forms.py: class ContactForm(forms.Form): from_email = forms.EmailField( required=True, widget=forms.EmailInput(attrs={"placeholder": "Your email address", "class": "heading"}), label='' ) subject = forms.CharField( required=True, widget=forms.TextInput(attrs={"placeholder": "Your subject", "class": "heading"}), label='' ) message = forms.CharField( required=True, widget=forms.Textarea(attrs={"placeholder": "Your message here"}), label='' ) This is my views.py def contact_page_view(request): contact_query = ContactForm(request.POST or None) if request.method == 'POST': if contact_query.is_valid(): from_email = contact_query.cleaned_data['from_email'] subject = contact_query.cleaned_data['subject'] message = contact_query.cleaned_data['message'] try: send_mail(subject, message, from_email, ['info@openitmation.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponse('Message successfully sent.') return render(request, 'pagesapp/contact.html', {'contact_sub': contact_query}) The current problem with my code is that it will only send successfully when "from_email" email matches the account in settings.py, times out otherwise. Anyone know how to configure django to send using a user … -
The relationship between Model A and Model B is based on the display of information about Model B from the Model A information filter In django
I have a model called tag in which there is a category field for the input word. Now I want to use the tag model in my product model so that only the words in the product category are displayed I have no idea for it this is TAG model: class TAG(models.Model): class categorychoices(models.TextChoices): general = 'general', _('عمومی') product = 'product', _('محصول') post = 'post', _('مقاله') main = 'main', _('صفحه اصلی') product_list = 'product_list', _('صفحه لیست محصولات') product_detail = 'product_detail', _('صفحه جزییات محصول') gallery = 'gallery', _('گالری') about = 'about', _('صفحه تماس با ما') contact = 'contact', _('صفحه ارتباط با ما') blog = 'blog', _('صفحه بلاگ') category = models.CharField(max_length=15, verbose_name='تنظیم برای', default=categorychoices.general, choices=categorychoices.choices) word = models.CharField(max_length=50, verbose_name='کلمه کلیدی', default=' ') and this is Product model : class Product(models.Model): name = models.CharField(max_length=50, verbose_name="نام محصول") category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, verbose_name="دسته بندی") image = models.ImageField(upload_to="products", verbose_name=" تصویر محصول") video_aparat = models.CharField(max_length=100, verbose_name='لینک ویدیو در آپارات', default='link',help_text='لینک را از قسمت اشتراک گذاری و قسمت embed کپی کنید کلمه embed باید داخل لینک باشد') video_youtube = models.CharField(max_length=100, verbose_name='لینک ویدیو در یوتیوب', default='link',help_text='لینک را از قسمت اشتراک گذاری و قسمت embed کپی کنید کلمه embed باید داخل لینک باشد') tag = models.ManyToManyField(TAG, verbose_name='کلمه کلیدی') active = … -
I deployed a django project on Heroku. When i set debug = True, everything works, when i set debug=False, It gives me server 500 error
I deployed a django project on Heroku. When i set debug = True, everything works, when i set debug=False, It gives me server 500 error both on local server and heroku production server. Allowed hosts is already set. everything is properly configured. Also kindly help me how to handle the secret key in heroku. project is hosted in Git hub. kindly go through the link https://github.com/peter-nani/core_project -
the redis.py causing errors i dont know why it is wrong celery==5.0.5 and redis ==3.5.3 and project is done in docker
celery_shopify1 | celery_shopify1 | Please specify a different user using the --uid option. celery_shopify1 | celery_shopify1 | User information: uid=0 euid=0 gid=0 egid=0 celery_shopify1 | celery_shopify1 | warnings.warn(RuntimeWarning(ROOT_DISCOURAGED.format( celery_shopify1 | [2021-02-02 04:31:16,480: CRITICAL/MainProcess] Unrecoverable error: SyntaxError('invalid syntax', ('/usr/local/lib/python3.8/site-packages/celery/backends/redis.py', 22, 15, 'from . import async, base\n')) celery_shopify1 | Traceback (most recent call last): celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/kombu/utils/objects.py", line 42, in get celery_shopify1 | return obj.dict[self.name] celery_shopify1 | KeyError: 'backend' celery_shopify1 | celery_shopify1 | During handling of the above exception, another exception occurred: celery_shopify1 | celery_shopify1 | Traceback (most recent call last): celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/worker/worker.py", line 205, in start celery_shopify1 | self.blueprint.start(self) celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/bootsteps.py", line 115, in start celery_shopify1 | self.on_start() celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/apps/worker.py", line 139, in on_start celery_shopify1 | self.emit_banner() celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/apps/worker.py", line 154, in emit_banner celery_shopify1 | ' \n', self.startup_info(artlines=not use_image))), celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/apps/worker.py", line 217, in startup_info celery_shopify1 | results=self.app.backend.as_uri(), celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/kombu/utils/objects.py", line 44, in get celery_shopify1 | value = obj.dict[self.name] = self.__get(obj) celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/app/base.py", line 1196, in backend celery_shopify1 | return self._get_backend() celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/app/base.py", line 912, in _get_backend celery_shopify1 | backend, url = backends.by_url( celery_shopify1 | File "/usr/local/lib/python3.8/site-packages/celery/app/backends.py", line 70, in by_url celery_shopify1 | return … -
Django backend with React frontend & using filterset API - how to fetch data?
I have setup an app with a Django backend and React frontend. If I type a URL into a browser I get the correct data back from Django. How do I construct the URL argument for the fetch call in React to take account of the API options? Here's the raw URL that works: 127.0.0.1:8000/api/app/?quantity=2&zip=&id= -
django is_valid returns false for model form even though all fields have a value
Why does this returns an invalid form? I click browse, select a csv file, select a user, check the boolean box, and submit. upload.html <form action = "" method = "POST" class = "mtop-25"> {% csrf_token %} {{form}} <button type = "submit" >Upload File</button> </form> models.py class Csv(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) file_name = models.FileField(upload_to='csvs', max_length = 100) public = models.BooleanField(default = False) def __str__(self): return "File id: {}".format(self.id) forms.py class CsvForm(forms.ModelForm): class Meta: model = Csv fields = '__all__' labels = {'file_name' : 'Browse'} views.py def upload(request): form = CsvForm if request.method == 'POST': form = CsvForm(request.POST or None, request.FILES or None) return HttpResponse(form.is_valid()) else: return render(request, 'upload/upload.html', {'form' : form})