Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Posting multiple values to a single field in django rest framework?
I'm using Django Rest Framework and I'm trying to post multiple value types to a single field in my serializer class. For example, I want to post values for "Temp (C)", "Humidity(%)", "Pyra(WPM)" all under the "value" field. I'm using extra_kwargs in my serializer class to tell my "value" field to accept the different value types I post to it. However, when I try to post using Postman, only the value for the first matching field ("Temp (C)" in this case) will get posted, not all the others. I was wondering if there was a way to have all the field types posted so I don't have to make a new post request for every value type I need? I know I could hardcode these value names into my models.py and serializer.py, but I need to keep models.py how it is right now. Also, here is an example of the JSON I'm trying to post: {"Node ID": "2", "Temp (C)": "22.6", "Humidity(%)": "29.67", "Pyra (WPM)": "118.9", "System Time": "1592287220"} This is the response I get: { "id": 80, "System Time": 1592287220.0, "Node ID": "2", "Temp (C)": 22.6, "units": null, "valueName": null } models.py class DataValueTable(models.Model): timestamp = models.FloatField() sensorName = … -
Links in e-mail are opened by someone else (Django)
I'm running Django on an Apache server on Ubuntu and the activation of a new account via a link in an e-mail fails sometimes. I've checked my access logs and I can see that the activation link is opened by an EC2 server (whois lookup gives an AWS resource, IP is not the public IP of my own server). Any ideas who/what this could be? I have TLS enabled in settings.py for sending emails: EMAIL_USE_TLS = True -
Django template is adding its name to path of image, preventing image from being found
I am working with images uploaded using ImageFields and upload_topath and name, and these images end up in the correct directory media/img/whatevs/. In my settings.py I have the following two lines. MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Now, in the template that matches my / url, these images display properly and I can see/inspect that the path ends up pointing correctly to media/img/whatevs/imgname.jpg However, when I want to display these images in another template called product.html that does not match the / url, then the path ends up pointing to product/media/img/whatevs/imgname.jpg instead of to media/img/whatevs/imgname.jpg, resulting in a 404. Somehow the name of the template is added to the img src path automatically. If I inspect it I see that the text points to media/img/whatevs/imgname.jpg but then if I hover my mouse over it I end up seeing this http://127.0.0.1:8000/product/media/img/whatevs/imgname.jpg. For clarity I add what I have in my files: urls.py urlpatterns = [ path('', HomeView.as_view(), name='home'), path('product/<slug>', ItemDetailView.as_view(), name='product'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Item(models.Model): image = models.ImageField(upload_to=get_image_upload_path) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' product.html, where it does not display <img src='media/img/whatevs/{{ item.slug }}' class="img-fluid" alt=""> home.html, where it displays properly <img … -
Operational Error no such column in Django 3.0
enter image description here I changed the name of the attributes of one of my models. As soon as I made the change in the models.py script, I tried to migrate it using makemigrations command, but it kept giving me an error that the email field is non-nullable and the database needs something to populate the existing rows. So I tried to reverse the previous migrations and ran the command python3 manage.py <app_name> zero. After this the previous non-nullable field error was resolved at the command line but as soon as I submit the form at the browser, I run into this Operational error. The crux of the matter is how to make changes to the attributes of one of the models in models.py and deal with the consequent migrations ? -
Form Validation On Frontend or Backend Django
I have an HTML form with a date field: <input type="date" class="form-control" placeholder="Date" name="date" autocomplete="off" required> Before submitted the form, I want to ensure that the date that was entered is greater than the current date. If it is older, then I want to show a custom form validation to say something like, "You must enter a date past today.". Do you suggest I do this validation on the backend or the frontend? Thanks!! -
ModuleNotFoundError: No module named 'pycurl' error occured while executing celery worker
I am developing Django application. 1.I have a requirement to display the popup message if user input for a text field is not valid. Valid/Invalid text input is based on the response received by performing network operation using PYCURL by passing form username & Password details with pycurl library posting form data using setopt POSTFIELDS to validate input details of a specific field text change in a form using Ajax request. pycurl library is working fine with out any issue . I am able to work on this requirement with out any error. 2.I have another requirement to perform celery task in the back ground, where selenium web driver execution will be done . To start celery task, when i execute "celery -A swat worker --pool=solo -l info" from virtual env, it displays below error: =========================================================================================== "E:\OLD_E_DRIVE_DATA\Python36\Scripts\djangoprojects\SeleniumWebDriverAutomationTool\swat\swatapp\urls.py", line 20, in from . import ajax File "E:\OLD_E_DRIVE_DATA\Python36\Scripts\djangoprojects\SeleniumWebDriverAutomationTool\swat\swatapp\ajax.py", line 15, in import pycurl ModuleNotFoundError: No module named 'pycurl' ========================================================================================== Note: 1.This error is not present when i execute python manage.py runserver from virtualenv. 2.This error message present only when i execute celery worker using another terminal activating virtualenv. Please confirm if any relation between pycurl and celery . Let me know if … -
Django, model logic to create single object when passing varying JSON format message (POST message)
I am creating a E-commerce website with Django. User may select multiple products from frontend ,and send the PO (Purchase Order) to backend. The PO may look like below, { userid:1, { product_id:2,price:33 }, { product_id:3,price:343 }, { product_id:4,price:34 } } note that user can add any number of products ,hence object length may vary. I created a model to accept the PO, class Po(models.Model): user = models.IntegerField() item_id = models.IntegerField() price = models.IntegerField() but above model in incapable to handle the incoming data. Perhaps , should I change the Json format so that individual product will be saved ? -
Django: Creating users with SQL Store Procedures
I'm creating a Django App. The users for this application are our employees. All of our employees are stored in a table called 'EmployeeData'. This table is connected to our HR application and it's updated every x amount of time. I need to create users in my django app according to this EmployeeData table, and at the same time add new users if there are new entries in the table. I was thinking of creating store procedures that would run every x time (the interval of time it runs in doesn't matter at this moment) that would look for new users in this table and then insert them in the auth tables from django. Is this the right approach? Or should I look into creating my own user model? -
Populate django-tables2 with list from views.py
how I can populate a table in html using django-tables2 and a list from views.py? def lista_productos(): django_cursor = connection.cursor() cursor = django_cursor.connection.cursor() out_cur = django_cursor.connection.cursor() cursor.callproc("SP_LISTAR_PRODUCTOS", [out_cur]) lista = [] for fila in out_cur: data = { 'data':fila, 'imagen':str(base64.b64encode(fila[11].read()), 'utf-8') } lista.append(data) return lista -
Reverse for 'results' not found. 'results' is not a valid view function or pattern name
i'm really new to programming, however i've been working on a django project. i was creating a way for users to create posts on the site, however i get the following error: Internal Server Error: / Traceback (most recent call last): File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\dylan\homemade\blog\views.py", line 46, in home_view return render(request, 'home.html', context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 903, in render_annotated return self.render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 903, in render_annotated return self.render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 903, in render_annotated … -
why comment objects has executed the function without removing from database?
I try to remove comment so, I tried the first time by the class-based view then I hashed it to try the second way by normal function to know what's going on here. so, when I try to delete the comment by ID nothing does happen it's just directing me to the web page without deleting the comment so in this case the program runs but doesn't remove the object so, what is going on here? Note: the posts and comments on the same page and slug field on that page are following by post not comment. if the title of the post is: new title so, the slug will be new-title depending on the post question_view.html <div class="user-answer"> <div class="row"> <div class="col-xs-12"> {% for comment in my_question.comment_set.all %} <div class="comments"> <div class="col-xs-0"> <div class="avatar"> <a href="{% url 'account:view_profile' comment.username %}"> <img class="img-circle img-thumbnail" style="width:50px; height: 50px;" src="{{ comment.logo }}"> </a> </div> </div> <div class="col-xs-10"> <!-- --Comment itself-- --> <div class="user_comment"> <p>{{ comment }}</p> <div class="fa fa-caret-left comment-arrow"></div> </div> <!-- start Options in comment --> <div class="sub-options"> {% if request.user.username == comment.username %} <!-- --Edit comment-- --> <div class="edit-comment"> <a>Edit</a> </div> <!-- --Delete comment-- --> <div class="delete-comment"> <form method="post" action="{% … -
How i allow user for login and disable status is changedin enable in django
How i allow user for login if user is_active=False and its in True after login in django any one tell me if you have any idea my code for disable user is below but its run else part............................................................................... in my views views.py def handlelogin(request): if request.method == 'POST': loginusername = request.POST.get('username','') loginpassword = request.POST.get('password','') userr = authenticate(username=loginusername, password=loginpassword) # post = User.objects.filter(username=loginusername,password=loginpassword) if userr is not None: userr.is_active=True userr.save() login(request,userr) return redirect('/user_homeview') return HttpResponse('logged in') return render(request,'user_homeview') else: messages.error(request, "Invalid credintials your Username or Password incorrect! ") return render(request, 'home/login.html') return HttpResponse('login Here') I used this code for disable user def disable_user(request): user = request.user user.is_active = false user.save() messages.success(request, 'Profile successfully Enabled.') return redirect('home') -
Django DateTimeField not showing up properly in browser
I want my django DateTimeField to be inputted the same way I input the values from the admin page, where the dates are selected from a calender. for reference this is how my models.py look like: from django.db import models # Create your models here. class TheDate(models.Model): """A topic the user is learning about""" theDate = models.DateTimeField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """returns a string representation of the model""" return str(self.theDate) forms.py class NewDate(forms.ModelForm): class Meta: model = TheDate fields = ['theDate'] labels = {'theDate': ''} the html page where i have set to create a new plan- new_date.html: {% extends "meal_plans/base.html" %} {% block content %} <p>Add new Date:</p> <form action="{% url 'meal_plans:new_date' %}"> {% csrf_token %} {{ form.as_p }} <button name="submit">Add New Date</button> </form> {% endblock content %} what can i do to the data be inputted in that way i hope the code here is enough and relevant. -
Passing a context variable through a class in Django
how can i pass a context variable in a class. i know that i would use the render if i was showing my template from a function. and then i could just pass my context variable as part of the render. But how do i pass a context variable to html if i am using a class to show the template. i have tried putting a function into my class but it has not worked. views.py class hithere(ListView): model = Datadata template_name = 'index.html' def whatsup(request): context = {} context['my_string'] = "this is my sring" return render(request, context) Index.html <h1> {{ my_string }} </h1> -
Django running on 127.0.0.2:80 on windows works fine but on mac it errors out
I have a django application that I want to run on my Mac for development purposes. On windows python manage.py runserver 127.0.0.2:80 runs fine but on mac I'm getting this error: http://127.0.0.2:80/ Quit the server with CONTROL-C. Error: That IP address can't be assigned to. Running on 127.0.0.1 seems to work fine, is this a mac specific issue? How do I go about solving this. -
What is the best way to store javascript generated innerhtml in the database?
The app that I'm creating is a single page questionnaire. The questions displayed are changed by the press of a button that also saves the answers given in a django form in my database. Through using ajax and Javascript I made it possible to do this without refreshing the page. However the answers are not coupled to the questions in the database. What is the best way to save these questions in the database as well? -
How to export django model as pdf from admin model
How to export django model as pdf from admin model? I tried a lot of things but not worked.. Can anyone explain with full coding/video/images -
is there a way to use the return value of a function as a default value in a django filed?
I want to get the value of the Product_desciption whenever I create a new entry from my admin pannel and pass it through the getimg() function and store the return value in my image filed automatically in my Forimg table. class Products(models.Model): Code = models.CharField(max_length=10) Product_description = models.CharField(max_length=200,primary_key = True) Val_tech = models.CharField(max_length=5) Quantity = models.IntegerField(default=0) UOM = models.CharField(max_length=5) Rate = models.FloatField(default=0) Value = models.FloatField(default=0) def __str__(self): return self.Product_description class Forimg(models.Model): @staticmethod def getimg(item): page = requests.get(f'https://www.google.com/search?tbm=isch&q={item}') soup = BeautifulSoup(page.text, 'lxml') item_head = soup.find('img',class_='t0fcAb') return item_head['src'] products = models.OneToOneField(Products, on_delete=models.CASCADE, primary_key = True) image = models.ImageField(upload_to = 'img/', width_field= 30, height_field = 40) def __str__(self): return self.products.Product_description -
Django Can Not Reach It's Own REST API Using Plotly Dash?
I have a Django instance which has the Django-REST-framework on it running on port 8000. When I write a template that consumes the data served out on the API, I get the following error: urllib.error.URLError: <urlopen error [WinError 10061] No connection could be made because the target machine actively refused it> However, if I run another Django server on the same machine simultaneously at port 7000, it has no problem displaying the data from the other instance's (port 8000) api. It seems as if the Django server can not reach itself. Does anyone know how to fix it? -
Link Header not showing in console
I am building a Django and Vue.js application. In my Django Settings 'DEFAULT_PAGINATION_CLASS': 'drf_link_header_pagination.LinkHeaderPagination', 'PAGE_SIZE': 10 I have a problem with pagination. in console>Network Tab. Link showing. ... Link: <http://127.0.0.1:8000/phones/?page=2>; rel="next", <http://127.0.0.1:8000/phones/?page=10>; rel="last" ... But when I tried to access it in my Vue component. axios.get(`${process.env.BASE_URL}/phones/`) .then((res) => { this.phones = res.data console.log(res.headers.link) }) But it doesn't exist there. It returns undefined. -
How to compare now and datetime field in Django?
If i want to apply check like this in views.py: now=timezone.now() if now <= arrival: messages.error(request, 'Please enter valid Time') return redirect('add_schedule') where arrival is datetime field in models.py It gives error of '<=' not supported between instances of 'datetime.datetime' and 'str', How can i apply this check? -
Django allauth REST social login without DRF
I've been searching quite a while for a solution to integrate social logins provided by Django allauth with a mobile app, but all seem to point towards using DRF. My Django project doesn't have DRF and I'd rather avoid to integrate it, as there are many things that would need to be changed in a rather complex project. Is there any solution to integrate Allauth's social logins via REST in a non-DRF project, or will I have to re-write allauth's views to REST by hand? Thanks -
Sending email notifications to subscribers when new blog post is published in Wagtail
I'm in the process of converting an existing Django project to Wagtail. One issue I'm having is email notifications. In the Django project, I have the ability for people to subscribe to a blog, and whenever a new post is published, the author can manually send out a notification to all subscribers in the admin. However, I'm not sure how to accomplish this in Wagtail. I've read the docs about the page_published signal (https://docs.wagtail.io/en/stable/reference/signals.html#page-published), however, I'm not sure how I could integrate my current code into it. In addition, I would prefer for the author to manually send out the notification, as the author doesn't want to email their subscribers every time a blog post is edited and subsequently published. For reference, the current code I have for the Django app is as follows (it only works if the blog app is in normal Django; because the blog models are now in the Wagtail app, the current code no longer works). models.py class Post(models.Model): """Fields removed here for brevity.""" ... def send(self, request): subscribers = Subscriber.objects.filter(confirmed=True) sg = SendGridAPIClient(settings.SENDGRID_API_KEY) for sub in subscribers: message = Mail( from_email=settings.FROM_EMAIL, to_emails=sub.email, subject="New blog post!", html_content=( #Abbreviated content here for brevity 'Click the following … -
It mind sound like a easy question for most of you. What is the difference between (user) and (User) in django?
User vs user ex: user=instance vs from django.contrib.auth.models import User What is the difference and when should I use each one. The letter cases in django are the most confusing part to me. -
form.save() not working my form.save for updating data isnt working
form.save() not working my form.save for updating data isnt working when i try to update my post it shows the original unedited post it dosent save the updated version.i donnt know whats causing the error idk if its views or anything in template if anyone could help i will be very grateful please help. here is the code: views.py from django.shortcuts import render from django.shortcuts import HttpResponseRedirect from .models import Post from .forms import PostForm def post_list(request): posts = Post.objects.all() context = { 'post_list': posts } return render(request, "posts/post_list.html", context) def post_detail(request, post_id): post = Post.objects.get(id=post_id) context = { 'post': post } return render(request, "posts/post_detail.html", context) def post_create(request): form = PostForm(request.POST or None) if form.is_valid(): form.save() return HttpResponseRedirect('/posts') context = { "form": form, "form_type": 'Create' } return render(request, "posts/post_create.html", context) def post_update(request, post_id): post = Post.objects.get(id=post_id) form = PostForm(request.POST or None, instance=post) if form.is_valid(): form.save() return HttpResponseRedirect('/posts') context = { "form": form, "form_type": 'Update' } return render(request, "posts/post_update.html", context) def post_delete(request, post_id): post = Post.objects.get(id=post_id) post.delete() return HttpResponseRedirect('/posts') urls.py from django.urls import path from .views import post_list, post_detail, post_create, post_update, post_delete urlpatterns = [ path('', post_list), path('create/', post_create), path('<post_id>/', post_detail), path('<post_id>/update', post_update), path('<post_id>/delete', post_delete), ] post_update.html <h1>welcome to post {{ …