Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Appointment booking system. Avoid double bookings
I am currently trying to build an appointment system. This works fine however the function doesn't catch if the same appointment has already been booked in the models. class BookingView(FormView): form_class = AvailabilityForm template_name = "availability.html" def form_valid(self, form): data = form.cleaned_data bookingList = Appointment.objects.filter() for booking in bookingList: if booking.start > data["end_time"] or booking.end < data["start_time"]: booking=Appointment.objects.create( name=data["name"], start=data["start_time"], end=data["end_time"] ) booking.save() print(booking.start) print(data["start_time"]) return HttpResponse("can be booked") else: print(booking.start ) print(data["start_time"]) return HttpResponse("Cant be booked") -
How to test GET and POST api which requires user logged in pytest Django?
I have created a fixture to create user in conftest.py @pytest.fixture def test_password(): return 'strong-test-pass' @pytest.fixture(scope='session') def create_user(db, test_password): def make_user(**kwargs): employee = e_ge_employee.objects.create() kwargs['password'] = test_password if 'username' not in kwargs: kwargs['username'] = str(uuid.uuid4()) if 'employee' not in kwargs: kwargs['employee'] = employee return e_ge_user.objects.create(**kwargs) return make_user and then wrote a testcase to check login in test_urls.py @pytest.mark.django_db def test_auth_view(client, create_user, test_password): user = create_user() url = '/accounts/login/' client.login( username=user.username, password=test_password ) response = client.get(url) print("RESPONSE - ",response) assert response.status_code == 200 Now I want to write a test case to test GET and POST API and the APIs will only work if the user is authenticated, Can someone please provide me with the solution.....Thanks in Advance -
Render html content stay on current page with form action set to different url in Django
My question is there is a way to render html content(bootstrap alert) on the current page(1st page) with POST action set to a different url(2nd page)? I have following content in views.py: def calendar(req): # 1st page return render(req,'calendar.html') def result(req): # 2nd page if req.method == 'POST': xxx else: no_data = "xxx" context = { 'no_data': no_data } return render(req, 'calendar.html', context) xxx return render(req,'result.html',context) The form info is submitted to different url(2nd page) in calendar.html: {% if no_data %} <div class="alert alert-warning" role="alert"> {{ no_data }} </div> <form action="{% url 'result' %}" method="POST"> Thank you. -
How to migrate remote postgres db into my local django project?
I am creating a Django project where I have to use existing database data. The existing database is Postgres and it is hosted on Aws. My goal is to copy them from Aws to my local Postgres DB and use in my project. Thanks -
Django using Amazon S3
So whenever I run the following a staticfiles folder gets created and I can't collectstatic to my AWS S3 bucket. (portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> python manage.py collectstatic Found another file with the destination path 'user\main.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig', 'storages', ] STATIC_ROOT = 'static/' # All of this is in my console.aws.amazon to configure aws s3 static files only # IAM Management Console AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID', '') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY', '') # Amazon S3 Buckets AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME', '') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'pages/static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
Typescript endpoint to list users in Django
So I have a Django project and I want to create a typescript endpoint to list which users live in a certain postal code. I have never used typescript so I don't know how to create it and integrate it with the django project. Help is much appreciated. the models.py if it is useful: class UsuarioMaster(models.Model): nombre = models.CharField(max_length=50) class UsuarioDetalle(models.Model): usuario = models.ForeignKey(UsuarioMaster, on_delete=models.CASCADE, null=True) codigo_postal = models.CharField(max_length=5) ciudad = models.CharField(max_length=50) pais = models.CharField(max_length=50, default='') -
How do I create a QR code in Python without saving it as an image
I am trying to make Qr Codes using Python on a Django applicaiton using this code : def generate_qr_code (reference): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=10, border=4, ) qr.add_data(reference) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white").convert('RGB') filename = reference+".jpeg" img.save("C:\\qrs\\"+filename) Now, this function is called when I click on a "Generate Qr Code" Button. My problem is that I would like the Qr Code to be displayed on a new tab on my browser instead of it being saved as an image, as I only need to print them on paper at that moment and I have no need to keep the images. Thank you for your help. -
facing some issues while installing the mysqlclient Django
i am facing some issues while installing the mysqlclient in virtual environment sudo apt-get install python3-mysqldb sudo apt-get install libmysqlclient-dev -
How to access Django secret key when git cloning from github?
So I have placed Django secret key in base.json and added that in .gitignore to prevent push and pulls to github and edited settings.py accordingly as such. Problem is that I am trying to deploy my api to AWS ec2 and when I git clone on my Ubuntu terminal, obviously that base.json file is missing and I cannot run my code because secret key is not found. So what should I do in this case? settings.py: import os, json from django.core.exceptions import ImproperlyConfigured secret_file = os.path.join(BASE_DIR, 'base.json') with open(secret_file) as f: secrets = json.loads(f.read()) def get_secret(setting, secrets=secrets): try: return secrets[setting] except KeyError: error_msg = "Set the {} environment variable".format(setting) raise ImproperlyConfigured(error_msg) SECRET_KEY = get_secret("SECRET_KEY") DEBUG = False ALLOWED_HOSTS = ['*'] I have seen How to access Heroku config variables inside Django settings and other similar ones but they all relate to Heroku and not my case. -
module 'collections' has no attribute 'MutableMapping'
i am trying to upload images from admin page to the data base, in django project i have configured and i have tried many ways to fix this but doesn't worked please guide me:- settings.py MEDIA_URL = '/media/' MEDIA_ROOT = str(BASE_DIR / 'media') urls.py urlpatters[...] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) models.py product_img = models.ImageField('Product Image', upload_to = 'product_img', blank=True ) docker file FROM python:3.9.7-alpine3.14 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY requirement.txt /app/ RUN pip3 install -r requirement.txt COPY . /app/ requirments.txt Django==3.2.9 Pillow==2.2.1 -
Python sorted object
I have query that is sorted via python however I would like to exclude the brands with the distance greater than 100km this is what I wrote, however it always gets distance that is beyond 100km return sorted( root.brands.filter(status=True, region_id=area), key=lambda qs: (qs.distance(**kwargs) <= 100, qs.distance(**kwargs) < 100 if qs.distance(**kwargs) > 0 else []) ) is there any way to do this? thanks -
NoReverseMatch at / Reverse for 'user-profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P<pk>[^/]+)/$']
Please somebody help please, am new to Django and don't know how to get around this in my code. Am following a tutorial and that builds a chatroom with Django. Everything works fine but then I wanted to modify it and display the posts written by a user on their profile page so that others can see it, but instead i got this error 'NoReverseMatch at / Reverse for 'user-profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P[^/]+)/$'] Here is my View file; from django.shortcuts import render, redirect from django.http import HttpResponse #from django.urls import reverse from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.db.models import Q from .models import Message, Room, Topic from .forms import RoomForm def userProfile(request, pk): user = User.objects.get(id=pk) rooms = user.room_set.all() context = {'user': user, 'rooms': rooms} return render(request, 'base/profile.html', context) here is my URL: from django.urls import path from . import views urlpatterns=[ path('', views.home, name="home"), path('room/<str:pk>/', views.room, name="room"), path('profile/<str:pk>/', views.userProfile, name='user-profile'), ] 'Error during template rendering' In template C:\Users\Nonesi\Desktop\StudyBudy\base\templates\base\feed_component.html, error at line 9 so here is my template: <div> {% for room in rooms %} <div> {% … -
getting 127.0.0.1 refused to connect. when try to add new fk in django admin
Hi i am always getting 127.0.0.1 refused to connect. error on popup when i tring to add new fk in existed model using + in django admin . is i am using "admin_interface",and some other package also i tried which are in installed apps ,is that reason that i am getting this error. i try to pass "*" in ALLOWED_HOSTS in setting.py , when i am trying that process in google chrome browser it show as i share in image 1 but when i tring to do same with firefox it is shared in second image . my setting.py file import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '' DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ # 'grappelli', "admin_interface", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mdeditor', "colorfield", 'drf_yasg', "rest_framework", 'django_filters', "corsheaders", "storages", 'rest_framework_swagger', 'authentication', 'mails', 'authors', 'book_store', 'institude_home_page', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'vani_prakashan.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'vani_prakashan.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } REST_FRAMEWORK = { # 'DEFAULT_AUTHENTICATION_CLASSES': [ # 'apps.authentication.backends.JWTAuthentication', # … -
how to send input date value from template to backend through ajax request - django
i've to make a query base on two dates, if the dates exists, if not just run the query without any filtration, but i dont know how send the dates input value from client side to server side , here is my views def priceByDateTime(request): start = request.GET.get('from') end = request.GET.get('to') print(start,end)# if start and end: datetimes = MyModel.objects.filter(invoice__created_at__range=(start,end)).annotate( total_price=Sum( (F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)) ).annotate( total_quantity=( Count('pk') ) ).aggregate( all_price=Sum(F('total_price')), all_qnt=Sum(F('total_quantity')) ) else: datetimes = MyModel.objects.all().annotate( total_price=Sum( (F('price')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)) ).annotate( total_quantity=( Count('pk') ) ).aggregate( all_price=Sum(F('total_price')), all_qnt=Sum(F('total_quantity')) ) return JsonResponse(datetimes,safe=False) @login_required def queryTemplate(request): return render(request,'myapp/datetimes.html') i know how to make the query dont sure how send the input date type values to backend and here is my GET form, to get the two date from $(document).ready(function(){ const start_date = new Date($('#from').val()); const end_date = new Date($('#to').val()); console.log(start_date) console.log(end_date) if(start_date && end_date){ data={ 'from':start_date, 'to':end_date } } function dateTimePrices(){ $.ajax({ type:'GET', url:'/prices/dateTime/data', data:data, success:function(data){ const datetimes = data; var k = '<tbody>'; if(datetimes){ k+= '<tr>'; k+= '<td>' + datetimes["all_qnt"] + '</td>'; k+= '<td>' + datetimes['all_price'] + '</td>'; k+= '</tr>' }else{ k+= '<td class="p-2 text-xs border border-purple-900 md:text-base textpurple" colspan=6>found nothing</td>' } k+='</tbody>' document.getElementById('datetime_list').innerHTML = k } }) } dateTimePrices(); }) <form action="" … -
How to keep current url including parameters in JavaScript
I am using the modal to edit data by using the code below, and when I click the 'Change' button, I want to keep the current url. Even when I set a parameter, I don't want me to lose the parameter. This url has no parameters set. So, if I edit data in modal and click the 'change' button, I lose all the parameters I set and return to the initialized screen. I am using Django and python, and I am getting parameter values through request.POST.get method in views.py . function (data, status, xhr) { let code = data.code if (code === 'error') { for (let i in fields) { let key = fields[i]; let labelElement = editForm.find('label[for=' + key + ']'); let container = labelElement.parent(); if (key in data.error) { container.addClass('card-inverse-danger'); const msg = data.error[key][0]; let text = $('<div class="text-danger small" style="line-height: 1rem;">' + msg + '</div>') labelElement.find('.text-danger').remove(); labelElement.append(text); } else { container.removeClass('card-inverse-danger'); labelElement.find('.text-danger').remove(); } } } else if (code === 'success') { window.location.href = '/study/help/'; --> I think I need to update this line. } }) -
I am unable to serialize my product images in Django Rest Framework
I am trying to create product model for my e-commerce app in Django rest framework, and I am able to upload images to my products on the admin panel but I am unable to get their links while calling the API. Here's my: models.py from django.db import models from api.category.models import Category from api.color.models import Color from api.size.models import Size class Product(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=250) regular_price = models.CharField(max_length=50) sell_price = models.CharField(max_length=50, blank=True, null=True) stock = models.CharField(max_length=50) is_active = models.BooleanField(default=True, blank=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True) colors = models.ManyToManyField(Color) sizes = models.ManyToManyField(Size) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.name class ProductImage(models.Model): product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image = models.FileField(upload_to = 'images/') def __str__(self): return self.image.url serializer.py from django.db.models import fields from rest_framework import serializers from .models import Product, ProductImage class ImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImage fields = ('image', ) #print(model) class ProductSerializer(serializers.HyperlinkedModelSerializer): colors = serializers.StringRelatedField(many=True) sizes = serializers.StringRelatedField(many=True) image = ImageSerializer(many=True, read_only=True) class Meta: model = Product fields = ('id', 'name', 'description', 'regular_price', 'sell_price', 'category','colors', 'sizes', 'image') admin.py from django.contrib import admin from .models import Product, ProductImage class ProductImageAdmin(admin.StackedInline): model = ProductImage @admin.register(Product) class ProductAdmin(admin.ModelAdmin): inlines = [ProductImageAdmin] class Meta: model … -
How to add redis sentinel in django apps?
I have a django application and I want to use redis sentinel for high availabilty. Since Django has added support for redis in its latest version (i.e django 4.0) so I am thinking to use it, but if a better solution is available in django-redis or django-redis-cache I might use them too. The sample Caching settings is given below from django-documentation. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': [ 'redis://127.0.0.1:6379', # leader 'redis://127.0.0.1:6378', # read-replica 1 'redis://127.0.0.1:6377', # read-replica 2 ], } } Here first node is master and other two nodes are its replica(or slaves). I wanted to ask how could I configure these settings so I could use them in my application. -
How to assign Foreign key inside loop Django
enter image description hereI want assign foreign key to each colors in loop colorArray=[{color:'red', product_id:5}, {color:'yellow', product_id:5}] Product Model class Product(models.Model): name = models.CharField(max_length=500) brand = models.CharField(max_length=500) description = models.CharField(max_length=500) Color Model class Color(models.Model): colorName = models.CharField(max_length=500) product_id = models.ForeignKey(Product, on_delete=models.CASCADE) views class AddColors(APIView): def post(self,request): for i in colorArray: s=AddColors() s.colorName=i['color'] s.product_id=i[Product.objects.get(id=i['product_id'])] s.save() return Response({'colors Saved'}) -
Mock API call in model signal Django
I am new to Django and unit tests, so any feedback is very helpful. I built a small integration with a third party to create a matching account in their system whenever an account is created in our system. I do this on a signal in the model class. The signal is simple and looks like this: @receiver(post_save, sender=Company) def create_integration_company(sender, instance, created, **kwargs): if created: company_integration_id = third_party.create_crm_company(instance) instance.integration_id = company_integration_id instance.save() When I ran our tests, it created thousands of accounts in this third party's system, so I discovered mock. We have a bunch of tests that create companies and I was wondering if I have to add this to every one of them? @mock.patch("apps.accounts.utils.build_request", return_value="123") My question is: at which level should I mock the response and just return 123 for the new integration id? Can I do it at the model level? Or do I have to do this for every test case we have? -
How to specify custom auth backend for single login view only?
I have a two login api endpoints. One for normal user where user login with only username and for staff users user should login with valid username and password. class PasswordLessBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = User.objects.get(username=username) except User.DoesNotExist: return None else: if self.user_can_authenticate(user): return user AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "users.backends.PasswordLessBackend", ] I want to remove my custom backend from settings and apply this in this login view only since other login for staffs should require correct password as well. class NormalUserLoginView(APIView): permission_classes = [permissions.AllowAny] def post(self, request): serializer = NormalUserLoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) username = serializer.validated_data.get("username") user = authenticate(username=username) if user is not None: refresh_token = RefreshToken.for_user(user) access_token = refresh_token.access_token data["access_token"] = str(access_token) data["refresh_token"] = str(refresh_token) -
uWSGI uid to get database connection
I am trying to work out the correct config to automate and not sure how to reconcile user id for uwsgi. I have a (Ubuntu system) user called 'prod' who owns the source code for a Django site, and a postgres database 'dbprod' with owner 'prod'. I can define a .pgpass in /home/prod so that the prod user can access the database without typing in a password. This is the postgres way. I am worried that running my uwsgi worker processes as this user ('prod') is wrong / insecure, in that if someone subverts the web-server process, they can change the code and the data and I'm toast, whereas if the process was owned by www-data who only had 'read' access to the source code, they'd need another exploit. If I make that change, to a different user (e.g. www-data), the database connection can't be established because www-data can't access 'prod''s home/.pgpass. I don't think I want 'www-data' to access the database. What is the correct approach now? (I know using docker is normal and would make this look somewhat different, but the fundamental issue of minimising privileges is the same) -
How do i paginate objects grouping by their date in each page?
Trying to paginate a list of objects by their date. For example: page 1 -> objects date is smaller than today page 2 -> objects date is equals to today page 3 -> objects date is equals to tomorrow and so on. Each page can have different number of elements. -
Change django picture img src in template based on min-width
I wasn't sure how to ask this question. Want to send correctly sized images to different screens from my django application. I have it so that when an image is uploaded, that it is saved to media but with multiple sizes. So, the image above shows in my media/uploads/pieces/{ID}/Sargent.jpg and all of it's other sized images. The models imageField is pointing to the "original" file without an underscore and width. templates/art/piece_detail.html <picture> <source media="(min-width:300px)" srcset="{{ piece.image.url ??? }}"> <source media="(min-width:375px)" srcset="{{ piece.image.url ??? }}"> <source media="(min-width:786px)" srcset="{{ piece.image.url ??? }}"> <source media="(min-width:1440px)" srcset="{{ piece.image.url ??? }}"> <img src="{{ piece.image.url }}" alt="{{ piece.name }} - {{ piece.height }} x {{ piece.width }}"> </picture> Then here I am using an HTML <picture> tag with some source medias to be how I serve the appropriate image. However I am at a loss on maybe the best way to do what I am trying to accomplish. I realize these break points are probably not exactly what I need, but just trying to get my idea across. I thought about adding more "path" fields to the Piece model and set them to these other URL paths too, but that seems like a sloppy solution to … -
Importing FDB file in Django Python in Visual Studio Code?
I am working in Django framework in Python using Visual studio code, I want to import an FDB file but I'm new to Django, therefore can't figure out how to do it. It would be really appreciated if I Could get what steps to follow to do it. Thanks -
Bizarre login/session error scenario with Django
if anyone could help I would be very thankful, I'm so confused and dumbfounded. The Scenario When we create a user on our sign up page, it redirects to the profile page where we can view all the attributes of the user, like it should. Creating a new user Getting Redirected after creating new Since we have not implemented logout yet, on a new incognito browser (to start a clean session with no pre-existing variables) we log in using an existing admin, we can see the user entry as well in the database. However, now when we use another new incognito tab to log into this new user, django refuses to log us in, and we get a 403 forbidden error and we are redirected to a error httpresponse page. Here is the bizzare part, when we change the password through the user table on the admin page, then decide to login again using a new incognito browser, it logs us in. We thought it was a problem with the password, so we got rid of the hash to see the raw password. So we tried again with a new user, confirming the password was the same. Also, when we …