Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apache showing "Index of /" directory instead of my functional django applicate
I am using windows 10 in conjunction with XAMMP (Apache) to host my website. What it looks like: https://imgur.com/a/yCtIH4M Here is the relevant segment of my htconfigs doc. LoadModule wsgi_module "C:/Users/taber/AppData/Local/Programs/Python/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/taber/AppData/Local/Programs/Python/Python310" WSGIPythonPath "C:\xampp\htdocs\neostorm" ################################################################################################## # NEOSTORM.US.TO VIRTUAL HOST # ################################################################################################## <VirtualHost *:443> ServerName neostorm.us.to Alias /static "C:/xampp/htdocs/neostorm/static" <Directory "C:/xampp/htdocs/neostorm/static"> Require all granted </Directory> WSGIScriptAlias / "C:/xampp/htdocs/neostorm/neostorm/wsgi.py" <Directory "C:/xampp/htdocs/neostorm/neostorm"> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> ################################################################################################## # MAIL.NEOSTORM.US.TO VIRTUAL HOST # ################################################################################################## <VirtualHost *:443> ServerName mail.neostorm.us.to DocumentRoot "C:/xampp/htdocs/webmail" <Directory "C:/xampp/htdocs/webmail"> Require all granted </Directory> </VirtualHost>``` [1]: https://i.stack.imgur.com/klF8N.png [2]: https://i.stack.imgur.com/DS0a5.png -
How do I generate Django seed data for a model that has a "through" field?
I'm using Python 3.9 and Django 3.2. I want to define Address objects for my Coop models, so I have set up these models ... class Coop(models.Model): = ,,, addresses = models.ManyToManyField(Address, through='CoopAddressTags') class CoopAddressTags(models.Model): coop = models.ForeignKey(Coop, on_delete=models.SET_NULL, null=True) address = models.ForeignKey(Address, on_delete=models.SET_NULL, null=True) address_is_public = models.BooleanField(default=True, null=False) My question is, how do I generate YAML seed data that creates the address, coop, and its join table data (CoopAddressTag), linking the two? address_pks = Command.get_and_print_address_yaml(file_path, city_pks) ... for row in input_file: id = row['ID'].strip().encode("utf-8", 'ignore').decode("utf-8") ... # Output the coop print("- model: directory.coop") print(" pk:",id) print(" fields:") print(" name: \"",name,"\"", sep='') print(" types:") for entry in types: print(" - ['", entry, "']", sep='') print(" addresses: [", address_pk, "]") print(" enabled:",enabled) if phone: print(" phone:",contact_phone_pk) if email: print(" email:",contact_email_pk) print(" web_site: \"",web_site,"\"", sep='') print(" approved: True", sep='') I need the Coop to exist before I can generate the join table data (CoopAddressTag), but then I'm confused about how to then enter the address data in the Coop in the YAML. -
In django models, how to add a constraint that looks across multiple rows
In the model below, I define a user, a habit the user is trying out, the start date (required) and end date (if the habit has ended). I want to add a constraint that each user can only be actively in one habit at a time. There is conceptually a few ways to determine this: For a specific user, only one habit has a NULL end date or for a specific user, the start-end range does not overlap for any of their habits, etc. I'm not sure how to approach writing this constraint, since it is looking across multiple rows instead of checking validity within one row. Any help getting started would be appreciated. from django.db import models from django.contrib.auth.models import User from django.db.models import F, Q class HabitChoices(models.TextChoices): NUTRITION = 'nutrition', 'Nutrition' EXERCISE = 'exercise', 'Exercise' SLEEP = 'sleep', 'Sleep' STRESS = 'stress', 'Stress' ALCOHOL = 'alcohol', 'Alcohol' SMOKING = 'smoking', 'Smoking' class HabitStatus(models.Model): """ This model keeps track, at a high level, of which habit the user is currently in. """ user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) habit_name = models.CharField(max_length=10, choices=HabitChoices.choices, default=HabitChoices.NUTRITION) start_date = models.DateField() end_date = models.DateField(null=True, blank=True) def is_current_habit(self): if self.end_date == None: return True else: … -
How can I reset a forloop.counter0 in django?
I have a code in django that creates a carousel for each card item. As I am looping through each image for each specific card, I realized the forloop.counter will keep continuing until the initial for loop has finished. So in my example, i is my initial loop and p is my secondary loop. i loops through cards and p loops through images within the carousel of each card. I need to reset the counter after one i so that the carousel counter starts from the beginning so that first image of every carousel is active. I'd really appreciate any help {% for i in inspections %} <div class="card - mb-3" style="width: 40 rem;"> <div id="myCarousel" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> {% for p in photos.all %} {% if p.inspection_id == i.id %} <button type="button" data-bs-target="#myCarousel" data-bs-slide-to="{{ forloop.counter0 }}" class="{% if forloop.counter0 == 0 %} active {% endif %}" aria-current="true" aria-label="Slide {{forloop.counter0}}"></button> {% endif %} {% endfor %} </div> <div class="carousel-inner"> {% for p in photos.all %} {% if p.inspection_id == i.id %} <div class="carousel-item {% if forloop.counter0 == 0 %} active {% endif %}"> <img src="{{ p.InspImages.url }}" class="img-responsive mx-auto d-block w-80" height="300" alt="..."> </div> {% endif %} {% … -
Is there a way to install memcached on windows server 2019?
I am trying to deploy my Django 4.0 project on Windows Server 2019, I am finding it difficult to install memcached -
Python migrations custom user model
I was wondering if anyone could point me in the right direction, please? I have built a custom user model as per the below code, however, when I run 'make migrations' it doesn't seem to pick up a few of the fields I have added in the custom user model. I think this is the cause of the following error message whenever I try to create a superuser. Traceback (most recent call last): File "G:\Shares\Website\Development\Intranet\HealthcareProject4\manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 184, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File ".\HealthcareProject4\Users2\models.py", line 32, in create_superuser return self._create_user(email, password, True, True, **extra_fields) File ".\HealthcareProject4\Users2\models.py", line 23, in _create_user date_joined=now, **extra_fields) File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\db\models\base.py", line 485, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg) TypeError: 'is_staff' is an invalid keyword argument for this function import datetime from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from django.core.mail import send_mail from django.utils.translation import ugettext_lazy as _ class … -
Is there a way to add additional fields on an implicit many-to-many table in Django?
Consider the following models in models.py: class Volunteer(models.Model): account = models.OneToOneField( UserAccount, on_delete=models.CASCADE, related_name= "volunteer", primary_key=True) request_offers = models.ManyToManyField('Request', related_name="volunteers", blank = True) volunteer_communities = models.ManyToManyField('Community', related_name="volunteers", blank = True) class Request(models.Model): req_type = models.ForeignKey('RequestTypes', related_name="requests", on_delete = models.CASCADE, blank = False, null = False) A volunteer can have many request_offers(type of request). In the implicit appname_volunteer_request (many-to-many) table, I want another field called date besides the default fields -- id, request_id and volunteer_id. Is there a way to add an additional field on the implicit table without creating a through table? Thanks! :) -
Django Forms to an API payload?
I am using a Django form to generate my HTML form. I wanted to use the data from my form as an API payload. if request.method == 'POST': form = GetKeyForm(request.POST) if form.is_valid(): appkey = form.cleaned_data['appkey'] secretkey = form.cleaned_data['secretkey'] shop_token = form.cleaned_data['shop_token'] shop_domain = form.cleaned_data['shop_domain'] payload = { "account_platform": { "shop_token": {shop_token}, "shop_secret": "", "shop_domain": {shop_domain}, }, "utoken": {utoken} } headers = { "Accept": "application/json", "Content-Type": "application/json" } This is the error that I am getting: Object of type set is not JSON serializable -
ModuleNotFoundError: No module named 'django_heroku' (Python help)
I'm having a lot of trouble with deploying to heroku with the python crash course material. I have tried a few things but continually feel clueless as to why it's not working? Seems the main error seems to be: ModuleNotFoundError: No module named 'django_heroku' What i've tried so far: installing pyscopg2-binary (instead of psycopg2==2.7.*) installing django-heroku installing gunicorn A few other things as well. Thanks for your help! Here is the wsgi.py file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learning_log.settings') application = get_wsgi_application() This is in my settings.py: LOGIN_URL = 'users:login' #heroku settings import django_heroku django_heroku.settings(locals()) this is my Procfile: web: gunicorn learning_log.wsgi --log-file - here is my requirements.txt file: beautifulsoup4==4.10.0 bootstrap4==0.1.0 dj-database-url==0.5.0 dj-static==0.0.6 Django==4.0.2 django-bootstrap4==22.1 django-heroku==0.3.1 django-on-heroku==1.1.2 gunicorn==20.1.0 psycopg2-binary==2.9.3 soupsieve==2.3.1 sqlparse==0.4.2 static3==0.7.0 whitenoise==6.0.0 And here is my --tail log (sorry about the length!) (ll_env) $ heroku logs --tail 2022-03-13T20:49:27.347897+00:00 app[web.1]: Traceback (most recent call last): 2022-03-13T20:49:27.347897+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-03-13T20:49:27.347898+00:00 app[web.1]: worker.init_process() 2022-03-13T20:49:27.347898+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process 2022-03-13T20:49:27.347898+00:00 app[web.1]: self.load_wsgi() 2022-03-13T20:49:27.347899+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-03-13T20:49:27.347900+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2022-03-13T20:49:27.347901+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi 2022-03-13T20:49:27.347901+00:00 app[web.1]: self.callable = self.load() 2022-03-13T20:49:27.347902+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line … -
django-filter list of links
I'm using django-filter's ChoiceFilter to generate a dropdown to filter results and it works great. However a dropdown is not what I have in mind for the design, instead I would like to use a list of links, but I can't find if there is such a filter. How can I have a list of links instead of a dropdown ? Current: Desired: views.py class manufacturerFilter(django_filters.FilterSet): manufacturer=django_filters.ChoiceFilter(choices=[]) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.filters['manufacturer'].extra['choices'] = [ (wheel, wheel) for wheel in WheelItem.objects.values_list('manufacturer', flat=True).distinct() ] -
error with 'str' object has no attribute 'save' for my django project
I take an error as 'str' object has no attribute 'save'. I couldn't find where is the problem. How can I fix it? [enter image description here][1] error screenshot: [1]: https://i.stack.imgur.com/87joO.png my model code: from django.http import HttpResponse from django.shortcuts import render, HttpResponse, HttpResponseRedirect from .models import yazi from .forms import CreateForm from django.utils.text import slugify # Create your views here. def postliste_view(request): yazilar = yazi.objects.all() return render(request, "liste.html", {"yazilar": yazilar}) def postdetail_view(request, id): yaziNesne = yazi.objects.get(id=id) return render(request, "detail.html", {"yazi" : yaziNesne}) def postcreate_view(request): form = CreateForm() return render(request, "create.html", {"form" : form} ) def formdoldur_view(request): form = CreateForm(request.POST or None, request.FILES or None) if form.is_valid(): yaziNesne = form.save(commit=False) yaziNesne = slug = slugify(yaziNesne.başlık) yaziNesne.save() return render(request, "gonderildi.html", {}) def postupdate_view(request, id): if request.GET: baslik = request.GET.get("baslik") metin = request.GET.get("metin") yaziNesne = yazi.objects.get(id=id) yaziNesne.başlık = baslik yaziNesne.metin = metin yaziNesne.save() else: yaziNesne = yazi.objects.get(id=id) return render(request, "update.html", {"yazi" : yaziNesne}) def postdelete_view(request, id): yaziNesne = yazi.objects.get(id=id) yaziNesne.delete() return HttpResponseRedirect("/post") # database api --> veritabanı işlemlerini yapan fonksiyonlar # django shell --> djangonun python kabuğu -
Set is_staff to true for new users that created new accounts from CreateView
I am having problem with Django. I am using UserCreationForm and generic CreateView in order for people to sign up and create an account. The code is as follows: Custom form: class SignUpCustomUserForm(UserCreationForm): first_name = forms.CharField(max_length=200) last_name = forms.CharField(max_length=200) email = forms.EmailField(max_length=200) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2'] View: class SignUpView(generic.CreateView): form_class = SignUpCustomUserForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' I do not have a model since I am using CreateView which basically handles the model. I want to automatically set every new created account as staff, but I can not figure out how to do it. Basically, I am working on a form which users can use to create an account with is_staff privileges and they can use those accounts to login to /admin (the default django admin). I tried setting model.is_staff to true in the Meta class inside the form class, but it didn't work out. Any advice or ideas is welcomed. Thank you -
bootstrap - modiyfying d-flex to not increase the width of input fields
I am currently experiencing a bug/issue that involves the use of d-flex. What is happening, upon the entering of invalid credentials, the error message that is outputted is causing the width of the input fields to change. Is there a way to still use d-flex and have the widths of the input fields fixed? Please see below my code: {% extends 'healthwithfriends/base.html' %} {% load widget_tweaks %} {% block content %} <section class="vh-100"> <div class="container h-100"> <div class="row d-flex justify-content-center align-items-center h-100"> <div class="login-card-container"> <div class="card custom-card text-white"> <div class="card-body p-5"> <div class="d-flex justify-content-center"> <h3>Health With Friends</h3> </div> <div class="d-flex justify-content-center mt-4"> <form method="POST"> {% csrf_token %} <div class="input-group mb-3"> <span class="input-group-text"><i class="fas fa-user"></i></span> {% render_field form.username type="text" class="form-control" placeholder="Username" %} </div> <div class="input-group mb-3"> <span class="input-group-text"><i class="fas fa-key"></i></span> {% render_field form.password type="password" class="form-control" placeholder="Password" %} </div> {% if form.non_field_errors %} <ul class='form-errors'> {% for error in form.non_field_errors %} <div class="alert alert-danger"> <b>{{ error|escape }}</b> </div> {% endfor %} </ul> {% endif %} <div class="d-flex justify-content-center mt-3 login-btn-container"> <button type="submit" name="button" class="btn btn-primary login-btn">Login</button> </div> </form> </div> <div class="mt-4"> </div> <div class="d-flex justify-content-center"> <p>Don't have an account? <a href="{% url 'sign up' %}" class="link-info">Register here</a></p> </div> </div> </div> </div> </div> … -
Unable to perform migration using Django and PostgreSQL
For the project that I have been working on we are using Django as the backend and PostgreSQL as out database. I have already installed all the required files for PostgreSQL and also created a database for the project. I keep on getting the following error when I try to perform migration. This is first part of the error after running python3 manage.py migrate This is last part of the error after running python3 manage.py migrate It says that it is unable to make connection with the port but I don't have any server running. I was using docker to connect the backend with frontend, but I ran docker-compose down command to take down docker. This is how I have setup the database for my project in PostgreSQL (This is the first time I am trying to perform migration in my computer for this project)Database setup in PostgreSQL -
How to reverse lookup the foreign key in Django
I have 2 models class Vendor(models.Model): vendor_name = models.CharField(max_length=50) class Food(models.Model): vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) food_title = models.CharField(max_length=50) I want to search for the vendors based on the vendor_name as well as food_title. Currently, I am able to get the vendors using this filter: keyword = "vendor name or food title" vendors = Vendor.objects.filter(vendor_name__icontains=keyword) The above filter will only work for vendor names. But, I want to get the vendors based on the food title as well. -
Django deployment on heroku throwing ModuleNotFoundError at / No module named 'pandas'
I have pandas and numpy installed in my pipenv and have checked that my requirements.txt is up to date and everything is installed. The app works fine on localhost but when it deploys my browser throws: ModuleNotFoundError at / No module named 'pandas' Request Method: GET Request URL: https://game-recs.herokuapp.com/ Django Version: 4.0.3 Exception Type: ModuleNotFoundError Exception Value: No module named 'pandas' Exception Location: /app/recommender/algorithm/code.py, line 1, in <module> Python Executable: /app/.heroku/python/bin/python Python Version: 3.10.2 Python Path: ['/app', '/app/.heroku/python/bin', '/usr/bin/python', '/app/.heroku/python/lib/python310.zip', '/app/.heroku/python/lib/python3.10', '/app/.heroku/python/lib/python3.10/lib-dynload', '/app/.heroku/python/lib/python3.10/site-packages'] All the other modules work fine... could this be a path issue? The project was deploying well until I added in a python file importing pandas. requirements.txt asgiref==3.5.0 backports.zoneinfo==0.2.1 dj-database-url==0.5.0 Django==4.0.3 gunicorn==20.1.0 numpy==1.22.3 pandas==1.4.1 psycopg2==2.9.3 psycopg2-binary==2.9.3 python-dateutil==2.8.2 pytz==2021.3 six==1.16.0 sqlparse==0.4.2 waitress==2.1.0 whitenoise==6.0.0 Heroku build logs (no error until I try to view the site) 2022-03-13T19:35:31.010043+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed 2022-03-13T19:35:31.010043+00:00 app[web.1]: File "/app/gamerecs/urls.py", line 25, in <module> 2022-03-13T19:35:31.010043+00:00 app[web.1]: from recommender.views import ( 2022-03-13T19:35:31.010043+00:00 app[web.1]: File "/app/recommender/views.py", line 12, in <module> 2022-03-13T19:35:31.010044+00:00 app[web.1]: from .algorithm.code import getRec 2022-03-13T19:35:31.010044+00:00 app[web.1]: File "/app/recommender/algorithm/code.py", line 1, in <module> 2022-03-13T19:35:31.010044+00:00 app[web.1]: import pandas as pd 2022-03-13T19:35:31.010045+00:00 app[web.1]: ModuleNotFoundError: No module named 'pandas' 2022-03-13T19:35:31.010939+00:00 app[web.1]: 10.1.49.237 - - … -
Django Channels showing current users in a room
I'm trying to show the current users that are connected to same websocket (in my case chat room) but I have a little problem. I want to create variable that stores the users and send it trough websockets to my frontend, I've achieved that, but here is the problem. Consumers.py - approach 1 class ChatRoomConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.users: list = [] @database_sync_to_async def create_msg(self, user_id=None, message=None, room=None): if user_id is not None: sender = User.objects.get(id=user_id) msg = Message.objects.create( author=sender, message=message, room_name=room) msg.save() return msg else: get_msgs = Message.objects.filter(room_name__in=[room]) serializer = MessageSerializer(get_msgs, many=True) return serializer.data async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = f'chat_{self.room_name}' self.messages = await self.create_msg(room=self.room_name) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.send(text_data=json.dumps({ 'db_messages': self.messages, })) async def disconnect(self, close_code): print(close_code) await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) type = text_data_json['type'] message = text_data_json['message'] username = text_data_json['username'] user_id = text_data_json['user_id'] self.user_id = text_data_json['user_id'] if type == 'chatroom_message': self.msg = await self.create_msg(user_id, message, self.room_name) await self.channel_layer.group_send( self.room_group_name, { 'type': type, 'message': message, 'username': username, 'user_id': user_id } ) async def chatroom_message(self, event): message = event['message'] username = event['username'] await self.send(text_data=json.dumps({ 'message': message, 'username': username, })) # nefunkcni ukazatel momentalnich … -
How to fix render() got an unexpected keyword argument 'path'
I have this code that uses folium which uses render to the map background appearance. !pip install folium import folium carparks = folium.Map(location=[50.68, -1.2667], width = 960, height = 500, zoom_start=11) # The following loops through the location items, splitting out the car part name # and the location as a pair of latitude and longitude values. # For each location, it then plots a circle marker on the map with the name as a popup string. for name, location in locations.items(): folium.CircleMarker(location=location, popup=name, radius=20, color='blue', fill_color='blue', fill_opacity=0.2).add_to(carparks) # we create the HTML file for the map, and display it below. carparks.render(path = 'data/IOWcarparlocations.html') carparks.render_iframe = True carparks but it gives this error : TypeError: render() got an unexpected keyword argument 'path' -
Problem with saving object in django-rest-framework
This is my view where I save Order object with values from frontend: @api_view(['POST']) @permission_classes([AllowAny]) def generate_bank_transfer_order(request): if request.method == "POST": body = json.loads(request.body) first_name = body.get("firstName") last_name = body.get("lastName") full_name = f"{first_name} {last_name}" today = datetime.now() transaction_id= f'00{today.strftime("%S%M%H%d%m%y")}' code_base = body.get('code') try: code = Code.objects.get(code = code_base) new_order = Order(email=body.get("email"), message=body.get("message"), city=body.get("city"), adress=body.get("adress"), postal_code=body.get("postalCode"), phone=body.get("phone"), full_name=full_name, product_names=body.get("cart"), shipment_fee=body.get("shipmentFee"), shipment_method=body.get("shipmentMethod"), transaction_id=transaction_id, total_price=body.get("price"), code=code) new_order.save() return JsonResponse({"success":new_order.transaction_id}) except ObjectDoesNotExist: new_order = Order(email=body.get("email"), message=body.get("message"), city=body.get("city"), adress=body.get("adress"), postal_code=body.get("postalCode"), phone=body.get("phone"), full_name=full_name, product_names=body.get("cart"), shipment_fee=body.get("shipmentFee"), shipment_method=body.get("shipmentMethod"), transaction_id=transaction_id, total_price=body.get("price")) new_order.save() return JsonResponse({"success":new_order.transaction_id}) This is my Order model: class Order(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, blank=True, null=True) message = models.TextField(max_length=1000, blank=True, null=True) email = models.EmailField(max_length=255, blank=True, null=True) city = models.CharField(max_length=75, default='') adress = models.CharField(max_length=100) postal_code = models.CharField(max_length=6) phone = models.CharField(primary_key=True, max_length=9, validators=[RegexValidator(r'^\d{9}$/')]) full_name = models.CharField(max_length=100) product_names = models.TextField(max_length=5000) shipment_fee = models.IntegerField(default=0) shipment_method = models.CharField(blank=True, null=True, max_length=50) code = models.ForeignKey(Code, on_delete=models.SET_NULL, null=True) transaction_id = models.CharField(max_length=150, default=0) total_price = models.DecimalField(default=0, max_digits=12, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) accepted = models.BooleanField(default=False) shipped = models.BooleanField(default=False) def __str__(self): return f"{self.email} : {self.transaction_id}" def save(self): if not self.created_at: self.created_at = timezone.now() self.updated_at = timezone.now() return super(Order, self).save() This piece of code is not perfect, but it saves the data I need. The problem is … -
receive the data passed in the body of the request API Django Python
i search a solution to get the data passed in the body of the request on django Python. I searched on the doc and tried functions like request.data/requestPost/httpRequest.body but any not works ! (sorry for my english) -
Cannot assign "": "" must be a '' instance
I am trying to make a registration key in the UserModel where the key field in the registration form is a foreign key to another model called RegistrationKey. I have made two posts about this topic earlier without any success, however has a few things changed in my code which makes those previous posts irrelevant. In the form field, the field for the key is a CharField as I can not display the keys for the users due to safety. These are the two previous posts: Save user input which is a string as object in db , Textinput with ModelChoiceField These are my two models. class RegistrationKey(models.Model): key = models.CharField(max_length=30) def __str__(self): return self.key class User(AbstractUser): key = models.ForeignKey(RegistrationKey, on_delete=models.CASCADE, null=True, blank=True) Since my latest posts have I created a class based view, which looks like this: class RegisterPage(CreateView): form_class = MyUserCreationForm def form_valid(self, form): key = form.cleaned_data['key'] try: keyobject = RegistrationKey.objects.get(key=key) form.instance.key = keyobject return super().form_valid(form) except RegistrationKey.DoesNotExist: form.add_error('key', 'error') return super().form_invalid(form) When I try and pass in the value Admin which is an object in the RegistrationKey model I get the following error: 'Cannot assign "'Admin'": "User.key" must be a "RegistrationKey" instance.' I don't know how to … -
How can I show own order list?
I would like to show all orders of a single user. This Code working perfectly. But the problem Is when I do log out then shows the below error. Even it doesn't go to the previous page. Now, what can I do? Errors: AttributeError at / 'AnonymousUser' object has no attribute 'user_frontend_order' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.3 Exception Type: AttributeError Exception Value: 'AnonymousUser' object has no attribute 'user_frontend_order' Exception Location: C:\Users\DCL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py, line 247, in inner Python Executable: C:\Users\DCL\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['D:\\1_WebDevelopment\\Business_Website', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32\\lib', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\Pythonwin', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Sun, 13 Mar 2022 18:12:22 +0000 Traceback Switch to copy-and-paste view C:\Users\DCL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\DCL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars D:\1_WebDevelopment\Business_Website\business_app\views.py, line 16, in index queryset = request.user.user_frontend_order.all() … views: def index(request): total_user = User.objects.count()-1 frontend_order_list = request.user.user_frontend_order.all() context = { "total_user":total_user, "frontend_order_list":frontend_order_list } return render(request,'0_index.html',context) Models: class Frontend_Order(models.Model): USer = models.ForeignKey(User,default=None,on_delete=models.CASCADE,related_name='user_frontend_order') Service_Type = models.CharField(max_length=250, null=True) Price = models.CharField(max_length=250, null=True) def __str__(self): return str(self.pk)+ str(".") + str(self.USer) -
django calendar, how to display all the days of a month in a single row
In django, How can i show the month calendar as follows in the template examle: year : 2022, Month : March Tue wed thu fri sat sun ---------------wed thu 1 2 3 4 5 6 ---------------30 31 -
Easiest/Best way to restrict people/unknown from accessing Django API?
I've written a Django API and it works well however I want to restrict people/unknown hosts from writing requests to the API. This is because I have a React Frontend deployed at example.com and I want to make sure that only example.com can send requests to the API. I'm not entirely sure how to do this. I was trying to do research into cors however from looking at this thread How can I block calls from unknown domains/IP to my REST API?, it seems like cors can't prevent other hosts/unknown from making requests? I want to secure my API such that only my Frontend host at example.com can make requests to the API and other hosts can't (including stuff like Postman and curl shouldn't be able to make requests). How do I go about doing this? Any help in the right direction is very much appreciated! Thank you so much! -
Django ORM Query Optimization Issue
I am making a blog website and I am facing some issues with the Query performance. I have 3 models User Model -> Users (To store user email, Password etc) Post Model -> Actual Posts people Model -> (To store users extra information) Post Model -> class Post(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) category = models.ForeignKey(Category, on_delete=models.PROTECT) title = models.CharField(max_length=255,null=True) description = models.CharField(max_length=1000,null=True) Likes = models.ManyToManyField(to=User, related_name='Post_likes') favourites = models.ManyToManyField(to=User,blank=True,related_name="favourite") People Model -> class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) photo = models.ImageField(upload_to='profile_pics', blank=True,null=True) Phone_number = models.CharField(max_length=255,null=True,blank=True) Birth_Date = models.DateField(null=True,blank=True) Created_date = models.DateTimeField(auto_now_add=True) Updated_date = models.DateTimeField(auto_now=True) Now as both of these models are connected to User model. I want to query the Post model and get the user photo in the template. Now when I use post.user.people.photo then for every post it generates a seperate query to DB resulting in slowness. I would like to use Join here to combines multiple tables and fetch all the records at once. I am currently using following Query -> posts = Post.objects.select_related().prefetch_related('images_set').annotate(comments_Count = Count('comments_post',distinct=True)).annotate(Count('Likes',distinct=True)).all().order_by('-id')