Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
VSCode breaks Django template tags with newline
Problem: {% extends 'base.html' %} {% block title %} Dashboard {% endblock %} {% block pagetitle %} becomes {% extends 'base.html' %} {% block title %} Dashboard {% endblock %} {% block pagetitle %} Note that the {% tag %} is being broken with a new line. This causes syntax errors with django templates. I've tried most top django template extensions and this does not fix the issue. I've also tried these settings: "[html]": { "editor.formatOnSave": false, }, "html.format.wrapLineLength": 0, "html.format.enable": false, "prettier.disableLanguages": ["html"] -
Django model fields with multiple values
How can I create a model with a field that is having a list of values? (For example a model called group with multiple members) Is it possible to implement the relationship with many to many fields? -
Django API ManyToMany on existing databse not working
at the moment I try to get recipes from my API. I have a Database with two tables one is with recipes and their ids but without the ingredients, the other table contains the ingredients and also the recipe id. Now I cant find a way that the API "combines" those. Maybe its because I added in my ingredient model to the recipe id the related name, but I had to do this because otherwise, this error occurred: ERRORS: recipes.Ingredients.recipeid: (fields.E303) Reverse query name for 'Ingredients.recipeid' clashes with field name 'Recipe.ingredients'. HINT: Rename field 'Recipe.ingredients', or add/change a related_name argument to the definition for field 'Ingredients.recipeid'. Models from django.db import models class Ingredients(models.Model): ingredientid = models.AutoField(db_column='IngredientID', primary_key=True, blank=True) recipeid = models.ForeignKey('Recipe', models.DO_NOTHING, db_column='recipeid', blank=True, null=True, related_name='+') amount = models.CharField(blank=True, null=True, max_length=100) unit = models.CharField(blank=True, null=True, max_length=100) unit2 = models.CharField(blank=True, null=True, max_length=100) ingredient = models.CharField(db_column='Ingredient', blank=True, null=True, max_length=255) class Meta: managed = False db_table = 'Ingredients' class Recipe(models.Model): recipeid = models.AutoField(db_column='RecipeID', primary_key=True, blank=True) # Field name made lowercase. title = models.CharField(db_column='Title', blank=True, null=True, max_length=255) # Field name made lowercase. preperation = models.TextField(db_column='Preperation', blank=True, null=True) # Field name made lowercase. images = models.CharField(db_column='Images', blank=True, null=True, max_length=255) # Field name made lowercase. #ingredients … -
How to allow only primary email address to login in django allauth?
I need help. I am using django-allauth for login, signup, and email management. My question is how to log in with only primary email on login page not secondary verified email. what should I do? -
URLconf didn't match Django
I'm new to Django and I'm trying to merge two projects from two different courses RP 1 and RP 2. The problem I'm getting is an unmatched URL configuration: While this is probably one of the most common errors in Django, I can't manage to find a solution to it in this case: My base urls.py file looks like this: It has 3 routes, the default admin/ and 2 custom ones I created for two apps: projects and users. The project one works fine, the problem is that I don't fully understand what the second route should do. Is path(r"^", include("users.urls")) asking Django to look in users.urls when the user enters any URL that doesn't match one of the default paths? The users.urls file looks like this: Can anyone give a tip on what's going wrong here? I am using Django 3.1.3 with Python 3.9. -
How to access atribute of instance I want to validate from inside serializer?
In my view I do following: class ReviewViewSet(viewsets.ModelViewSet): #queryset, serializer_class and permission_classes defined here def perform_create(self, serializer): title_id = self.kwargs.get('title_id') title = get_object_or_404(Title, pk=title_id) serializer.save(author=self.request.user, title=title) I want to validate that review doesn't exist yet. I'm trying to do this in serializer's validate(): class ReviewSerializer(serializers.ModelSerializer): title = serializers.SlugRelatedField(slug_field='pk', read_only='True') author = serializers.SlugRelatedField(slug_field='username', read_only='True') def validate(self, data): title = # <-- How to get title here? author = self.context['request'].user queryset = Review.objects.all().filter(title=title, author=author) if queryset.exists(): raise serializers.ValidationError('Review alredy exists') return(data) class Meta: fields = '__all__' model = Review Attempt to do title = self.title raises AttributeError: 'ReviewSerializer' object has no attribute 'title' How to access title from inside validate() in my case? -
ModelForm has no model class specified. when use model form
Traceback (most recent call last): File "E:\farming\eauth\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\farming\eauth\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\farming\eauth\fwave\farmingwave\views.py", line 14, in contact form = ContactForm() File "E:\farming\eauth\lib\site-packages\django\forms\models.py", line 287, in __init__ raise ValueError('ModelForm has no model class specified.') Exception Type: ValueError at /about_us Exception Value: ModelForm has no model class specified. -
How can I create a model in Django having every Day of the week already nested?
I want to create a model in django, kind of a daily Routine where you fill up your tasks for each day but I want the day name to be kind of 'built-in' for each Routine class. For example like this sort of calendar: Where this is a Routine class where I can insert my tasks for example. So for example on Monday I can add for example 'Paint the room', and 'Read a book', on tuesday I can leave it blank or add only 1 task 'Rest' and so on. my First Idea was creating subclasses for each day but it didn't seem user friendly my current code (doesn't work properly): class Task(models.Model): day = models.CharField(max_length = 10) task = models.TextField() class Routine(models.Model): title = models.CharField(max_length = 128) day = models.ManyToManyField(Task, default = None) I wasn't getting anywhere with this method because I wanted to have every day already inserted and from there I could add multiple tasks to each one, and that is the reason why I wanted to acquire some help. If anyone could help me I would appreciate it a lot. At least I would like to know what method to use for this case or … -
Ajax POST data not passed to the request in Django
I am trying to implement a basic Ajax request to a Django project. The data is send correctly to the XHR object (checked in browser console) but it's not retrieved in the view. // script.js const item_name = "test" fetch('app/add/', { // not hard coded but this is the result in the browser method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({"item_name": item_name}) }) Indeed when I run the code and look at the browser's console, the XHR contains the correct header and body: [XHR] POST http://localhost:8000/api/add/ Request: {"item_name": "test"} Now for the backend part, I have my urls defined correctly urls.py # urls.py urlpatterns = [ path('api/add/', views.add_item) ] And in the views declaration I have: # views.py @login_required def add_item(request): if request.method == "POST": item_name = request.POST.get('item_name', 'default_value') return JsonResponse({"data": item_name}) From there I get back the response and the console shows: Status 200 OK Header Content-Type: application/json Response JSON: {"data": "default_value"} This clearly shows that that in the view, request.POST.get('item_name') doesn't find anything. I am pretty certain that the problem does not come from a django redirection caused by a missing trailing slash (django/ajax: Unable to get Ajax post data in the views.py) … -
React And Django
hello friends please need you help in this one developing a lead manager app with react django rest_frame when i run server it runs fine but when i run this certain command (npm run dev) i get npm run dev lead_manager_react_django@1.0.0 dev C:\Users\SterlingTech\Desktop\lead_manager_react_django webpack --mode development ./leadmanager/frontend/src/index.js --output ./leadmanager/frontend/static/frontend/main.js [webpack-cli] Unknown argument: --output npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! lead_manager_react_django@1.0.0 dev: webpack --mode development ./leadmanager/frontend/src/index.js --output ./leadmanager/frontend/static/frontend/main.js npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the lead_manager_react_django@1.0.0 dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\SterlingTech\AppData\Roaming\npm-cache_logs\2020-11-11T10_02_30_863Z-debug.log (lead_manager_react_django-tk_lVMTa) C:\Users\SterlingTech\Desktop\lead_manager_react_django>python manage.py python: can't open file 'C:\Users\SterlingTech\Desktop\lead_manager_react_django\manage.py': [Errno 2] No such file or directory please help me out -
Python Django csv_exports include data in csv from other related models
I am using django_csv_export module (reference: https://pypi.org/project/django-csv-exports/) because I need to export some data from django admin. In my case, the admin can view 'Orders' through the django admin panel. My model 'Order' is related to another model 'OrderItem' (i.e. an order has at least 1 order item). When exporting I want to show data included in Order and related OrderItem. I simply use: admin.site.register(Order) to register the model in admin, and they are able to export all order data using the module stated above. I am looking for a way to kinda 'merge' Order and OrderItem so that when they export, each order includes data from order item. In pseudocode: I want admin.site.register(AllOrders) where AllOrders = Order + related OrderItem Is there a way to do that? Keep in mind that there can be multiple OrderItems associated to one Order (e.g. OrderItem has one field called 'name', in the example AllOrder it could be 'names' as a concatenated string of all names) Here's the models: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) date_time = models.DateTimeField(auto_now_add=True) total = models.DecimalField(max_digits=6, decimal_places=2) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.DO_NOTHING) product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) # Product has the 'name' field quantity = models.PositiveIntegerField() Any … -
Date and Time in Django template
I tried this solution and also followed this StackOverflow answer But still, it doesn't work. I import it from django.utils import timezone as Timezone library. My models.py from django.db import models from ckeditor_uploader.fields import RichTextUploadingField from django.utils import timezone # Create your models here. class Post(models.Model): title = models.CharField(max_length=300) body = RichTextUploadingField(blank=True, null=True) dop = models.DateField(default=timezone.now) def __str__(self): return self.title Django template {% extends "taskscheduler/base.html" %} {% block title %}{{ post.title }}{% endblock %} {% block main %} <div class="continer homepage"> <div class="row shadow p-3 mb-5 bg-white rounded"> <div class="col"> <h3 class="d-flex justify-content-between align-items-center">{{ post.title }}</h3> <small class="badge badge-info">{{ post.dop | date:"F d, Y"}} {{ post.dop|time:"H:i" }}</small><hr/> <p class="article-content">{{ post.body|safe }}</p> <div class="fb-comments" colorscheme="light" data-href="http://127.0.0.1:8000/p/{{ post.id }}" data-numposts="5" data-width="100%"></div> </div> </div> </div> {% endblock %} But the result still showing only the date. I want to see the date along with the time -
Django Rest Framework: reference serializer of extended group inside user serializer
I extended the Group model in my models.py and created the corresponding serializer, which is working fine. However, when I try to serialize the group field inside the User serializer I only obtain the default fields. Let me show some part of the code: models.py class GroupExtended(Group): description = models.TextField(blank=True) digitaltwin_permissions = models.ManyToManyField( to = DigitaltwinPermission, blank = True, default = None, related_name = "gemelo" ) panel_permissions = models.ManyToManyField( to = PanelPermission, blank = True, default = None, related_name = "panel" ) def __str__(self): return str(self.name) class Meta: verbose_name_plural = "4. Grupos" serializer.py class GroupExtendedSerializer(serializers.ModelSerializer): digitaltwin_permissions = DTPSerializer(read_only=True, many=True) panel_permissions = PPSerializer(read_only=True, many=True) class Meta: model = GroupExtended fields = ['id','name','description','digitaltwin_permissions','panel_permissions','permissions'] class UserSerializer(serializers.ModelSerializer): groups = GroupExtendedSerializer(read_only=True, many=True) class Meta: model = User fields = '__all__' What I obtain with the user API is the following JSON: { "id":1, "groups":[ {"id":2, "name":"Admin", "permissions":[]} ], etc } Whereas I obtain the JSON perfectly serialized with the Groups API, that is, I am getting all new fields. What am I doing wrong? Is it even possible? Thank you! -
model.py module is not connected after loading existing database in Mysql in django
I have an existing database. I imported it into django. With the command python manage.py inspectdb> models.py I created models.py. It has a table stations2: class Stations2(models.Model): id_stations = models.IntegerField(db_column='ID_stations', primary_key=True) # Field name made lowercase. name = models.TextField(db_column='Name', blank=True, null=True) # Field name made lowercase. type = models.TextField(db_column='Type', blank=True, null=True) # Field name made lowercase. country = models.TextField(db_column='Country', blank=True, null=True) # Field name made lowercase. latitude = models.FloatField(db_column='Latitude', blank=True, null=True) # Field name made lowercase. longitude = models.FloatField(db_column='Longitude', blank=True, null=True) # Field name made lowercase. elevation = models.IntegerField(blank=True, null=True) site_gaw_id = models.TextField(blank=True, null=True) stations_id = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'stations_2' accordingly, in the admin.py file, I wrote: from django.contrib import admin from .models import Stations2 admin.site.register(Stations2) I run the command python manage.py runserver, but I don't see any table in the admin panel. I'm trying to run model.py for fun, but I get the error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. As I understand it, to fix it, you need to insert export DJANGO_SETTINGS_MODULE = mysite.settings. However, to be honest, I still did not understand where to … -
Uploading Django to Ionos
I finished my first Django app and I want to upload it online on my domain with a server hosted by Ionos. But I really can't figure it out. NOTE: settings.py is configured for production, I guess. On my website by default, I have this "log" folder with different files in it: Then I uploaded just simply my Django website (the content of the project folder) and so when I type in my domain I get 403 Forbidden Error. So what I tried to do in order to understand better, is that I tried to upload a simple index.html file, and as expected it worked. Then I uploaded an index.html file inside a folder and so I got the same error. It may be this? I really can't get my head around it so any help is hugely appreciated! -
How to extend Django's user model
I'm aware that there is a way to extend the user model in Django along with its authentication app. Is there a way to use an email as the username, and also create a user ID as the primary key? -
TokenRefreshView returns Status Code 500 instead of Access Token
According to this Documentation. if you want to get a new access token from Refresh token. You need to use Request method POST like this: curl \ -X POST \ -H "Content-Type: application/json" \ -d '{"refresh":"somerefreshtokenhere"}' \ http://localhost:8000/api/token/refresh/ Which, in turn I used this code in django to refresh the token everytime the access token is expired: requests.post(url="somekindofurl/refresh-view" ,headers={"Content-Type": "application/json"}, data={"refresh": variable.refresh_token}) However, this returns a full HTML page of status 500 internal server error. Whenever I tried to use Postman, however, it succeeded as you can see, it returns access token as intended. Note the link I used and Refresh token used are the same. I have no idea what cause it to returns 500 status error. -
Import Keras in Django
this question is related to this but the solution didn't help me. I decided to open a new thread because the topic was to old and the proposed solutions did not work. So what's the problem: when i try to import keras, django stop working. When i restart apache in the logs i can see: 2020-11-11 10:01:07.783351: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not load dynamic library 'libcudart.so.10.1'; dlerror: libcudart.so.10.1: cannot open shared object file: No such file or directory 2020-11-11 10:01:07.783383: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. and this is fine. But if i try to access any of my pages they just don't load. Nothing more happen in the log, any error or something. What am i doing wrong? My goal is to use a trained model for sentiment analysis. I'm working on a remote virtual machine with ubuntu 18.04, python 3.6, django 3.1.2, Keras 2.4.3, tensorflow 2.3.1 -
Dropdown does not work after spliting the django form using wizard form
I have a django template as follows: <form method="POST" action="/new_post" enctype="multipart/form-data"> <fieldset class="form-group"> {% csrf_token %} <div class="card-body"> {{ form.tags }} </div> </fieldset> </form> and had a Js script which was doing something once dropdown value was changing, as follows: <script> $("#id_tags").change(function () { var tag_id = $(this).val(); console.log(tag_id); } </script> it works fine but once I change the form to multiple django form using wizard(as below), $("#id_tags").change(function () does not work any more. <form method="POST" action="/new_post" enctype="multipart/form-data"> <fieldset class="form-group"> {% csrf_token %} {{ wizard.management_form }} <div class="card-body"> {{ wizard.form.tags }} </div> </fieldset> </form> I tried also $("#id_0_tags").change(.. but still does not read any value! Do you know why? -
base_url issues in drf_yasg swagger
I am running Django with Nginx in 8000 port. Here Nginx is exposed outside with 8000 port. But in Swagger UI the base_url is set as without port. So Swagger is trying to access endpoints without a port, then it gives a response as TypeError: Failed to fetch. Kindly refer to the below image to know how base_url is set Kindly refer to the below image to know how a request is sent from Swagger When I access the endpoint using Postman it is working fine. The problem occurs only when I try using Swagger (because is sent a request without port). Please help me to resolve this issue. Thanks. Note: I'm using the drf-yasg==1.17.1 package to generate Swagger UI Other requirements are Django==3.0.3 and djangorestframework==3.11.0 -
Read text from specified location in image in python
Is there a way for read text from an image from specific fixed location? def read_image_data(request): import cv2 import pytesseract pytesseract.pytesseract.tesseract_cmd = "C:/Program Files/Tesseract-OCR/tesseract.exe" img = cv2.imread("workcenter_dash.png") text = pytesseract.image_to_string(img) print(text) In above example I used "pytesseract" to read image text which working fine for reading text, But in my case I want read text from specificed location. For Example: In above image, I want read text from only where selected with red rectangle. So please give me best solutions regarding this. Thanks in advance. -
Django sending email from_email arguments
Why is there from_email argument in send_email django function, when we specify EMAIL_HOST_USER in settings.py module? -
How to get all objects in datetime range of every hour?
I want to get the objects with datetime range of every hour any suggestions? summary_exists = table_name.objects.filter(summary_date__range=(date_from, date_to) -
Django sessions behave differently locally and on Heroku
I am sending data from one HTML template to another using a session. Basically, I have something like request.session['send_input'] = send_input in one template and sent_input = request.session.get('send_input') in the other one. The input I'm sending is send_input = { 'artists': context['chosen_artists'], 'songs': input_songs, 'ids': input_ids, } However, I also want to be able to delete data, so I'm doing if not ('chosen_artists' in context) or reset_button: context['chosen_artists'] = [] context['chosen_ids'] = [] context['chosen_songs'] = [] context['ready'] = False context['pasted'] = False del request.session['send_input'] when a user clicks the reset button. Locally, this works fine. The lists containing chosen_artists etc. become empty. But on the server running on Heroku, the behaviour is different and doesn't make sense. Both 'ready' and 'pasted' truly become False, but the lists are not emptied. The only reason I think this might have is that some variables are cached on the server and not locally. Is it possible that local variables created in views.py are cached somehow? P.S. I'm a Django beginner and doing this for a school project. -
Paddle Payments Cancel Subscription url not working
Fairly new to django and I've implemented subscription payments to my django app using dj-paddle module and by reading this guide. I've tried using the subscription update and cancel url's from the guide but clicking on them nothing happens, the page just refreshes. <a href="{{ subscription.update_url }}" class="btn btn-lg btn-primary"> Update Payment Method </a> <a href="{{ subscription.cancel_url }}" class="btn btn-lg btn-danger"> Cancel Subscription </a> The only way i can cancel a subscription so far is via the admin dashboard.