Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access a dict from a PY file in Jinja for Flask Website
Im creating a site on flask, using jinja i want to access a dict from my dict.py file to display a table on my template but I am given a 'coin_dict' is undefined error on when i render. Any help? Template Code to access keys and values from dict: {% for key, value in coin_dict() %} <tr> <td> {{ key }} </td> <td> {{ value }} </td> </tr> {% endfor %} -
DRF Transaction atomic not work when I'm trying to call external def
I have multiple operations that I need to send it to server as single query and for that I'm using transaction atomic but this is not work if I call def post_image. this function is not in the same directory it is inside another file This my ImagesTrip.py: def post_image(trip_id): #lot of operations ... If serializer.valid(): serializer.save() return Response(status = status.HTTP_201_CREATED) this views.py I'm working on it with transaction.atomic(): trip_instance=trip.save() respo_img= post_images(trip_instance.pk) I need to save trip and store it in DataBase only if post image is valid and successfully done -
When loading JSON data into postgresql database, it only loads last object?
I am working on a Django project and I'm trying to load data into my PostgreSQL database through fixtures. I've read the documentation and followed the same format but for some reason, despite having several data, it will only show the last object when I try to view them in my database. I've even tried loading as yaml but still the same result. Here's an example: { "model": "my_app.post", "pk": null, "fields": { "category": 5, "post_title": "Your Next Investment 0.21 Acres of Flat Vacant Land 30 mins", "description": "It’s time to turn up the heat on your next investment. 0.21 acres of flat vacant land in Colorado City, Colorado. Start building your dream home now. This land would be the perfect place to start. Imagine waking up to unobstructed views and enjoying the many benefits of outdoor living.", "date_created": "2022-04-03" } }, { "model": "my_app.post", "pk": null, "fields": { "category": 5, "post_title": "$1,225 / 364ft2 - Patio/Balcony, Central Air, Tennis Court", "description": "Welcome home to Alta Living! Settle into one of our renovated studio, one, or two bedroom homes. If you are searching for a relaxing and inviting space, you're in luck! Every floorplan offers spacious living areas, vinyl plank … -
Celery django and python with ASCII
Using celery with django framework, I get this output: Traceback (most recent call last): File "/usr/local/bin/celery", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python3.6/dist-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/usr/local/lib/python3.6/dist-packages/celery/bin/celery.py", line 213, in main return celery(auto_envvar_prefix="CELERY") File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 760, in main _verify_python3_env() File "/usr/local/lib/python3.6/dist-packages/click/_unicodefun.py", line 130, in _verify_python3_env " mitigation steps.{}".format(extra) RuntimeError: Click will abort further execution because Python 3 was configured to use ASCII as encoding for the environment. Consult https://click.palletsprojects.com/python3/ for mitigation steps. This system supports the C.UTF-8 locale which is recommended. You might be able to resolve your issue by exporting the following environment variables: export LC_ALL=C.UTF-8 export LANG=C.UTF-8 Is there a way to set python to work globally with UTF-8? Where I should use this sentences? At command line?: export LC_ALL=C.UTF-8 export LANG=C.UTF-8 But I still have the same problem. I have also tried adding these statements to the top of celery.py import sys reload(sys) sys.setdefaultencoding("utf-8") celery.py from imp import reload import os from celery import Celery import sys reload(sys) sys.setdefaultencoding("utf-8") os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'appName.settings') app = Celery('appName') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() -
how to hit an api gateway endpoint from zappa
I am using django with zappa lambda https: //github.com/zappa/Zappa in production and the web application work fine. The problem i am facing is that in production, when i try to hit a public aws gateway endpoint in the code, the call to the resource timeout. (When i try locally, my codes do hit that endpoint) After reading multiple articles I found out that its because zappa lambda deploy the codes inside a private VPC,which has no access to the internet. If anyone has a quick solution to be able to hit from zappa lambda in production that endpoint that would be very helpful -
Do I need to test an already tested ForeignKey field when unit testing
I am writing unit tests for my Django project and I was wondering if it is actually useful to include assertions about a ForeignKey object that I already created unit tests for. I will use the example from the documentation: from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline In this scenario lets say that I already wrote tests for the Reporter model, so I already tested it's fields. Is there any point to include assertions about the reporter field (other than making sure that it's the correct type) when writing tests for the Article model? Like for example checking if the first_name of the article's reporter object is not bigger than 30 characters, etc. It is probably not the smartest question but I didn't find a definite answer so far. -
Python command not found, but found after restarting command prompt
I was working on a python project where I was about to run it, but then the command prompt responded with: "'python' is not a known bash or shell command." I tried closing and opening the command prompt, but this time it worked. I don't really have a problem with it, but just wanted to know why this happened. -
django rest framework method 'DELETE' not allowed because DefaultRouter
This is my first project with Django and I am having a bit of trouble with the URLs. I have a customer model and I created the ModelViewSet for it so I can retrieve, delete and update the models in the database. To get all the basic URLs I used rest_framework.routers.DefaultRouter and registered the CustomerViewSet to it like so: router = routers.DefaultRouter() router.register(r'customers', CustomerViewSet, basename='customers') And then registered the URLs like so: urlpatterns = [ path('', include(router.urls), name="customers"), ] My problem is that I need to add a new URL for deleting all the customers in the database. I tried adding it like so: urlpatterns = [ path('', include(router.urls), name="customers"), path('customers/', deleteAllCustomers, name='deleteAll'), ] Where deleteAllCustomers is a function decorated with api_view(['DELETE']. When I try to call this URL (using Postman), I get 405 error (method 'DELETE' not allowed). From what I understand, it happens because that URL is already assigned by the DefaulteRouter for PUT/POST methods. I tried adding a destroy function to my CustomerViewSet, but it is only called when deleting one instance (with primary key passed in the URL). I haven't found a way to make the URL work and wasn't able to find any similar question. -
The best way to calculate closest distance with Google API and Django
I have a page with a list of people, and I would like the user to click a button to sort this list by closest. The list is of objects with the variables LON and LAT for longitude and latitude. I have made a function that calculates the distance based on Google Distance Matrix API. Here is the function: def calculateDistance(lat1, lon1, lat2, lon2): gmaps = googlemaps.Client(key=config('MATRIX_API')) matrix = gmaps.distance_matrix((lat1,lon1), (lat2,lon2), mode="driving") print(matrix['rows'][0]['elements'][0]['distance']['text']) I would like to know what is the best way to calculate the distance for all people in the list and order it inside the view that renders the page without creating a very heavy workload on the server. I thought of an idea, is to do this in the background (using Django Celery) and store the distances in the database so that the sorting happens by retreiving the distances from the DB instead of making API calls everytime the person refreshes the page, for example: class Distances(models.Model): visitor = models.ForeignKey(Visitor..... # Visitor looking for people person = models.ForeignKey(Person.... # Person on the list dist = models.CharField(....... And the function above, gets executed in the background every time a new person gets added to the database, or … -
Django Template Language: Create conditional for entire Model (not record by record)
Newbie problem. Per the following script in a template ... {% if request.user not in myModel %} <p>You have no account in the system.</p> {% endif %} ... the statement "You have no account in the system." is appearing 100 times on screen---because there are 100 records and therefore the condition is being checked 100 times. Is there a way to modify the script so that the statement appears just once? Meaning, it checks the entire database once for evidence that request.user appears anywhere in the model in aggregrate (and not whether it appears in each of the 100 records in the database)? Maybe there's an easier/better way to do this in views.py vs a template, but that's beyond my knowledge. Thank you. -
How to open a link if a function get called Django
I am trying to verified my user using email. It is all working fine but here I want to open a url when one of my api get called. After register I am sending them an email with link to activate account so link is one of my api which is a function I get the user by id and get save email verified and send a response as verified but rather then sending a response I want to automatically send him to the login page. How can I do it? In my frontend I am using react. this is the activate function or api @api_view(['GET']) def activate_user(request, pk): user = CustomUser.objects.get(id=pk) print(user) user.is_email_verified = True user.save() return Response('Email Verified') -
How to get email from usercusomer for followers
I want to send email for each follower after create item. But I don't know how to get this field from Models, and also I don't know how to send each follower to relate following. models.py class Book(models.Models): title = models.CharField(max_length=255) author = models.ForeignKey( "users.CustomUser", on_delete=models.SET_NULL, null=True ) # This is my try #But it doesn't work @hook(AFTER_CREATE) def send_followers(self): user = Followers.objects.all() followers_email = CustomUser.objects.filter( followers__follower__in=, followers__following=self.author.profile) if CustomUser.objects.filter( followers__follower__in=CustomUser.objects.only( 'followers__follower'), followers__following=self.author.profile ).exists(): send_mail( "Article published", '%s' % ( followers_email ), "nikitaalexnazarov@yandex.ru", [self.author.email], fail_silently=False, ) else: pass class CustomUser(AbstractUser): gender = models.ForeignKey( "Gender", on_delete=models.CASCADE, blank=True, null=True ) class Followers(models.Model): follower = models.ForeignKey( "users.CustomUser", on_delete=models.CASCADE, null=True, blank=True) following = models.ForeignKey( "Profile", on_delete=models.CASCADE, null=True, blank=True) class Profile(models.Model): slug = models.SlugField(unique=True) user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) -
PyTelegramBotAPI NameError: name 'p' is not defined Python(Django)
I am writing a telegram bot using pytelegrambotapi. I created a database using Python (django). The following code describes the calculation of the area of a rectangle. I first wrote the bot using a global variable. I have a problem! If only one user uses the bot, the bot is responding correctly. If the bot is used by many users at the same time, the bot is mixing up the answers and returning the wrong answer. I want to solve this problem using a database. But then I edited the code and made it look like this(BOT.PY) and I had a problem with localvariable. I can't figure out where the error is. Please help me :( BOT.PY ... ...; float_pattern = r'^\d{1,7}\.\d{1,2}$' ... ... def p_first(message): if message.text.isdigit() or re.match(float_pattern, message.text): chat_id = message.chat.id uid, _ = Profile.objects.get_or_create( external_id=message.chat.id, defaults={ 'name': message.chat.username } ) Message( profile=uid, param1=message.text ).save() p = Message.param1 print('Parameter (p) from:', chat_id) bot.send_message(message.chat.id, "Ajoyib, perimetr qabul qilindi!") msg = bot.send_message(message.chat.id, "<b>2. "Now secondside: "</b>", parse_mode="html") bot.register_next_step_handler(msg, height) return p else: msg = bot.send_message(message.chat.id, "Nice!") bot.register_next_step_handler(msg, p_first) def height(message): if message.text.isdigit() or re.match(float_pattern, message.text): chat_id = message.chat.id uid, _ = Profile.objects.get_or_create( external_id=message.chat.id, defaults={ 'name': message.chat.username } ) Message( … -
How to add query parameters to the <a href=
I want to redirect from one page to another (and save the query parameters). So i redirect like base.html <tr> <td> <a href="search/"></a></td> <td>...</td> </tr> urls.py path('main/search/', views.x, name='table_query') views.py @login_required @inject_session_params def table_structure(request, user_data, *args, **kwargs): if request.method=='GET': user_data['table']=kwargs['table'] user_data['structure'] = getTableProps(kwargs['table']) else: return redirect('login') return render(request, 'x.html', user_data) I have got al the needed information which I would like to use for the query, but I am not sure how to use it inside <a>. I have tried to create another function, which would generate the url and then redirect to the needed view, but it gives me an error. This is what I have tried: base_url=reverse('table_query') query = urlencode({'x': x, 'y': y, 'z': z}) url='{}?{}'.format(base_url,query) How to add query parameters (with a function) inside a tag, without writing <a href="search?x=x&y=y&z=z"? -
making django model field that is a foreign key pointing to a model field in different app taking array of user in a specific group
I'm new to django rest framework, what I'm trying to achieve is to create a model field that is a foreign key and points to a different app model and take their user_id(the automatic id that is predefined) users\models.py class user(models.Model): username = models.CharField(max_length=10, unique=True) name = models.CharField(max_length=64) creationtime = models.DateTimeField(auto_now_add=True) userdescription = models.CharField(max_length=250) def __str__(self) -> str: return self.username teams\models.y class team(models.Model): teamname = models.CharField(max_length=64) description = models.CharField(max_length=128) creationtime = models.DateTimeField(auto_now_add=True) admin = models.ForeignKey(user, related_name='admin', on_delete=models.CASCADE) members = models.ForeignKey(user, related_name='members', on_delete=models.CASCADE) def __str__(self) -> str: return self.teamname so what I want is like when I see the members column in database it should show an array of user_id, something like this: members: [1,2,5,7,8] these number refers to the automatic index that is created for each row or you know like when we do a get request for a specific user_id like: https://localhost:8000/users/1/ thanks in advance for the help. -
Will Django Migrations result in conflicts with distributed version control?
I'm planning to work on a Django project with several collegues via Gitlab. Let developer A create a model on branch feature/model_a: class model_A(models.Model): field_A = models.CharField(...) Dev A runs makemigrations, receives a migration file (something like 0001_migration) and commits and pushes it to the remote repository. Now Dev B develops another model on feature/model_b: class model_B(models.Model): field_B = models.CharField(...) and also creates a migration file (Django will call this migration file also 0001_migration!). So given that the two developers develop their models on separate branches (which I believe is a good and recommended practice), they will now have a repository conflict. What are recommended and proven ways to prevent this problem? -
How can i Register and Login In The Same Page in Django?
i would like to have both my login form and my registration form on the same page within the same template, so i would like to have them under one view function but i am not too sure on how i can do that, here is my code. Views.py def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) == "Register" if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request,"Account was Created for " + user) context = {'form':form} return render(request,'login.html',context) def login(request): if request.method == "POST": if request.POST.get('submit') == 'Login': username = request.POST.get('username') password = request.POST.get('password1') user = authenticate(request, username=username, password=password) if user is not None: login(request,user) return redirect('shop.html') else: messages.info(request, 'Wrong Username or password') context = {} return render(request,'shop.html',context) login.html <div class="formBx"> <form method="POST",name="Login",value="Login"> {% csrf_token %} <h2>Sign In</h2> {{form.username}} {{form.password1}} <input type="submit" name="submit" value="Login"> <p class="signup">Don't have an Account?<a href="#" onclick="toggleForm();">Sign Up.</a></p> {% for message in messages %} <p id="messages">{{message}}</p> {% endfor %} </form> </div> </div> <div class="user signUpBx"> <div class="formBx"> <form method="POST" value="Register"> {% csrf_token %} <h2>Create an account</h2> {{form.username}} {{form.email}} {{form.password1}} {{form.password2}} <input type="submit" name="submit" value="Register"> <p class="signup">Already Have an Account?<a href="#" onclick="toggleForm();">Sign In.</a></p> {% for message in messages %} <p id="messages">{{message}}</p> {% endfor %} … -
What is the Django way to add data to a form that is already instantiated?
Suppose you have a ModelForm to which you have already binded the data from a request.POST. If there are fields of the ModelForm that I don't want the user to have to fill in and that are therefore not shown in the form (ex: the user is already logged in, I don't want the user to fill a 'author' field, I can get that from request.user), what is the 'Django' way of doing it ? class RandomView(View): ... def post(self, request, *args, **kwargs): form = RandomForm(request.POST) form.fill_remaining_form_fields(request) ### How would you implement this ??? if form.is_valid(): ... I have tried adding the fields to the form instance (ex: self.data['author'] = request.user) but given its a QueryDict it is immutable so it clearly isn't the correct way of doing this. Any suggestions ? -
mssql-django - TCP Provider: Error Code 0x2746 (10054) (SQLDriverConnect)
Have a dockerized Django 4 app running on Docker (Debian10) host, connecting to a network SQL Server 2012 (running on Windows10 box) in development environment. Cannot get same docker image to connect to SQL Server 2014 (running on Server2012 VM) in staging environment. Can see on SQL Server event logs that DB connection is successful: Login succeeded for user '<USERNAME>'. Connection made using SQL Server authentication. [CLIENT: <DB_SERVER_IP>] However, Django errors out with the following Stack Trace: alluradjango-web-1 | self.connect() alluradjango-web-1 | File "/home/djangouser/.local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner alluradjango-web-1 | return func(*args, **kwargs) alluradjango-web-1 | File "/home/djangouser/.local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect alluradjango-web-1 | self.connection = self.get_new_connection(conn_params) alluradjango-web-1 | File "/home/djangouser/.local/lib/python3.9/site-packages/mssql/base.py", line 329, in get_new_connection alluradjango-web-1 | conn = Database.connect(connstr, alluradjango-web-1 | django.db.utils.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x2746 (10054) (SQLDriverConnect)') requirements.txt: asgiref==3.5.0 backports.zoneinfo==0.2.1 Django==4.0.3 django-allow-cidr==0.4.0 django-environ djangorestframework==3.13.1 mssql-django==1.1.2 netaddr==0.8.0 pyodbc==4.0.32 pytz==2021.3 sqlparse==0.4.2 black==22.1.0 pylint==2.12.2 pylint-django==2.5.2 python-decouple==3.6 pre-commit==2.17.0 djangouser@2062b37a0a3a:~$ odbcinst -j unixODBC 2.3.6 DRIVERS............: /etc/odbcinst.ini SYSTEM DATA SOURCES: /etc/odbc.ini FILE DATA SOURCES..: /etc/ODBCDataSources USER DATA SOURCES..: /home/djangouser/.odbc.ini SQLULEN Size.......: 8 SQLLEN Size........: 8 SQLSETPOSIROW Size.: 8 /etc/odbc.ini is empty djangouser@2062b37a0a3a:~$ cat /etc/odbcinst.ini [ODBC Driver 17 for SQL Server] Description=Microsoft ODBC Driver 17 for SQL Server … -
Why Heroku redirect my site on HTTPS with no SSL setup?
I've deploy my django website on heroku. After adding my custom domain, when i try to access to http://www.example.com it redirect me to https://www.example.com and i get this message ERR_SSL_UNRECOGNIZED_NAME_ALERT I haven't add any SSL certificate, is it normal that i'm redirect to HTTPS? -
Django cannot access dictionary, returns blank
When I try and access a simple dict in django: {'The Batman': [{'datetime': datetime.datetime(2022, 4, 1, 11, 0, tzinfo=datetime.timezone.utc), 'id': '1'},{'datetime': datetime.datetime(2022, 4, 1, 11, 0, tzinfo=datetime.timezone.utc), 'id': '1'}], 'Ice Age': [{'datetime': datetime.datetime(2022, 4, 1, 11, 0, tzinfo=datetime.timezone.utc), 'id': '1'}, {'datetime': datetime.datetime(2022, 4, 1, 11, 0, tzinfo=datetime.timezone.utc), 'id': '1'}]} I use this loop to access the keys: {% for film in data %} ...Code here {% endfor %} but then when I go to access the values, it returns nothing. I am accessing the values as follows: {% for showing in film.key %} ...Code here {% endfor %} I am printing out the data to my screen every time, so I know there is data there, because the headings register too. Unsure what is happening or what I am doing wrong. Fairly new to Django so pls be nice :) -
How can I do addition in django views?
When I go to add multiple integer variables, I'm getting below error. Now, what has to do? Error: TypeError at / unsupported operand type(s) for +: 'method' and 'int' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.3 Exception Type: TypeError Exception Value: unsupported operand type(s) for +: 'method' and 'int' views: total_frontend_order = request.user.user_frontend_order.all().count total_backend_order = request.user.user_backend_order.all().count total_complete_website_order = request.user.user_complete_website_order.all().count a = total_frontend_order+1 -
Getting TypeError when trying to upload to s3 from heroku
Error: TypeError at /accounts/work_feed/upload/1 sequence item 0: expected str instance, NoneType found Im getting this error when I try to upload an image from my django app on heroku to an aws s3 bucket. My settings.py looks like: ROOT_URLCONF = 'ClassTrail.urls' DATABASES = { 'default': dj_database_url.config() } STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = 'static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' django_heroku.settings(locals()) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('BUCKET_NAME') S3_URL = 'https://%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_QUERYSTRING_AUTH = False (I cut out some irrelevant bits of settings.py) My app works perfectly with postgres and aws locally, but when I run the website on heroku, everything works except for uploading files to aws. Thank you for any help! -
Django ModelViewSet. How to merge two perfrom methods/functions?
Is there a way to merge perform methods/functions? The view uses ModelViewSet. I have two functions perform_create and perform_update that do the same thing and I wondered could I merge them somehow? Body { "title": "1 Title", "description": "1 Description", "author": { "id": 1 } } View class ArticleView(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer def perform_create(self, serializer): author = get_object_or_404(Author, id=self.request.data['author']['id']) return serializer.save(author=author) def perform_update(self, serializer): author = get_object_or_404(Author, id=self.request.data['author']['id']) return serializer.save(author=author) Serializers class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = '__all__' class ArticleSerializer(serializers.ModelSerializer): author = AuthorSerializer() class Meta: model = Article fields = '__all__' -
File access issues with django and gunicorn
I’m wondering how file permissions work on Django. I have created a file debug.log where I want my logging to output. Its permissions look like this -rw-rw-r-- 1 ubuntu ubuntu 0 Apr 3 19:16 debug.log I have a Django superuser called ubuntu who I think should have rw access to this file based on what this says. However, when I run systemctl status gunicorn, I get File "/usr/lib/python3.8/logging/config.py", line 570, in configure raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'file' Which according to this post Should mean that either the file doesn’t exist, or my user doesn’t have access. The filename has value os.path.join(BASE_DIR, 'debug.log'). And if I print that value out, I get /home/ubuntu/ACE/rangr/debug.log which is where the debug.log file is. Does anyone know why my django user doesn't have access to debug.log or why django thinks the file doesn't exist?