Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google oAuth2 getting 500 error after redirected to url
I followed all the neccessary steps for login using google. But after login in through a google account, it will redirect to my local URL but get a 500 error. in google cloud platform redirect URL is -- http:localhost:8000/oauth/complete/google-oauth2/ How to fix these? -
How to upload a databse file from local, and access its tables and records from backend(Django)?
I am creating an application where a user uploads a database file from his/her local machine, and I need to show all the tables, rows, and data records from that database file in the frontend. How can I achieve this? Frontend - React Backend - Django -
Django admin action with intermediate page processes only first 100 of selection
I have an admin action where I select artists and then choose an email which I want to sent them. If I filter the artists and then choose select all, I get around 1000 artist. If I sent the email, its only send to the first 100. This is my action: def send_email(self, request, queryset): form = None if 'apply' in request.POST: form = ChooseEmailForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] htmlMessage = email.htmlMessage for artist in queryset: send_single_email(email, artist) self.message_user(request, _('Successfully emailed \'%s\' to the selected artists.') % (email)) return HttpResponseRedirect(request.get_full_path()) if not form: form = ChooseEmailForm(initial={'_selected_action': request.POST.getlist(ACTION_CHECKBOX_NAME)}) return render(request, 'admin/send_email.html', {'artists': queryset, 'email_form': form}) This is my form: class ChooseEmailForm(forms.Form): _selected_action = forms.CharField(widget=forms.MultipleHiddenInput) email = forms.ModelChoiceField(queryset=Email.objects.all(), label='') and this is my html: {% extends "admin/base_site.html" %} {% block content %} <p>Select the email to send:</p> <form action="" method="post"> {% csrf_token %} {{ email_form }} <p>De chosen email will be send to the following artists:</p> <ul>{{ artists|unordered_list }}</ul> <input type="hidden" name="action" value="send_email" /> <input type="submit" name="apply" value="Send email" /> </form> {% endblock %} On the intermediate form it says: 'De chosen email will be send to the following artists:' and lists all 1000 artists. But when I apply, it's only … -
Fail to send email, but no error and exception
I am working on sending an activation email after the user registers an account. Everything works fine in the console. However, when I change to smtp Email backend, the program will stuck at send_mail() and then the program will refresh itself and send back "the username is taken". Finally, no email has been sent. I don't think the email setting is wrong since the program can send the reset password link to any email address. Can someone please help me!!!!!!!!!!! Feel free to leave any comments!!!!!! Here are the pieces of code Thankssss from django.contrib.auth.models import User, auth from django.contrib import messages from django.http import HttpResponse from django.shortcuts import render, redirect from django.views import View from django.core.mail import send_mail, BadHeaderError from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text, DjangoUnicodeDecodeError from .utils import token_generator import requests def send_letter(request, user): uidb64= urlsafe_base64_encode(force_bytes(user.pk)) domain= get_current_site(request).domain subject = "Activate your account" email_template_name = "activation_email.txt" c = { "email":user.email, 'domain': domain, 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': token_generator.make_token(user), 'protocol': 'http',} email2 = render_to_string(email_template_name, c) try: ####The program will stuck here !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! send_mail(subject, email2, 'admin@example.com' , [user.email], fail_silently=False) except Exception as ex: print(ex) class RegistrationView(View): … -
How to return custom messages for each functions in a DRF Viewset?
I'm having a viewset class JobPostView(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] serializer_class = JobPostSerializer queryset = JobPost How will I return custom messages for each function? for eg. if using the get function, I have to return "listed successfully" with data, for the post "posted successfully" with data, likewise for put, patch and delete. -
535, b'Incorrect authentication data when sending email in django project
I am getting this erro while sending email to users The error looks like this:- (535, b'Incorrect authentication data') My settings :- EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myEmail@gmail.com' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 It was working yesterday. Suddenly its not working i dont know what to do? Here is my view where i am trying to send an email to user def send_email_to_user(request, *args, **kwargs): users = User.objects.exclude(username=request.user) if request.method == "POST": sender = request.user receiver = request.POST.get('receiver') subject = request.POST.get('subject') content = request.POST.get('content') send = SendEmailToUser( sender = sender, receiver = receiver, subject=subject, content = content, ) send.save() send_mail( subject, content, # 'itna.sakib@gmail.com', 'noreply.marketage@gmail.com', [receiver], fail_silently=False, ) return HttpResponse("Success") args = { "users": users } return render(request, "adminmailview/send_mail_to_user.html", args) -
Stripe -403 authentication credentials not provided
I am working on an application where I am using Stripe to process my payments. I have tested each and everything in test mode but when I switch to live mode I am facing errors on my web hooks and the error rate is 100% the possible explanation that Stripe returns is: { "detail": "Authentication credentials were not provided." } The status code is: 403. -
How to use authentication in Django application
In my Django application I have a PetOwner model with the following fields: first_name, last_name, email, phone_number, address. I want to create an authentication system now for my users which for now is a PetOwner. I was thinking I should extend from django.contrib.auth.models or more specifically, from django.contrib.auth.models import User I was planning on having a OneToOneField in my PetOwner model to reference the User. Something like the following... user = models.OneToOneField(User, on_delete=models.CASCADE) I'm not sure if this makes sense to do though. Also, I do not want my PetOwner to have access to admin privileges. I'm use to other frameworks like Flask or NodeJS where I would have to hash the password and have a hashed_password saved in a user document or row depending if I'm using sql or nosql. I want to basically make sure that when I am referring to a user I am referring to a PetOwner. -
Dont know how to solve
Back-end Challenge In the Python file, write a program to access the contents of the bucket coderbytechallengesandbox. In there there might be multiple files, but your program should find the file with the prefix_cb_, and then output the contents of that file. You should use the boto3 module to solve this challenge. You do not need any access keys to access the bucket because it is public. This post might help you with how to access the bucket. Example Output contents of some file -
Creating a survey with Django
I am trying to implement a survey in Django and have run into a couple of issues. The survey has two questions and the answer choices are supposed to be represented with radio buttons (the user can only select one choice for their answer). The issues I ran into: I am not able to show only the answer choices that belong to a specific question. For some reason I am getting all answer choices below each question. I have tried editing my models to link specific choices to a question, but still the same issue. 2)After the user clicks "Submit" they are not being directed back to the survey index page nor are their answers saved in the database. Here is what I have so far for my models: User = settings.AUTH_USER_MODEL class Questionnaire(models.Model): questionnaire_name = models.CharField(max_length=255) questionnaire_text = models.CharField(max_length=200) def get_absolute_url(self): return reverse('questionnaire-detail', args=[str(self.id)]) def __str__(self): return self.questionnaire_name class Question_Prompt(models.Model): prompt = models.CharField(max_length=200) questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE, related_name='prompts') def __str__(self): return self.prompt class AnswerOption(models.Model): q_prompt = models.ForeignKey(Question_Prompt, on_delete=models.CASCADE, related_name='answers') questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE, related_name='responses', default='') answer_text = models.CharField(max_length=200) def __str__(self): return self.answer_text class UserAnswer(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) questionnaire_taken = models.ForeignKey(Questionnaire, on_delete = models.CASCADE) questionnaire_date = models.DateTimeField(auto_now_add=True) … -
Django view URL after deployment with Gunicorn
I have a Django backend and a React frontend that have been working perfectly before deployment. I ran: nohup python manage.py runserver my_server_ip:8000 & In this case, the view can be called by React with: my_server_ip:8000/app1/view1 After that, I deployed Django with Gunicorn and React with Nginx, Nginx config: server { listen 80; root /path_to_react_build_folder; server_name my_server_ip; index index.html; location = /favicon.ico { access_log off; log_not_found off;} location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } Gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target Gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=my_username Group=www-data WorkingDirectory=/home/my_username/django_project_root ExecStart=/home/my_username/python_virtualenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock django_project_root.wsgi:application [Install] WantedBy=multi-user.target Connection was okay as I typed my_server_ip in browser (i.e. default to index.html set in Nginx config). All static things like background color and banner displayed normally but I couldn't get the result from API call. Browser console showed: GET http://my_server_ip:8000/app1/view1 net::ERR_EMPTY_RESPONSE How can I let React access Django's view in this case? -
how can i use sql console on web?
I want to make web page to practice SQL Query. User can type SQL sentence and check the result. I think that needs SQL console that operating on Web, How can I build SQL console on Web? Is there any good tools? +) I'm developing with DRF and Vue.js. -
Ajax calls not calling on a PWA
I just covert a django project to a pwa using django_pwa. Before hand, the project worked perfectly. Part of the project, I am making GET and POST requet using ajax. Now that it is a pwa, it seems like ajax is not making these calls. Any reason why? I know pwa are still a bit new, and I can't seemed to find anything related to both of these on google or yourtube. -
How to easily extract request.POST data after Django form submission?
My request.POST data looks like this after my Django form submission: <QueryDict: {'form-0-country': ['19389'], 'form-0-city': ['Montreal'], 'form-0-eid': ['450'], 'form-0-company': ['Nestle'], 'form-0-dept': ['HR'], 'form-1-country': ['19390'], 'form-1-city': ['Toronto'], 'form-1-eid': ['432'], 'form-1-company': ['Nestle'], 'form-1-dept': ['Finance']}> These are values of two forms contained in two different rows on the webpage. The values from these two rows are printed sequentially in the request.POST. Is there a way to get this data printed in the backend in a simpler way so that I don't have to loop through all this data to extract the specific fields contained in it? For eg. something like this: <QueryDict: {'form-0-country': ['19389','19390'], 'form-0-city': ['Montreal','Toronto'], 'form-0-eid': ['450'], 'form-0-company': ['Nestle','Nestle'], 'form-0-dept': ['HR','Finance']> so that I can easily loop through the value (lists) in the dict above. instead of: <QueryDict: {'form-0-country': ['19389'], 'form-0-city': ['Montreal'], 'form-0-eid': ['450'], 'form-0-company': ['Nestle'], 'form-0-dept': ['HR'], 'form-1-country': ['19390'], 'form-1-city': ['Toronto'], 'form-1-eid': ['432'], 'form-1-company': ['Nestle'], 'form-1-dept': ['Finance']}> -
django permission based on AD group membership
I'm trying to grant access to specific URLs and menu links in base.html file based on AD groups an authenticated users belong to. The AD instance is fairly large but it also includes deeply-nested AD groups, so, quering the AD server for every HTTP request is an expensive one. A solution I'm think of at the moment is to write a custom middleware that queries the AD server the first time a user access the application, I query the AD server one time, get all the access levels they should have and store this information in a session, then, when they make another request, I check the session values first if I already set permissions for that specific user, this should avoid querying the AD server everytime. Given this criteria, is there any native django authorization classes/technique that is able to handle this sort of access privilege? -
Django: as_view: How does cls and initkwargs are passed to view function
I am trying to understand the as_view code for Class based views. I see self = cls(**initkwargs) How the view function get cls and initkwargs I have put an image to mean what I want to ask -
Paginating Django View with Foreign Key Data
I'm trying to build a simple Django gallery that allows photos to be added to an album. Everything thus far is working fine (upload photo, add to album, paginated all photos listing, photo details/display pages, etc), until I try to display the 'album' pages. I can get the page to render the the album and all of the associated photos, but if I try to paginate the album, things start to get weird. Here are my models: # models.py class Albums(models.Model): id = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=500) slug = models.SlugField(max_length=500, unique=True) description = models.TextField(blank=True, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) return super().save(*args, **kwargs) class Photos(models.Model): id = models.AutoField(primary_key=True, unique=True) album = models.ForeignKey( Albums, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Album" ) photo = models.ImageField(upload_to="photos/") slug = models.CharField(max_length=16, null=False, editable=False) # I know I'm not using a SlugField here; that's on purpose title = models.CharField(max_length=500) description = models.TextField(blank=True, null=True) upload_date = models.DateTimeField( default=timezone.now, verbose_name="Date uploaded" ) def __str__(self): return self.title def save(self, *args, **kwargs): [...] # stuff to get the image's EXIF data and use that to set the slug self.slug = str(datetime.strftime(img_date, "%Y%m%d%H%M%S")) [...] # plus a bunch of other stuff that happens … -
Django dynamic url parameters
I'm trying to make an example for a product page where people can put designs on their product's. I'm using django and try to make my "designer" page behave differently on the type of product selected. I want to have it behave like www.mysite.com/designer/foo where foo is the name of the product I have gotten to make it work like www.mysite.com/designer?product=foo but i like the simplicity of the first url more and i can't imagine that wouldn't be possible. urlpatterns = [ path('', overview, name='overview'), path('designer/', designer, name='designer'), path('administration/', administration, name='administration'), path('admin/', admin.site.urls), ] my url patterns are like this, i've tried fiddling around with some examples using regex behind the "/" after designer. but i can't get it to work, the server keeps trowing Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/designer/exampleA I'm afraid i don't know where to start looking and how to properly formulate my question as webdeveloping is quite new to me. -
create dynamic feedback form using Django
I am trying to create a dynamic feedback form using Django in which form creator can ask anything in any format(i.e. Boolean, text, etc). Is there any way to do this. Thanks :) -
Twilio - how to handle inbound sms
I just made an account on twilio and I was able to configure things so that I can send sms through a django app I wrote. However, now I am trying to understand what hapens to inbounds sms. Basically, if someone replies to the message that they receive through my Twilio, what happens to that text? -
Django return PDF from chromium with custom name
I am using chromium within django to export a PDF file. It is working well, but the exported file "myfile.pdf" is saved to my app's root directory. I am trying to determine the best way to serve the file with a custom name and date, while also not filling the web app with these left over files. Should I use a temporary directory? Here is my code so far: class PrintPDF(DetailView): template_name = "print.html" def get(self, request, *args, **kwargs): html_file = self._create_html_file(request) cmd = settings.PDF_EXPORT_COMMAND cmd_options = [ "--headless", "--print-to-pdf=myfile.pdf", "--disable-gpu", "--run-all-compositor-stages-before-draw", "--virtual-time-budget=10000", "--force-device-scale-factor=1", "--no-sandbox", "--disable-dev-shm-usage", html_file, ] subprocess.check_call(cmd + cmd_options, timeout=600) os.remove(html_file) return FileResponse(open("myfile.pdf", "rb"), content_type="application/pdf") def _create_html_file(self, request): self.object = self.get_object() context = self.get_context_data(object=self.object) html = render_to_string(self.template_name, context, request) tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".html") with open(tmp.name, "w") as f: f.write(html) return tmp.name -
Limit Django data to current user
Hoping you can help me. I am trying to run the below - for ONLY the current requesting user. But it pulls back the data for all users. Can you help me to figure out why that is? open_tasks = skills.objects.filter(creator=request.user).raw(''' SELECT *, round(((closed_points)/(open_points+closed_points)*100),2) as points_pct, round(((closed_count)/(open_count+closed_count)*100),2) as closed_pct from ( SELECT id, sum(open_points) as open_points, sum(closed_points) as closed_points, sum(open_count) as open_count, sum(closed_count) as closed_count from ( SELECT id, case when status = 'open' then sum(points) end as open_points, case when status <> 'open' then sum(points) end as closed_points, case when status = 'open' then sum(count) end as open_count, case when status <> 'open' then sum(count) end as closed_count from ( SELECT category as id, status, sum(cast(points as int)) as points, count(*) as count FROM voximisa_skills group by category, status)s group by id, status)p group by id)j ''') -
Django-how to set only one review per user and movie
movies_detail.html {% extends 'base.html' %} {% block content %} <img src="{{ articles.image.url }}" width="200px" height="300" style="display: inline-block;" > <div id="movie_plot"> <h2>{{articles.title}}</h2> <p>{{articles.plot}}</p> {{articles.category}} <p>{{articles.cast}}</p> </div> {% if isReviewAllowed == True %} <div class="isReviewAllowed"> <div class="nav_button"><a class="new_movie" href="{% url 'movies:review' slug=articles.slug %}">Create Review</a></div> </div> {% endif %} {% for review in all_reviews %} {% if review.Review == movie.title %} <div class="all_reviews"> <div class="review"> <p><span style="font-weight: normal;">Reviewed by: </span> {{review.user}} </p> <p><span style="font-weight: normal;">Description: </span>{{review.text}}</p> <form style="text-align: center;" action="{% url 'movies:like' slug=articles.slug %}" method="post"> {% csrf_token %} <button style="color: white; background: #104e89;" type="submit", name="review_id", value="{{ review.id }}", class="btn btn-primary btn-sm">Like</button> {{review.count_likes}} </form> </div> {% elif review.movie.title == movie.title %} <div class="review"> <p><span style="font-weight: normal;">Reviewed by: </span> {{review.user}} </p> <p><span style="font-weight: normal;">Description: </span>{{review.text}}</p> </div> </div> {% endif %} {% endfor %} {% endblock %} so the problem is when i create review with (for example:nir_user make review for batman movie) the review appears in all the movies and not in the specific movie tell me please if you want me to show you more code. -
Working with websockets on multiple tab to check realtime send and receive events
I am stuck in a strange situation. I don't know how to describe it. Well, I have set up WebSockets in my project, On the client side I'm using react, And on the server side, I'm using Django channels. On a single tab, all flow is working fine. e.g : I'm sending data from the client-side with sockets to the server and receiving it back on the client-side. but on the other tab, it doesn't receive at the same moment or we can say real-time receiving . I'm basically trying to build a notification system on WebSockets. -
How to fix 500 internal server error while using Django and React
I'm trying to create a simple shopping cart with django and react. When I click on the add-to-cart button I get 500 Internal Server Error from react. The error it's displaying in django is: ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x00000268F76AEFA0>": "order_product.user" must be a "User" instance. I have tried every means I know but I'm still not able to fix it. Below is the programme: DJANGO urls.py path('add-to-cart/', add_to_cart_view.as_view(), name='add-to-cart'), views.py class add_to_cart_view(APIView): permission_classes = [] def post(self, request, *args, **kwargs): id = request.data.get('id', None) if id is None: return Response({"message": "Invalid request"}, status=HTTP_400_BAD_REQUEST) product = get_object_or_404(Product, id=id) requested_product = order_product.objects.create( product=product, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if not order.products.filter(product__id=requested_product.id).exists(): order.products.add(requested_product) return Response(status=HTTP_200_OK) else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.products.add(order_product) return Response(status=HTTP_200_OK) REACT export const AddToCartURL = "http://127.0.0.1:8000"; const handleAddToCartURL = async (id) => { try { const res = await axios.post(`${AddToCartURL}/add-to-cart/`, {id}); setProduct(res.data); console.log(res.data) } catch (err) { } }; return( <Box sx={{ flexGrow: 1 }} m={4}> <Grid container spacing={3}> <Grid item xs={9}> <Item> <img src={product.image} alt="" /> <div> <p>{product.description}</p> <p>{product.label}</p> <p>{product.price}</p> </div> <button color='primary' onClick={() => handleAddToCartURL(product.id)}> <AddShoppingCartIcon /> </button> </Item> </Grid> <Grid item xs> <Item>Similar Products</Item> …