Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pass data from django view to Javascript file
I have table data in PostGreSQL which is easily accessed in my Django View. Now I want to pass this data to a javascript .js file whose purpose is to use this data and visualize using d3.js This is what I have tried as an example, but no luck views.py def view_function(request): data = 'test_data' return render(request, 'test.html', context = {'data':data}) test.html <head> </head> <body> <script src="{% static 'test.js' %}">myFunction({{data}})</script> </body> test.js function myFunction(view_data) { console.log(view_data); } -
I Dont Need Any Votes But i need help Please ! DJANGO
I created a post that allows me to upload multiple image and the post contain title, description and image but im trying to be display in this template , but on every post are being displayed all photos not only the photos that have been upload for that post here is my template code {% for post in posts %} <section class="container" style="margin-top: -0.8rem;"> <div class="carousel-inner"> <div style="background-color: #000000" class="card text-center"> <div class="card-body"> <h1 class="card-title" style="color: #FFFFFF; letter-spacing: 6px; font-size: 20px; margin-bottom: -0.7rem;">{{ post.title }}</h1> </div> </div> <div id="{{ post.id }}" class="carousel slide" data-interval="false" data-ride="carousel"> <ol class="carousel-indicators"> {% for p in photos %} <li data-target="#carouselExampleIndicators" data-slide-to="{{forloop.counter0}}" class="{% if forloop.counter0 == 0 %} active {% endif %}"></li> {% endfor %} </ol> <div class="carousel-inner" role="listbox"> {% for p in photos %} <div class="carousel-item {% if forloop.counter0 == 0 %} active {% endif %}" style="background-color: #000000"> <img class="d-block w-100" src="{{ p.image.url }}" alt="First slide"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#{{ post.id }}" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#{{ post.id }}" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <div style="background-color: #000000" class="card text-center"> <div class="card-body"> <p class="container" style="color: #FFFFFF; font-size: 10px; letter-spacing: 2px; text-align: justify; … -
how to create shopping cart? [closed]
hi I'm coding a shopping cart and I write the cars session but I couldn't write the view .I searched and found a code that had the view but it was for django and had forms could you please help me to change the views into django rest framework??? actually my problem is the cart_add function in views this is the code??? #cart CART_SESSION_ID = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(CART_SESSION_ID) if not cart: cart = self.session[CART_SESSION_ID] = {} self.cart = cart def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product for item in cart.values(): item['total_price'] = int(item['price']) * item['quantity'] yield item def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def add(self, product, quantity): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session.modified = True def get_total_price(self): return sum(int(item['price']) * item['quantity'] for item in self.cart.values()) def clear(self): del self.session[CART_SESSION_ID] self.save() #views def detail(request): cart = Cart(request) return render(request, 'cart/detail.html', {'cart':cart}) @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddForm(request.POST) if form.is_valid(): cd = … -
Heroku postge error while django program deploy
I tried many things but no luck. I have uploaded the Django project to Heroku but for Postgres DB I am using Heroku run python manage.py migrate but it does not run shows an error File "/app/main_app/settings.py", line 129, in default=config('DATABASE_URL') NameError: name 'config' is not defined Although, I declared from decouple import config from dj_database_url import parse as dburl DATABASES = { 'default': config('DATABASE_URL', default=DEFAULT_DBURL, cast=dburl) } Please can anyone show a clear example Heroku Postgres database? configuration and then migration command must work? -
Django: Save images from multi-upload Form to Model with an ImageField
I have a MediaModel, with a ThumbnailerImageField from the easy-thumbnails module, which create some thumbnails of the uploaded image: class Media(models.Model): author = models.ForeignKey('Author', on_delete=models.SET_NULL, to_field="name", null=True) keywords = TaggableManager(blank=True) # a django-taggit widget tags = models.ManyToManyField(Tag, blank=True) ... # Resize and compress media_field = ThumbnailerImageField(upload_to=get_filepath, resize_source=dict(size=(1920, 1080), quality=80)) I already have an admin page to create medias, and everything works fine. But now, I have a lot of files (>1000) to upload, and I don't want to do that file by file. So I created a form with a multi images upload: class MassUploadForm(forms.Form): folder = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True, 'webkitdirectory': True, 'directory': True})) author = forms.ModelChoiceField(queryset=Author.objects.all()) tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all()) My view: @user_passes_test(lambda u: u.is_superuser) def mass_upload(request): if request.method == 'POST': form = MassUploadForm(request.POST) if form.is_valid(): files = request.FILES.getlist('files') for f in files: # How to create and save a MediaModel here, with the ThumbnailerImageField pass return HttpResponseRedirect('/mass_upload/') else: form = MassUploadForm() return render(request, 'web_app/admin/web_app/mass_upload.html', {'form': form}) But now I really don't know how to, for each file, create a MediaModel and fill the ThumbnailerImageField... If someone can help me, it will be great :) -
Connection cursor return None after first query
I'm a newbie in Python and working for the first time with Django. My connection.cursor() return None after first call. Here's my problem : def request_pc(request): body = request.body.decode('utf-8') data = json.loads(body) if not firstCheck(data['testValue1']): return JsonResponse({'error': 'foo'}) data = secondCheck(data['testValue2']) if not data: return JsonResponse({'error': 'foo'}) def first_check(testValue1): with connection.cursor() as cursor: row_count = cursor.execute(''' SELECT 1 FROM foo_session WHERE value = %s ''', [testValue1]) if 1 == row_count: return True return False def second_check(testValue2): with connection.cursor() as cursor: row_count = cursor.execute(''' SELECT * FROM core_foo2 WHERE value = %s ''', [testValue2]) res = cursor.fetchone() pprint(row_count) // return 1 pprint(res) // return empty if not res: return False return res first_check return data and everything is ok but second_check return row_count = 1 and data is empty I have the same problem if I copy/paste the first query on the second... Thank you -
On ubuntu sever nginx not able to serve cross-domain image url
I have developed project using Django framework and getting image files from http://data.myothersite.org/data/images/agents/A_1747.jpg In localhost I have tested and able to get all images in my listing page but on live server which has domain http://www.myfirstsite.org & I am not able to get all images which are hosted on http://data.myothersite.org and getting permission denied error. I have tried to set add_header Access-Control-Allow-Origin http://data.myothersite.org/` in nginx conf file but not have any luck. I have tried to find solution online also but not able to find. Thanks. -
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