Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test Meta tags for Images in a Django Project on local host
I have a Django Project and I am trying to add Meta Tags for an Image and Test them in the Local Host before going for the public Website. In the base.html I have added the following: <meta property="og:title" name="description" content="{% block description %}{% endblock %}"> <meta property="og:type" content="website" > <meta property="og:image" content="{% block image %}{% endblock %}"> In the home.html I have add the following: {% block description %}{{ info.description }}{% endblock %} {% block image %}{{ info.avatar.url }}{% endblock %} My question is: How do I test it before going production because on the local host I can see the path of the {{ info.avatar.url }} on the top of the page. -
ModuleNotFoundError: No module named 'django.config' using celery and rabbitmq
I'm getting this error after running the following command: C:\Users\callu\project_name>celery -A project_name worker -l info I'm wondering if it has something to do with the fact that I've not created my django project in a virtual environment but I can't find anything on the issue. If it was due to it being outside a virtual environment I'm not sure how I'd get around it without restarting the project in one (is it easy to move to a venv in PyCharm?) I run my django server and my above celery command here: C:\Users\callu\project_name> I run start my RabbitMQ server in another location (not venv) but don't think that's the issue Full Traceback: Traceback (most recent call last): File "c:\users\callu\appdata\local\programs\python\python37-32\lib\site-packages\cached_property.py", line 70, in __get__ return obj_dict[name] KeyError: 'data' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\callu\appdata\local\programs\python\python37-32\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\callu\appdata\local\programs\python\python37-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\callu\AppData\Local\Programs\Python\Python37-32\Scripts\celery.exe\__main__.py", line 7, in <module> File "c:\users\callu\appdata\local\programs\python\python37-32\lib\site-packages\celery\__main__.py", line 15, in main sys.exit(_main()) File "c:\users\callu\appdata\local\programs\python\python37-32\lib\site-packages\celery\bin\celery.py", line 213, in main return celery(auto_envvar_prefix="CELERY") File "c:\users\callu\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 764, in __call__ return self.main(*args, **kwargs) File "c:\users\callu\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 717, in main rv = self.invoke(ctx) File "c:\users\callu\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 1135, in … -
Why is my date in python wrong after formating using timedelta?
I am using Django and have a problem with a date that I need to calculate. The Variable data > test should be 17:00 and not 15:00. Why does this happen as soon as I format the date? My timezone is Europe/Berlin. Changing the timezone has to effect to the time printing in test. It is always -2h def date(req): now = datetime.datetime.now() model = MyModel.objects.filter(date__gt=now).first() next = model.date future = datetime.timedelta(hours=float(model.future)) #model.future = 1.5 open = next-future date = next.strftime('%Y/%m/%d') data = { 'next': next, 'date': date, 'time': open, 'test': open.strftime('%Y/%m/%d %H:%M:%S') } What I get: next: 20. November 2021 18:30 date: 2021/11/20 time: 20. November 2021 17:00 test: 2021/11/20 15:00:00 -
"Could not derive file name from *" while uploading images in django
I am building a image upload modle in django and the upload_to function to name the path. But it is showing me this error from django.utils import timezone from django.contrib.auth import get_user_model # Create your models here. def user_directory_path(instance, filename): return 'images/{0}/'.format(filename) class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Images(models.Model): User = get_user_model() category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1) title = models.CharField(max_length=250) alt = models.TextField(null=True) image = models.ImageField( max_length=255,upload_to=user_directory_path, default='posts/default.jpg') slug = models.SlugField(max_length=250, unique_for_date='created') created = models.DateTimeField(default=timezone.now) author = models.ForeignKey( User, on_delete=models.PROTECT, related_name='author') ``` -
REST Django - use objectID right after creation
I have a Project model from wich I can create instances via POST method. I created a new model called UserProject wich contains a userID and a projectID. Now I want to add an UserProject object each time a Project is created with that POST view. The Project is being created, but the UserProject database keeps being empty, what am I missing? models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Project(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) name = models.CharField(max_length=500, default = None) descriptor = models.CharField(max_length = 1000, null = True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'projects' def __str__(self): return self.name class Userproject(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) user = models.ManyToManyField(User) project = models.ManyToManyField('Project') created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null = True) class Meta: db_table = 'UserProjects' def __str__(self): return self.id views.py : class ProjectView( APIView, ): def post(self, request): serializer = ProjectSerializer(data = request.data) if serializer.is_valid(): serializer.save() id = serializer.id user = request.user n = Userproject.objects.create(user = user, project = id) n.save() return Response({"status": "success", "data": serializer.data}, status = 200) else: return Response({"status": "error", "data": serializer.errors}, status = 400) serializers.py: … -
The static resource location of Django's static page is incorrect
When loading picture resources on the page, the following error is always prompted, and the picture resources cannot be loaded. WARNING 2021-10-19 23:05:11,608 basehttp 3161 140233184446208 "GET /dist/static/webpack/img/logo18.png HTTP/1.1" 404 7224 This is my setting: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] there is always a strange "/dist" in the path. -
Django rest_framework forgot password
I'm newbie in Django I have a trouble with this: I've already make API for 'request-reset-email', 'password-reset' and 'password-reset-complete' Here are the code: file: urls.py from django.urls import path from .views import * from django.contrib.auth import views as auth_view from rest_framework_simplejwt.views import ( TokenObtainSlidingView, TokenRefreshSlidingView, ) urlpatterns=[ path('register/', RegisterView.as_view(), name="register"), path('login/', LoginAPIView.as_view(), name="login"), path('email-verify/', VerifyEmail.as_view(), name="email-verify"), path('token/refresh/', TokenRefreshSlidingView.as_view(), name='token_refresh'), path('request-reset-email/',RequestPasswordResetEmail.as_view(), name='request-reset-email'), path('password-reset/<uidb64>/<token>/',PasswordTokenCheckAPIView.as_view(),name='password-reset'), path('password-reset-complete/',SetNewPasswordAPIView.as_view(),name='password-reset-complete') ] file Views.py: from django.shortcuts import render from rest_framework import exceptions, generics, serializers from rest_framework.response import Response from rest_framework import status from .models import * from .serializers import * from rest_framework_simplejwt.tokens import RefreshToken from .utils import * from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse import jwt from django.conf import settings from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils.encoding import smart_str, force_str, smart_bytes, DjangoUnicodeDecodeError from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode # Create your views here. class RegisterView(generics.GenericAPIView): queryset = User.objects.all() serializer_class=RegisterSerializer def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data user= User.objects.get(email=user_data['email']) token=RefreshToken.for_user(user).access_token current_site=get_current_site(request).domain realtivelink = reverse('email-verify') absurl='http://'+current_site+realtivelink+"?token="+ str(token) email_body='Hi '+ user.email+ ' Use link below to verify your email \n' + absurl data={'email_body':email_body,'to_email':user.email,'email_subject':'Verify your email'} Util.send_email(data) return Response(user_data,status= status.HTTP_201_CREATED) class VerifyEmail(generics.GenericAPIView): def get(self,request): token= request.GET.get('token') try: payload=jwt.decode(token,settings.SECRET_KEY,algorithms='HS256') user=User.objects.get(id=payload['user_id']) if not user.is_verified: user.is_verified=True user.save() return … -
obtaining individual model values python django
I have a database object that has several values that make it up. I can select the whole object by doing the following my_object = WholeValues.objects.all() The object has different parts such as "height, weight, arm_length, leg_length". each part is of type FloatField() in the django database model. How can I access these individually? for example just obtaining the weight value. -
Django template fragment caching not working the way it is supposed to
Referring to following documentation, I am trying this https://docs.djangoproject.com/en/dev/topics/cache/#template-fragment-caching {% cache 500 sidebar request.user.username %} {% if user.is_authenticated %} {{ user.first_name}} {% endif %} {% endcache %} The problem is my authenticated Name and picture is getting cached and seen by other users, and those of other users by some other user. Essentially anyone coming in hits the cache of previous chap visiting the web site. Apart from this no user access or any other security issue is not there. Can you advise why this is so and what is the solution to the problem. -
Bootstrap and Jinja - centering images
I'm using Bootstrap3 in my Django project and I would like to display images in row next to each other horizontally and I have: <div class="row"> {% for image in images %} {% if image.image %} <div class="col-lg-4 col-md-4 col-xs-4 thumb"> <img class="img-responsive" src="{{ image.image.url }}" /> </div> {% endif %} {% endfor %} </div> and it works. But images are displayed from left to right (for example, if there is only 1 image, it's pinned to the left and it doesn't look great). How can I center all images to always be centered independent on number of images? -
How do I clear path from history in Django?
I want to clear all path from history and redirect to new path. If is there any way to do this please provide suitable solutions. -
from an address get the altitude and longitude in django rest, I am new with this python
I am designing an api with django, I need to convert many directions to latitude and longitude, I don't know where to start I am something new in this -
Importing view is showing error from app in Django?
i am trying to create simple hello world page from django in pycharm and from urls.py file of my app "first_app" trying to import views. But when i type "from first_app import views" in urls.py, pycharm is underlining it as an error but my hello world page is still showing. Earlier it was giving some error. I am attaching screenshot of it. I have also mentioned first_app in installed_apps in settings.py file of the project. If any one knows about it please tell me what the issue is here. -
How do I change a parameter dynamically?
I have a simple e-commerce on Django. Can you show how to implement a dynamic price change depending on the number of items? For example: when adding to cart from 1 to 10 items the cost is 1, from 11 to 20 the cost is 0.9 and so on. Thank you very much! -
Django set relation between two models
I want to save my custom Model as Field in another Model as shown below. It's normal when I create and work with them during one session. But when I start a new session Django loads the Game model with player1 and player2 that have a null id. Here example of my code class Player(models.Model): name = models.CharField(max_length=40) class Game(models.Model): player1 = Player() player2 = Player() -
How to install python package from the project if requirememt.txt is not exist
How to install python package from the project if requirememt.txt is not exist like: In node.js we run npm install command and all npm package install. like that, I want a python package installed from the project. If any way to do that? -
Getting error when setting up HyperlinkedModelSerializer
I keep getting the error Could not resolve URL for hyperlinked relationship using view name "departments-api". You may have failed to include the related model in your API, or incorrectly configured the "lookup_field" attribute on this field. I am trying to link this but am not sure where I am going wrong here. I can get to the '/api/' page but can not click on either of the links to take me to the corresponding page. I believe I may need to change around my serializer hyperlinkedidentityfield or my api_root function but am not sure where to start. Models.py class Department(models.Model): name = models.CharField(max_length=300) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=300) # delete dept == delete teacher department = models.ForeignKey(Department, on_delete=models.CASCADE) tenure = models.BooleanField() def __str__(self): return f'{self.name} teaches {self.department}' def get_absolute_url(self): return reverse('teacher-detail', kwargs={'pk': self.pk}) serializers.py class TeacherSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="teachers-api") class Meta: model = Teacher fields = '__all__' class DepartmentSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name="departments-api") class Meta: model = Department fields = ['url', 'name'] urls.py urlpatterns = [ path('api/', api_root), path('api/teachers/', TeacherAPIList.as_view(), name='teachers-api'), path('api/teachers/<int:pk>/', TeacherAPIDetail.as_view()), path('api/departments/', DepartmentAPIList.as_view(), name='departments-api'), path('api/users/', UserAPIList.as_view()), path('api/users/<int:pk>/', UserAPIDetail.as_view()), ] views.py @api_view(['GET']) def api_root(request, format=None): return Response({ 'teachers': reverse('teachers-api', request=request, format=format), 'departments': reverse('departments-api', request=request, … -
Group by query in Django ORM
I an having a confusion on how to write a django query to get my data. I have 2 tables 'ticket' and 'ticket_details'. Below is the schema for them. Ticket(id, name, type, user) TicketDetails(ticket_id, message, created_time) Note: Multiple message can be associated to one ticket id. And ticket_id is a foreign key to the Ticket table. I would like to fetch all the columns from both the table where only the latest message from the TicketDetails table should be picked for a particular ticket id. Thanks in advance -
REST Django - How to grab recently created Object
I use a post method to create an instance of the class called Project. When the Post method is done, I want to get the ID of the recently created Project-object. How would I do this? my model looks like this: models.py class Project(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) name = models.CharField(max_length=500, default = None) descriptor = models.CharField(max_length = 1000, null = True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'projects' def __str__(self): return self.name and my view is this: views.py: class ProjectView( APIView, ): def post(self, request): serializer = ProjectSerializer(data = request.data) if serializer.is_valid(): serializer.save() user = request.user return Response({"status": "success", "data": serializer.data}, status = 200) else: return Response({"status": "error", "data": serializer.errors}, status = 400) -
How does Django handle multiple CRUD actions on same table? (at same time)
I am curious about how Django handles multiple actions to be performed on same table at the same time. I'm using Postgresql with Django ORM. Does it have locking mechanism to handle such scenario? If yes then is it by default or any parameter must be added? -
TypeError when querying in bulk - DjangoPhoneNumber
In my application, I'm using the django-phonenumber-field package to store the user phone number. When I try to query in bulk using a list of phone numbers, the following error appears: TypeError: keys must be str, int, float, bool or None, not PhoneNumber This StackOverflow post would help if I was using pure python, but instead I am doing the following Django query: registered_users = User.objects.in_bulk( data["phone_number"], field_name="phone_number" ) The data["phone_number"] is simply a list containing strings. So, it seems I should pass the field differently, but I have no idea how to convert the field to a valid format for Python. Any ideas? -
Best practice for changing certain variables if published to a branch
I work on a custom documentation management system with Django. Currently there is a productive envoirment on an IIS + Hyper-V with a database, let's call it productiveDB. New features are implemented locally in different branches, using another database, let's call this one stagingDB. When I work locally on a new branch I have to adjust the database configuration and credentials from productiveDB to stagingDB in my settings.py - furthermore I set the DEBUG Mode to True. When I commit my changes and merge into master, I sometimes forget to adjust the settings and this is where my question begins: What is the best practice to handle this 'inattention'? Sure, I could keep the local settings adjusted for the staging envoirment and vice versa for the productive settings but here and then I have to add new settings to the aformentioned file and therefore I would have to commit the edited settings.py. Is there a 'build in' way in GitLab or git to mark specific variables and change them according to the branch they are under? Like: if branch=master then set DEBUG=FALSE, DATABASE=productiveDB before while the CI/CD pipeline is running or do I have to stick to a custom script? -
I tried to install django using pip install django, later i get error to upgrade pip, i done upgrade pip, but still got error as below i mentioned
WARNING: The script sqlformat.exe is installed in 'C:\Users\Easwar Sai Prasad\AppData\Roaming\Python\Python38\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. WARNING: The script django-admin.exe is installed in 'C:\Users\Easwar Sai Prasad\AppData\Roaming\Python\Python38\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. -
Why does reset_sequences=True cause pytest to actually flush differences to the test_database?
I'm running my django tests using pytest and I saw some strange behaviour. To find out what happened I put a breakpoint() in my tests and then psql'ed into my postgres database to see what the status was. To my surprise all database tables were empty even though when using MyModel.objects.all().count() gave about 500 (test) records. I looked up the documentation and fiddled around a bit, and then found out that when I change @pytest.mark.django_db at the top of my tests to @pytest.mark.django_db(reset_sequences=True) the counts I see when psql'ing into postgres show the same as what I get from doing a count using the django orm. To add to the confusion, the documentation actually says that reset_sequences=True Must be used together with transaction=True to have an effect. Why does setting reset_sequences to True have the effect that doing a count using psql has the same effect as doing a count using the django ORM? -
How to connect different apps in a server? [closed]
We have multiple apps in different languages on a single python server that needs to be connected together in realtime, my friend suggest using a TCP connection for them to work together, is it the only/right choice? will there be some sort of problems in the future. Is there really no way of connection different programming languages together without using RMI/Docker/Vagrant?