Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Everytime I install django for my virtual environment I end up installing it globally. How to install django for virtual environment only?
I am a beginner and trying to learn Django, for that I am working in virtual environment. Whenever I try to install Django in my virtual environment it is installed globally, which is I think I should avoid. Here is the picture of my command prompt.enter image description here -
How to establish a One to One relation in django model in mongo db?
I am using mongo db with djongo in django. I have two models Employee and PresentEmployee. Employee: class Employee(models.Model): employee_id = models.CharField(primary_key=True, max_length=10, null=False, blank=False) employee_name = models.CharField(max_length=200, null=False, blank=False) email = models.EmailField(max_length=500, null=True, blank=True) def __str__(self): return self.employee_name PresentEmployee: class PresentEmployee(models.Model): employee_id = models.OneToOneField(Employee, on_delete=models.CASCADE) present_id = models.IntegerField(null=False, blank=False) id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) def __str__(self): return str(self.employee_id) when I try to add a new object to PresentEmployee, I am getting the error web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 808, in __iter__ web_1 | yield from iter(self._query) web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 167, in __iter__ web_1 | yield self._align_results(doc) web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 269, in _align_results web_1 | if selected.table == self.left_table: web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 133, in table web_1 | return alias2token[name].table web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 133, in table web_1 | return alias2token[name].table web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 133, in table web_1 | return alias2token[name].table web_1 | [Previous line repeated 917 more times] web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 130, in table web_1 | name = self.given_table web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 141, in given_table web_1 | name = self._token.get_real_name() web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 361, in get_real_name web_1 | … -
How to include package.tar.gz to Python project and install it
I have a Django project and it uses folium package, in wich I needed to add some code. Now I have that modded package.tar.gz in my project directory. How to install it upon deploing to Heroku and use instead of original one? -
AttributeError: 'AsyncResult' object has no attribute 'head'
AttributeError: 'AsyncResult' object has no attribute 'head' In my views.py file the error throwing at data = df.head(50) when i'm running and retrive the data as asynchronous background task. Could anybody help me here? task.py @shared_task def eda_flow_task(path, mode): sleep(30) try: with adls_client.open(path, mode) as f: df = pd.read_csv(f, low_memory=False) return 'data load success' except Exception as e: response_dict.update({'error': str(e)}) view.py def eda_flow(request): path = '/data/satyajit/us_amz.csv' mode = 'rb' df = eda_flow_task.delay(path, mode) data = df.head(50) json_records = data.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) context = {'data': data} return render(request, "home/tables-simple.html", context) -
EnvError during Heroku push
I added my gmail password to my .env file located in the root directory of my django project. Why is heroku raising an Env error when I push, is there something else I haven't done? My settings.py file import: from pathlib import Path from environs import Env env = Env() env.read_env() my .env file: DEBUG=True SECRET_KEY = Secretkeyyy DATABASE_URL=sqlite:///db.sqlite3 EMAIL_HOST_PASSWORD = passworddd my refence to the .env email variable in my settings.py: EMAIL_HOST_PASSWORD = env.str("EMAIL_HOST_PASSWORD") the error during heroku push: (.venv) PS C:\Users\user\Desktop\DJANGO_PROJECTS\diary_app> git push heroku HEAD:main Enumerating objects: 345, done. Counting objects: 100% (345/345), done. Delta compression using up to 4 threads Compressing objects: 100% (337/337), done. Writing objects: 100% (345/345), 1007.91 KiB | 79.00 KiB/s, done. Total 345 (delta 48), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-22 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: -----> Installing python-3.10.7 remote: -----> Installing pip 22.2.2, setuptools 63.4.3 and wheel 0.37.1 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting asgiref==3.5.2 remote: Downloading asgiref-3.5.2-py3-none-any.whl (22 kB) remote: Collecting black==22.8.0 remote: Downloading black-22.8.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl … -
django url error this problem is happening only when user is logged in
"Environment of the project: Request Method: GET Request URL: Django Version: 3.0.5 Python Version: 3.10.7" "error is with the template and url" "eg: more details about question ....................................." "error at line 12" "Reverse for 'customer' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['customer/(?P<pk>[^/]+)/$']" 2 : 3 : <div class="homeWrapper"> 4 : <header> 5 : <nav> 6 : <ul class="nav__links"> 7 : <li><a href="{% url 'home' %}">Home</a></li> 8 : <li><a href="{% url 'gallery' %}">Gallery</a></li> 9 : <li><a href="#faqs" class="scroll">About us</a></li> 10 : <!--page is in demo mode after deployment logic will be made here--> ##error is with line 12 11 : {% if user.is_authenticated %} 12 : <li><a href=" {% url 'customer' pk=current.id %} ">Customer</a></li> 13 : {% else %} 14 : <li><a class="scroll" href="#login">Login</a></li> 15 : {% endif %} 16 : {% if request.user.is_staff %} 17 : <li><a href="{% url 'graph' %}">Dash Board</a></li> 18 : {%endif%} 19 : <script src="https://cdn.jsdelivr.net/npm/darkmode-js@1.5.7/lib/darkmode-js.min.js"></script> 20 : </ul> 21 : </nav> 22 : #log " Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/website/views.py", … -
window.close() stopped working after updating to Django 4
I updated packages in my project to latest version, and while testing in Firefox I encountered that window.open() assigned to variable returns Object - debugged with the code below: let test = window.open($(e.currentTarget).attr('href'), '_blank', "height=640,width=480,toolbar=0,location=0,menubar=0"); console.log(test); And, when I close test (this object) using .close() (test.close()) it works just fine, but after upgrading packages (django 3 to 4 version) it stopped working, and test variable returns Window, not Object. I'm not really sure why it works that way, does Django 4 set some custom headers that cause the window close mechanism not work properly? How I should fix that? -
Django Models to calculate discount
I am doing an ecommerce project as my first django project and I am having some trouble on how to calculate my actual price and my discount price if there is a discount price so what I want to do is that if the admin adds a discount to a product I want to add a value to a field inside a model called discount price and in that model I want to calculate how much discount percentage the admin has put in and what the discounted price would be after applying the discount percentage ps: English is my second language and I'm sorry if you were not able to understand tldr : I want to calculate the price and the discount percentage and make the value it to another field in the model called discount price this is my models for the product and discounts(please point out how I should improve and any of my mistakes) from django_extensions.db.fields import AutoSlugField from django.core.validators import MinValueValidator, MaxValueValidator # Create your models here. class Products(models.Model): product_name = models.CharField(max_length=200, unique=True) slug = AutoSlugField(populate_from=['product_name'], unique=True) description = models.TextField(max_length=500, blank=True) price = models.IntegerField(validators = [MinValueValidator(0)]) discount_price = models.IntegerField(validators = [MinValueValidator(0)],null=True) image1 = models.ImageField(upload_to='photos/Products') image2 = … -
Forking Django Oscar's static files doesn't work
I'm trying to fork default oscar's static. My folder structure is the following: myproject/ static/ oscar/ templates/ flatpages/ oscar/ myproject/ And I set the following settings: STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static/' ] Forking templates works just fine, but the same thing doesn't work with static, default files are still served in HTML. To fork static I used this command: ./manage.py oscar_fork_static Any idea why is it so? -
Saving a form created with html as pdf
I have a registration form created with HTML and when I click the save as PDF button, I want the contents of that form to be saved in a certain way. I tried frameworks like jsPDF, but I couldn't solve the UTF-8 problem in them. Can you help with this issue? -
Collapse navbar in html issue
I am making a navbar in django using html, css and bootstrap. I want it to collapse if the view is narrow enough, i have achieved this but it makes a strange thing when you press the menu button, it opens but very widely and strange like this: This is before i click the menu button This is when i click, but automatically it closes the menu and gets back t the 1st image This is my code right now: <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}" /> <title>{%block title%}Base{%endblock%}</title> </head> <body> <style> #github { margin-left: -4; margin-right: 10; } #busqueda { margin: auto; } #logout { margin-left: 5; } </style> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a id="github" href="https://github.com/pabsanort2/hongOS" target="_blank" rel="noopener noreferrer"><img src="{% static 'github.png' %}" alt="enlace github"></a> <a class="navbar-brand" href="/home">HongOS</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar" aria-controls="navbar" aria-expanded="false"> <span class="navbar-toggler-icon"></span> </button> <div id="navbar" class="navbar-collapse collapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/home">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="/clasificar">Clasificar <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="/info">Info <span class="sr-only">(current)</span></a> </li> <!-- <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> --> <!-- <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" … -
Data in 'context' is not passed to HTML
The context within the first conditional statement is delivered well, but the context updated within the second conditional statement is not delivered in HTML. For example, 'MODEL_LIST' in first context is delivered well, but 'mape_val' in second context is not. I want it to be delivered. How Can I solve this problem ? <views.py function CODE> def csv_forecast(request): context = {} username = request.user if request.method == 'POST' and request.FILES.get('csvfile'): uploaded_file = request.FILES.get('csvfile') p_data = pd.read_csv(uploaded_file) p_data.reset_index(drop=True, inplace=True) columns_list = list(p_data.columns) columns_list = [column.lower() for column in columns_list] p_data.columns = columns_list os.makedirs('media/csv', exist_ok=True) p_data.to_csv(f'media/csv/{username}.csv', index=False) start_date = p_data.loc[0, 'date'] len_date = int(len(p_data)*0.8) end_date = p_data.loc[len_date, 'date'] datas = [] for i in range(1, len(columns_list)): datas.append(columns_list[i]) MODEL_LIST = ['ARIMA', 'EMA5', 'LSTM'] context = {'datas' : datas, 'd' : p_data, 'columns_list' : columns_list, 'MODEL_LIST' : MODEL_LIST, 'start_date' : start_date, 'end_date' : end_date} if request.POST.get('sendModel') and request.POST.get('sendPdata') and request.POST.get('sendRdata'): send_pdata = request.POST.get('sendPdata') send_rdata = request.POST.get('sendRdata') send_model = request.POST.get('sendModel') cleaned_pdata = re.split(r'[\[\],"]', send_pdata) cleaned_rdata = re.split(r'[\[\],"]', send_rdata) cleaned_model = re.split(r'[\[\],"]', send_model) selected_pdata = [i for i in cleaned_pdata if len(i) >= 1] selected_rdata = [i for i in cleaned_rdata if len(i) >= 1] selected_model = [i for i in cleaned_model if len(i) >= 1] … -
"GET /style.css HTTP/1.1" 404 2565
Ссылка на мой CSS файл Строение директорий Почему то при запуске сервера ошибка 404 не найден файл style.css пробовал ставить абсолютную адресацию не помогло , если запускать html через IDe то все работает. Как починить, спасибо. -
Field 'id' expected a number
I've defined my custom user model as below (to have email as username): class User(AbstractUser): username = None email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email And Profile model in api app as below: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) verified = models.BooleanField(default=False) def __str__(self): return self.user.email This is the serilizer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['user', 'verified'] And the view: @api_view(['POST']) def get_user(request): email = request.data['email'] user = Profile.objects.get(user=email) serializer = ProfileSerializer(user) return Response(serializer.data) But when I call get_user and post email=myuser@mydomain.com to it, I get this: ValueError at /api/get/ Field 'id' expected a number but got 'myuser@mydomain.com'. -
How can I resolve this linting error? "Consider adding meta keywords. <html lang="en-US"> (H031)"
I'm pretty stumped here. I get that it's telling me I should add meta keywords but which ones ? what am I missing ? -
django is just a cluster fig, is PHP any better?
Am trying to learn Django, I followed several tutorials, followed Django guidelines and I ended up having no idea what am doing. if u want to add an app u have to update it in URLs of the app and connect it to the URLs in the site and update it in the list of apps and connect its function to the action file and update it again in the database file.. it's just a freaking mess to a person who's new to web development, is PHP any better or just the same unfriendliness to users? I designed a python app that took me 56 hrs and now I am tormenting myself with the attempt to make it usable by uploading to a website which made me end up having to learn server-side development, front-end development, and JS development... any recommendations on what should I do now to make my app usable? -
Dangjo with Mongodb, spaces in field name: FieldError: Cannot resolve keyword '' into field
Short-time lurker looking for a bit of guidance. I started a small project to automate a little of the day-to-day. I chose Python and from here I have become interested in programming. About a month ago I decided to keep track of what was going on and hooked up a MongoDB instance to the automated process. Moving onto a GUI using Django. I have hit an issue with one of my views and I suspect the answer will likely be to remove spaces from field names but thought I would ask here as a hail mary :) When trying to apply a filter to my objects it returns the following error: Error: django.core.exceptions.FieldError: Cannot resolve keyword '' into field. Choices are: NP Title ID, Product Code, Product Type, _id Problem model and view below: Model: class Railway_Products(models.Model): _id = models.ObjectIdField(name='_id', editable=False) np_title_id = models.CharField(name='NP Title ID', max_length=15) product_type = models.CharField(name='Product Type', max_length=15) product_code = models.CharField(name='Product Code', max_length=15) class Meta: db_table = "Products" verbose_name_plural = "products" View: class Railway_Products_ListView(generic.ListView): model = Railway_Products context_object_name = 'product_list' queryset = model.objects.filter(name='NP Title ID',__icontains='PPSA') I know the issue is this line: queryset = model.objects.filter(name='NP Title ID',__icontains='PPSA') and name= not enjoying the '' or simply not … -
MongoDB stopped the support for all 32 bits OS a while ago
MongoDB stopped the support for all 32 bits OS a while ago because it's limited to about 2GB of RAM which is simply not enough to run something in production and it was too complicated / costly to support both 32 and 64 bits systems in the code. I am learning MERN Stack Development and I don't have required specs computer (64bit), I learned NodeJs, React And also Express but Stucked at MongoDb because I don't have 64bit computer.I don't understand that how I continue. What technology replaces mongodb in this situation. It that PHP or Django(python). And Here is my Code- const mongoose = require("mongoose"); mongoose.connect("mongodb://localhost:27017/test",{useNewUrlParser:true,useUnifiedTopology:true}).then(()=>{ console.log("mongodb connected successfully!"); }).catch((err)=>{ console.log(err); }); Output- MongooseServerSelectionError: Server at localhost:27017 reports maximum wire version 3, but this version of the Node.js Driver requires at least 6 (MongoDB 3.6) at NativeConnection.Connection.openUri (C:\Users\MASTER\Documents\temp file\MERN With 6PP\mongoDB\node_modules\mongoose\lib\connection.js:824:32) at C:\Users\MASTER\Documents\temp file\MERN With 6PP\mongoDB\node_modules\mongoose\lib\index.js:381:10 at C:\Users\MASTER\Documents\temp file\MERN With 6PP\mongoDB\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5 at new Promise (<anonymous>) at promiseOrCallback (C:\Users\MASTER\Documents\temp file\MERN With 6PP\mongoDB\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10) at Mongoose._promiseOrCallback (C:\Users\MASTER\Documents\temp file\MERN With 6PP\mongoDB\node_modules\mongoose\lib\index.js:1234:10) at Mongoose.connect (C:\Users\MASTER\Documents\temp file\MERN With 6PP\mongoDB\node_modules\mongoose\lib\index.js:380:20) at Object.<anonymous> (C:\Users\MASTER\Documents\temp file\MERN With 6PP\mongoDB\index.js:3:10) at Module._compile (node:internal/modules/cjs/loader:1103:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10) { reason: TopologyDescription { type: 'Unknown', servers: Map(1) { 'localhost:27017' => [ServerDescription] }, stale: … -
DRF use two models in one Serializer
My Profile model has relation with Django's built-in User model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) verified = models.BooleanField(default=False) Looking at the documentation for Nested Relationships my serializers look like this: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['date_joined'] class ProfileSerializer(serializers.ModelSerializer): date_joined = UserSerializer(many=False) class Meta: model = Profile fields = ['user', 'verified', 'date_joined'] And my endpoint: @api_view(['POST']) def get_user(request): user = Profile.objects.get(user=request.user) serializer = ProfileSerializer(user) return Response(serializer.data) How ever I get this error when calling that with email=email address in the body of the request: TypeError at /api/get/ Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x000001C454C28F70> I don't want to use id for query. I want email address to be used. -
How to filter through objects in python? [closed]
I am receieving an array of items from an API like this: { "items": [ { "id": "1", "name": "Item #1", "owner": { "id": "james", "type": "user", }, }, { "id": "2", "name": "Item #3", "owner": { "id": "david", "type": "user", }, }, { "id": "3", "name": "Item #3", "owner": { "id": "david", "type": "user", }, }, ], } Based off this example, how can I return only the items by owner 'david' in my get function in Views? -
Django: how to change table names globally?
I know I can change table name per model using db_table attribute, as explained in the doc. However, what if I want to do it globally? Let's say, I want all my table to be like: db_table = f"table_{{model_name}}" Is there any setting for this? Otherwise, I guess I could use a mixin to be inherited from. However, the whole purpose of doing this is to NOT think of table naming when any developer will add a new model. After reading this issue, It seems maintainers didn't even consider to add this feature as they did not understand the need, which is pretty clear to me :/ Any idea? Thanks. -
I'm using django to build a website and I want to link tutors and students
I'm currently stuck with the best way of assigning tutors to students and then tutors can add lessons for these students and they can both see these lessons, but you can only assign one foreign key to the class "MyLessons". So I'm not sure whether it's worth creating a MyStudents class, storing students inside this (but their user is the same as tutors except is_tutor=false) and then for each student creating a MyLessons class that the tutor can add to. I think I can make an approach I'm just worried it won't be very efficient or there will be some serious problems later on. Such as the other way was that each lesson would auto take in the tutors email (I set the username to email) and then when displaying the tutors lessons it would go through every lesson and display the lessons with a matching email... problems are though, if I reassign a student to a new tutor I'd like the new tutor to see the lessons but this would mean manually changing each and if there are too many lessons and students the process would get slow. -
Edit related field on the edit page of the parent model
My Profile model has a OneToOne field with User model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) verified = models.BooleanField(default=False) And ModelAdmin is defined as below: class UserAdmin(UserAdmin): fieldsets = ( .... .... ('Permissions'), 'fields': ( 'is_active', 'is_staff', 'is_superuser', .... .... Is it possible to add verified filed to the above (after is_superuser for example) so I can edit it in the same page as the rest of the User model? P.S: I've already managed to add it to list_display and list_filter of User. -
Django create db table headers from dict
I am trying to create a model.Model with the columnheaders(key) and types(value). I tried it with the setattr("self",columnheader,columntype) but this seems to not work. Can i dynamically alter the table with django inbuilts or do i have to use raw sql? My example dict: _dict = { "column_1": models.IntegerField(), "column_2": models.IntegerField() } My try class table(models.Model): for columnheader,columntype in _dict.items: setattr("self",columnheader,columntype) -
what are the technogies used to build news website with live steaming
Please specify the steps and required technologies to build website with live steaming option . i am trying to use WordPress but am not sure whether live streaming work in WordPress