Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'Manager' object has no attribute 'remove'
I am trying to allow a logged in user to delete their comment under a comment section, but I keep getting the error thrown in the title, and I'm not sure why. I've read up on Managers in the docs but don't quite understand what the issue is, as all my other models work just fine. Here is the code views.py def delete_comment(request, comment_id): comment_details = Comment.objects.get(id=comment_id) # Throws error at this line Comment.objects.remove(comment_details) return HttpResponseRedirect('view') models.py class Comment(models.Model): comment = models.CharField(max_length=64) item = models.ForeignKey('Listing', on_delete=models.CASCADE, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.comment}" -
Error: Cannot import 'account'. Check that 'accounts.apps.AccountConfig.name' is correct
When I run python manage.py runserver in Django, I get the following error. Error django.core.exceptions.ImproperlyConfigured: Cannot import 'account'. Check that 'accounts.apps.AccountConfig.name' is correct. I tried everything but could not figure it out. What should I do? acconuts/apps.py from django.apps import AppConfig class AccountConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'account' mysite/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'app', 'accounts', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', ] -
i have a problem with docker. service "todo" is not running container
i trying to make a docker-compose for my django project but when im using "docker-compsoe exec" i geting this error. service "todo" is not running container im expecting when write "docker-compose exec todo sh -c "python startapp todolist" its make an app but its not happend and i getting this error. "service "todo" is not running container" enter image description here enter image description here -
Debug of django {{form.as_p}} in html
I am a beginner in django with python, I confront a problem about the TemplateDoesNotExist in django/forms/errors/list/default.html, Is anyone know the solution? Error capture I already tried remove the {{form.as_p}} in my html, the page is work without the form. Therefore, I guess the problem may come from the modalform I made, but I still not find the wrong. -
Remove port from URL - Django Apache2 Gunicorn
I would like to know how to omit the port number from my URL. I currently host a website on an Apache Ubuntu server on port 443 and redirect any http traffic to the https version of the site. (www.mycompany.com) However, I also run a Django server on the same Apache VPS using Gunicorn, currently on port 8000 and would like to achieve the URL of www.mycompany.com/blog My current situation for the URL is www.mycompany.com:8000/blog I have tried altering the ports that the Django server runs on to 443 and 80, but quickly realised the firewall won't allow that. I am not sure what to do. Do I have to do a reverse proxy? This is my first time doing this so any help is greatly appreciated. -
How can a model be cleared (Django ) when moving to another page or reloading the current one?
Good day! I ask for help please, this is very important for me, can someone tell me something. I have a page template. And a view made for it. I also have code with various operations on models in this view. When there is a transition on this page - representation, I have a form in which I place the processed data. When I reload the page or go to another page - view, the data in the form remains unchanged because I use a model specially made for this as the data source for the model. I need to clear the model or do some other operation when I leave this page to another one or reload it. -
DRF: Dynamic literal type hint for models.TextChoices
Given this model from django.db import models class Olympian(models.Model): MedalType = models.TextChoices('MedalType', 'GOLD SILVER BRONZE') medal = models.CharField(max_length=6, choices=MedalType.choices, default=MedalType.GOLD) and this function which takes in the CharField as a param fn_with_type_hint(olympian.medal) How can I type hint the param more strictly without hard-coding like this? def fn_with_type_hint(medal: Literal['Gold', 'Silver', 'Bronze']): pass What I tried I tried Olympian.medal but it's just a string medal: Olympian.medal I also tried variations of this to no avail medal: Literal[*Olympian.MedalType.values] I also can't use this solution because I don't start with a list of strings https://stackoverflow.com/a/64522240/8479344 -
Unable to host Tensorflow model on Heroku
I am trying to host a Django application that holds a tensorflow model on heroku. When pushing to the heroku application I receive this error: "Could not find a version that satisfies the requirement tensorflow-intel==2.11.0." From what I understand heroku runs pip install requirements.txt, so I am not sure why it would not be able to find that version. Screenshot of output from trying to push to heroku Any explanations or solutions would be appreciated. Also if there is a better way to host a tensorflow model, please let me know. -
Django 403 forbidden only happens at login in prod environment
I have a Login using the Django Login/authentication, once I Post the request to login I get the 403 Forbidden error with the following message: CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. This only happens with the login and not with the other forms that I have in my application. this is my login form: {% extends "main/base.html" %} {% load static %} {% load widget_tweaks %} {% block content%} <div class='container'> <div class='row pt-4'> <div class="col"> </div> <div class="col-md-4 col-md-offset-4"> <div class="card text-center"> <!-- Login Form --> <div class="card-header bg-dark"> <h2 class="text-secondary">Login</h2> </div> <div class="card-body card text-left"> <form method="POST"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form.visible_fields %} <div class="form-group"> <label>{{ field.label_tag }}</label> {% render_field field class="form-control" %} {% for error in field.errors %} <span class="help-block">{{ error }}</span> {% endfor %} </div> {% endfor … -
How to connect django to MS-SQL server in pycharm?
error as - No matching distribution found for ms-sql I am unable to connect to the ms-sql server with the command "pip install ms-sql django". In previous projects, I was able to connect using the same command. it's not working now. This command uninstalls Django 4.1.1 version and installs the 4.0.7 version. But, now, its giving an error. Is there any update? please advise how to connect django to MS-SQL server using pycharm. -
Filtering one model with the id column of a different model in Django
I want to display a table in HTML which contains columns from two different tables/models. The models look something like this: class Vor(models.Model): id_vv = models.BigIntegerField(db_column='ID_VV', blank=True, null=False, primary_key=True) vdat = models.DateField(db_column='VDat', blank=True, null=True) v_li = models.TextField(db_column='V_Li', blank=True, null=True) ... # more columns/objects exist and class VorDet(models.Model): id_det = models.BigIntegerField(db_column='ID_Det', blank=True, null=False, primary_key=True) v_li = models.TextField(db_column='V_Li', blank=True, null=True) v_twg = models.TextField(db_column='v_twg', blank=True, null=True) ... # more columns/objects exist vor = models.ForeignKey(Vor, on_delete=models.CASCADE, blank=True, null=True) #empty as it was not part of the legacy data table The data in the DB was imported from csv files (legacy data base from access) using ./ manage.py migrate --fake -initial. So models.ForeignKey() is empty - I'm not quite sure if that matters or not. I need to display vdat, v_li and v_twg in the same list. id_vv has a one-to-many connection to id_det and only becomes unique if the v_li-columns also match. Right now I can solve the problem by: filtering the first model Vor by vdat Using the the output of 1. I input id_vv values into VorDet.objects.filter(id_det__in=...) then merge both outputs via pd.merge() vor_list = Vor.objects.filter(vdat__startswith="2022").values() det_list = VorDet.objects.filter(id_det__in=[x['id_vv'] for x in vor_list]).values() comb_list = pd.merge(pd.DataFrame(vor_list), pd.DataFrame(det_list), left_on = ['id_vv', 'v_li'], right_on … -
FATAL: role 'postgres' does not exist
I've been dockerizing an app with postgresql and making it ready for production. However, when going back to work to a different app (that also is using PostgreSQL), I'm not able to run the django server, neither to access to PostgreSQL 14 server inside of Pgadmin. When trying to initializate the server in the Pgadmin, there is this message error when entering the password: connection to server at "localhost" (::1), port 5432 failed: could not initiate GSSAPI security context: The operation or option i s not available. Credential for asked mech-type mech not found in the credential handle connection to server at "localhost" (::1), port 5432 failed: FATAL: role "postgres" does not exist I was using this database normally and without problems, both from Django local development server as well as from Pgadmin. Django project database's user is a different user, but also says role 'username' does not exist. I tried to follow other answers but can't make it work. How could I have messed it up? -
Max retries exceeded with url: Failed to establish a new connection: [Errno 111] Connection refused'
I keep getting this error: HTTPConnectionPool(host='127.0.0.1', port=8001): Max retries exceeded with url: /api/v1/auth/sign_in (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f0f8cbdd430>: Failed to establish a new connection: [Errno 111] Connection refused')) I searched through the stackoverflow and couldn't find the solution that would help me. Here's my code example: host = 'http://127.0.0.1:8001' response = requests.request(method=request_data['method'], url=f'{host}/{settings.ACCOUNTS_API_PREFIX}{request_data["url"]}', json=json_data, params=params, headers=headers, ) Basically I'm trying to send a POST request to authenticate myself on the service, however I keep getting the above error. I have 2 containers - one is a web application (Django), another one is accounts that stores all details of the users to authenticate them. Both containers are up and running, I can open the website, I can open the API swagger for accounts, however I can't send the POST request and get any response. Can someone assist me to figure it out? -
how to give the client argument in django management commands?
I have a function in django management commands that should take a url as an argument class Command(BaseCommand): help = u'Enter the url' def add_arguments(self, parser): parser.add_argument('url',type=str,help=u'Enter the url') def handle(self,*args,**kwargs): url = kwargs['url'] main(url) it doesn't matter what the function is, everything in it works when a command is called through the terminal but I have a question, how can I implement this into the client part? I want the user to enter a url and it is passed to the function. What are the ways to pass user arguments to django management commands? -
SQL: Join information from two tables
I have three relational postgres tables (timescale hypertables) and need to get my data into a CSV file, but I am struggling to get it to the format I want. I am using django as frameworks, but I need to solve this with raw SQL. Imagine I have 2 tables: drinks and consumption_data. The drinks table looks like this: name | fieldx | fieldy ---------+--------+------ test-0 | | test-1 | | test-2 | | The consumption_data table looks like this: time | drink_id | consumption ------------------------+-------------+------------------------------ 2018-12-15 00:00:00+00 | 2 | 123 2018-12-15 00:01:00+00 | 2 | 122 2018-12-15 00:02:00+00 | 2 | 125 My target table should join these two tables and give me all consumption data with the drink names back. time | test-0 | test-1 | test-2 ------------------------+-------------+---------+------- 2018-12-15 00:00:00+00 | 123 | 123 | 22 2018-12-15 00:01:00+00 | 334 | 122 | 32 2018-12-15 00:02:00+00 | 204 | 125 | 24 I do have all the drink-ids and all the names, but those are hundreds or thousands. I tried this by first querying the consumption data for a single drink and renaming the column: SELECT time, drink_id, "consumption" AS test-0 FROM heatflowweb_timeseriestestperformance WHERE drink_id = 1; … -
Django REST framework - parse uploaded csv file
I have setup Django REST framework endpoint that allows me to upload a csv file. The serializers.py looks like this: from rest_framework import serializers class UploadSerializer(serializers.Serializer): file_uploaded = serializers.FileField() class Meta: fields = ['file_uploaded'] In my views.py file, I'm trying to read data from uploaded csv like this: class UploadViewSet(viewsets.ViewSet): serializer_class = UploadSerializer def create(self, request): file_uploaded = request.FILES.get('file_uploaded') with open(file_uploaded, mode ='r')as file: csvFile = csv.reader(file) for lines in csvFile: print(lines) I'm getting the following error: ... line 37, in create with open(file_uploaded, mode ='r') as file: TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile I have checked type() of file_uploaded and It is <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> How can I read this file into dictionary or dataframe so I can extract the data I need from it? -
Django Models multiple foreign key relationship
say I have a model, e.g.,: class Topic(models.Model): date = models.DateField(null=False, blank=False) subject = models.ForeignKey(Subject, blank=False, null=False, on_delete=models.CASCADE) topic_id = models.PositiveIntegerField(null=False, blank=False) aggregate_difficulty = models.PositiveIntegerField(null=False, blank=False) class Meta: constraints = [models.UniqueConstraint(fields=["subject", "date", "topic_id"], name="topic_unique")] And we have another model, e.g.,: class Module(models.Model): date = models.DateField(null=False, blank=False) subject = models.ForeignKey(Subject, blank=False, null=False, on_delete=models.CASCADE) topic_id = models.PositiveIntegerField(null=False, blank=False) content = models.TextField() difficulty = models.PositiveIntegerField(null=False, blank=False) How can I create a foreign key relationship from module to topic using the three fields: date, subject and topic_id? I would like to have this format, so the person inserting into the database would not have to find out the auto-generated topic id before inserting into the module table. There are many modules to one topic and many topics to one subject. -
webpack main.js file size is 6.3 in "webpack --mode production"
I am using webpack to combine django & React js. but main.js bundle file is too large (6.3 MB) so the page to much time to load webpack.config.js const path = require("path"); const webpack = require("webpack"); const NodePolyfillPlugin = require("node-polyfill-webpack-plugin"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, // Additional configuration to handle *.css files { test: /\.css$/i, use: ["style-loader", "css-loader"], }, { test: /\.svg$/, use: ["@svgr/webpack"], use: [ { loader: "svg-url-loader", options: { limit: 10000, }, }, ], }, { test: /\.(png|jpg)$/, type: "asset/resource", }, ], }, optimization: { minimize: true, }, performance: { hints: false, maxEntrypointSize: 512000, maxAssetSize: 512000, }, plugins: [ new NodePolyfillPlugin(), new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production"), }), ], }; babel.config.json { "presets": [ [ "@babel/preset-env", { "targets": { "node": "10" } } ], "@babel/preset-react" ], "plugins": ["@babel/plugin-proposal-class-properties"] } My pakage.json Installed is "webpack": "^5.75.0", "webpack-cli": "^5.0.0" I am unable to optimize with minimize = true Its show error when minimize = true ERROR in main.js main.js from Terser plugin -
ValueError at /borrow/
I am tryin to automatically populate a table B whenever a user fills out a form that populate tableA. Whenever i fill out the form to populate table A, i run into this error. Traceback (most recent call last): File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dubsy/virtualenvs/djangoproject/libmain/books/views.py", line 21, in borrow borrower.save() File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/db/models/base.py", line 812, in save self.save_base( File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/db/models/base.py", line 878, in save_base post_save.send( File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 176, in send return [ File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 177, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/home/dubsy/virtualenvs/djangoproject/libmain/books/models.py", line 84, in create_lending ApprovedLending.objects.create(member=row["member_id"]) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/db/models/query.py", line 669, in create obj = self.model(**kwargs) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/db/models/base.py", line 541, in __init__ _setattr(self, field.name, rel_obj) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py", line 235, in __set__ raise ValueError( Exception Type: ValueError at /borrow/ Exception Value: Cannot assign "1": "ApprovedLending.member" must be a "User" instance. Here is my models.py class A(models.Model): member = models.ForeignKey(User, on_delete=models.CASCADE, default="") book = models.ForeignKey(Books, on_delete=models.CASCADE, default="") library_no = models.CharField(default="", max_length=255, blank=True) staff_id = models.CharField(default="", max_length=255, blank=True) application_date = models.DateTimeField(auto_now_add=True) class B(models.Model): member = models.ForeignKey(User, on_delete=models.CASCADE, default="", null=True) book = models.ForeignKey(Books, on_delete=models.CASCADE, default="", null=True) … -
Problem with email sending when server status is on smtp
So I am making a website with account activation when registering and this works fine. But the part where I have to send email to reset password doesn't. If I turn the email backend to 'console', It works fine. In the console I get the message with the token link to reset the password. When I turn the email backend to 'smtp' it just doesnt work and I get a long error after I submit the email that the message has to be sent on. Also I don't have a pasword reset view. I don't know if that is the problem.email_SettingsPassword reset formspasswordreset_confirm_htmlpassword_reset_Form_htmlpassword_reset_urlserrorerror location I tried moddeling a Password reset view. I don't know if the view was right or this does not solve the problem. Also I googled this error but I didnt find something useful. Tried to change some urls. -
Django Dynamically Assign Model Object Field In For Loop
I want to dynamically pass the field name of a model in a for loop function. The code below is what I want to achieve, but obviously "object.model_field" won't work because it's looking for that specific name and not using the variable passed through the function. How can I lookup the field name of the variable passed through the function? query_objects = my_model.objects.all() def function(query_objects, model_field): object_list = [] for object in query_objects: object_list.append(object.model_field) return object_list -
Django & Django Rest Framework. Custom accounts app
I need help in creating a custom accounts app instead of using django_allauth or the built-in django user model. I'm stuck on LoginView, LogoutView, SignupView, and linking the created model to django rest framework auth model (using the created model to authenticate your api with token). Here is what i have wrote: models.py: from django.db import models class Account(models.Model): email = models.EmailField(unique=True, blank=True, null=True) phone = models.CharField(max_length=30, unique=True, blank=True, null=True) password = models.CharField(max_length=250) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) urls.py: from django.urls import path from accounts.views import ( AccountsView, AccountView, SignupView, LoginView, LogoutView ) app_name = 'accounts' urlpatterns = [ path('', AccountsView.as_view()), path('<int:pk>', AccountView.as_view()), path('signup/', SignupView.as_view()), path('login/', LoginView.as_view()), path('logout/', LogoutView.as_view()) ] serializers.py: from django.contrib.auth.hashers import make_password from rest_framework import serializers from accounts.models import Account class AccountSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) email = serializers.EmailField() phone = serializers.CharField(max_length=30) password = serializers.CharField(max_length=250, write_only=True, required=True) created_at = serializers.DateTimeField(read_only=True) updated_at = serializers.DateTimeField(read_only=True) def create(self, validated_data): password = make_password(validated_data.get('password')) account = Account.objects.create( email=validated_data.get('email'), phone=validated_data.get('phone'), password=password ) return account def update(self, account, validated_data): password = make_password(validated_data.get('password')) if validated_data.get('password') is not None else account.password account.email = validated_data.get('email', account.email) account.phone = validated_data.get('phone', account.phone) account.password = password account.save() return account views.py: from django.http import Http404 from rest_framework import status from rest_framework.views … -
How to make an input field with prompts that will appear in the process of entering data
I am making a site on Django. And I faced a problem. I would like to create an input field in the form so that it is initially empty, but so that in the process of how the user enters data into it, a frame will appear next to it, with possible selection options based on data already entered by the user. In short, I want to make something like this field Help me please -
CPanel installing requirements.txt file problem
Getting error in cPanel while installing requirements.txt file in django project. note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure × Encountered error while trying to install package. ╰─> cffi note: This is an issue with the package mentioned above, not pip. hint: See above for output from the failure. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. -
Import data containing title instead of ID in django
I am using django-import-export. It is an extension used to import tables of data to the admin panel using a csv file. I have a model with a foreign key : ProductModel, now if i want to import data i have to supply an ID of the ProductModel in the csv. I want a bypass so I can use title of an object instead of id in the csv class Item(models.Model): title = models.CharField(max_length=100) model = models.ForeignKey(ProductModel, ....) class ProductModel(models.Model): title = models.CharField(max_length=100) desc = models.Tex.....