Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to run django custom management command using crontab?
I want to delete expired file every min I created command python manage.py delete which delete all expired files. but crontab won't work, I don't know maybe I did something wrong. here cronjobs in settings.py CRONJOBS = [ ('* * * * *', 'django.core.management.commands.delete'), ] so how can I fix this? -
how do I add an item to the cart without the page reloading
So how do I do this? if I gotta use REST api how do I set it up? would really appreciate your help, thx! link to the code: https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352 -
Not able to create heroku-redis for my heroku application
I have been trying to add a heroku-redis add on to my django application deployed on heroku,usually free add-ons like heroku PostgreSQL and heroku-redis should not need me to verify my account with billing but for some reason I can't create a heroku-reddis add-on but can normally create Heroku Postgres add-on Here's the error I'm getting -
Can't send http request from React to Django, using nginx and certbot
I have a docker swarm where I configured a React app on port 3000, Django backend on port 8000, nginx and certbot. On the frontend part everything works great and all the routes have ssl. However, whenever I try to send a request from my React app to Django it fails. Desired behavior: 1.Access frontend on http 2.Nginx forwards it to https 3.Https frontend sends http request to Django 4.Django sends back a http request which is forwarded to https by nginx This fails at step 4 where there is an error because of the https and http trying to communicate with each other. I send my request as: fetch("http://example.com:80/app/receipt") and get the error login.js:55 Mixed Content: The page at https://example.com/login' was loaded over HTTPS, but requested an insecure resource <the same route but http>. This request has been blocked; the content must be served over HTTPS. I understand what the problem is, but I have not configured https separately in my backend app and I was hoping there is a way to do this only from the nginx configure file. From what I read, generating a self-signed certificate is not a good idea. I do not currently understand how … -
Cannot assign "'username'": "Message.sender" must be a "User" instance
I'm fairly new to Django / Channels so apologies if everything required isn't being shown here. I'd be happy to provide further info if necessary. Anyway, I've been working on a one-to-one chat application and am running into this error: ValueError: Cannot assign "'admin'": "Message.sender" must be a "UserProfileModel" instance. This issue is that I thought admin was an instance of my user model? admin is the username of my superuser, which is logged in as I get this error. When I try to change the admin input to self.scope['user] I then get a serialization error. Any help is appreciated. Here is my consumers.py file: import json from channels.generic.websocket import WebsocketConsumer from django.conf import settings (unused) from accounts.models import UserProfileModel from asgiref.sync import async_to_sync from chat.models import Thread, Message class ChatConsumer(WebsocketConsumer): def create_chat(self, msg, sender): new_msg = Message.objects.create(sender=sender, text=msg) new_msg.save() return new_msg def connect(self): self.me = self.scope['user'] self.user_name = self.scope['url_route']['kwargs']['room_name'] self.you = UserProfileModel.objects.get(username=self.user_name) self.thread_obj = Thread.objects.get_or_create_personal_thread(self.me, self.you) self.room_group_name = f'personal_thread_{self.thread_obj.id}' # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() print(f'[{self.channel_name}] [{self.room_group_name}] connected') def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) # WHAT IS TEXT_DATA REFERRING TO? … -
Debugging Django on a deployed remote server
I am running Django with Nginx and Gunicorn on a remote server. There are certain types of interactions I can do on the remote machine (via my web browser) that will cause the webserver to respond with a "502 Bad Gateway nginx/1.10.3 (Ubuntu)" error after doing certain POST operations to the Django webserver. This error happens repeatably after exactly 30 seconds. Which makes me think it's some kind of timeout with Nginx. When I run the Django server locally everything runs fine. But I don't think this is a problem with Nginx, I think it's a problem with Django on the remote system. Can anybody provide any guidance about how to see what is going on with Django on the remote machine? Or how to debug this problem further. -
How to have orderitem and shipping under each order in the admin panel?
how do I make it better for the website operator to process the order, can we have each orderitems and shipping addresses associated with the order to be under each "Order" in the admin panel? would really appreciate your help, thx! models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0) date_added = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=40, choices=STATUS_CHOICES, default="Order Placed") tracking_no = models.CharField(max_length=300, null=True, blank=True) class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) address_one = models.CharField(max_length=200) city = models.CharField(max_length=200) country = models.CharField(max_length=300) zipcode = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) admin.py admin.site.register(Order, OrderAdmin) admin.site.register(OrderItem, OrderItemAdmin) admin.site.register(ShippingAddress, ShippingAddressAdmin) -
How to create arrays out of Rest Api data DJango Angular Typescript
I have this returned and stored in a variable "detections: any =[]" from my rest API in django. [ { "DetectionId": 2, "CityId": 2, "TimeUpdated": "2018-11-20T21:58:44.767594Z", "Percent": 22, }, { "DetectionId": 3, "CityId": 2, "TimeUpdated": "2016-11-20T21:58:44.767594Z", "Percent": 22, } ] Im trying to move all "Percent" and "TimeUpdated" values into seperate arrays so I can connect them to a line graph in ChartJS but as this is my first time using advances typescript and rest APIs I dont know how to approach this problem as I need to have this data connected to a chart. any help or advice is greatly appreciated. -
Django - Is it possible to get objects of "indirectly related one to one field" with reverse_many_to_one_manager?
For instance I have these models: class Company(models.Model): name = models.CharField(max_length=100) class User(AbstractBaseUser): email = models.EmailField(max_length=250, unique=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Company, on_delete=models.PROTECT) is_admin = models.BooleanField(default=False) Now I can easily get all the profiles for a company using the following query: Company.objects.first().profile_set.all() But is there a way I can get the related users from company instead of profile, keeping in mind that a user object is one to one related with profile object? Note: These models are just example models, and keeping in view the application logic, we can't combine user and profile model. -
problem with quering a many to one in django
Im fairly new to Django, I was attempting to make a many to one query in my program. Im making af clinic site, in which I want a list of patients for the given clinic to be shown. I have the following Model.py and views.py: models.py class Klinik(models.Model): class Patient(models.Model): klinik = models.ForeignKey(Klinik, null=True, on_delete=models.SET_NULL) views.py def kartotek(request, kl_id): klinikid = Klinik.objects.get(id=kl_id) patienter = Klinik.Patient_set.all() context = {'patients':patienter,} return render(request,'DentHelp/kartotek.html', context ) The error message is for the _set.all() attribute, but I cant see what the problem should be -
Importing OrbitControls (Django)
So I'm trying to import OrbitControls, but it gives me error. Anyone know way to import it when using Django? Three is imported successfully. code error -
How to create a serializer with multiple models, that are connected to each other?
So I have UserAccount model, which has this fields: class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) iin = models.CharField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) father_name = models.CharField(max_length=255) phone_number = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_doctor = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['iin', 'first_name', 'last_name','father_name', 'phone_number'] def get_full_name(self): return self.first_name + ' ' + self.last_name + ' ' + self.father_name def __str__(self): return self.email And also this class that has user as a foreign key: class Patient(models.Model): user = models.ForeignKey(UserAccount, on_delete=models.CASCADE) district = models.CharField(max_length=255) def __str__(self): return self.user.email So my question is how to create a serializer for the registration? How am I supposed to create a UserAccount and Patient which has UserAccount as a foreign key together??? PLS HELP This is my diploma work THIS DOES NOT WORK class RegistrationSerializer(serializers.ModelSerializer): class PatientCreateSerializer(serializers.ModelSerializer): class Meta: model = Patient exclude = ['user'] patient = PatientCreateSerializer() class Meta: model = UserAccount fields = '__all__' def create(self, validated_data): patient_data = validated_data.pop('patient') user_instance = UserAccount.objects.create(**validated_data) Patient.objects.create(user=user_instance,**patient_data) return user_instance Also, how am I supposed to send data in POSTMAN? LIKE THIS? { "patient": { "district": "2323232", "user": [{ "email": "someemail@gmail.com", "iin": "02020202002", "first_name": "Some", "last_name": … -
How can we get data of current logged in user in flutter if used django as a backend
I want to show widgets in flutter as per the types of user logged in. For example if the user is logged in as seller, he/she can see widgets to sell the goods and if he/she is buyer they should get option to buy goods. I want to achieve this in flutter with django backend... -
django-tenants: Restrict access to public schema
I am trying to create a multi tenant app (with shared database and isolated schema) using this Django-Tenants package. And I've followed the example videos to setup a demo: video1 and video2 app clients (models.py) from django.db import models from django_tenants.models import TenantMixin, DomainMixin class Client(TenantMixin): name = models.CharField("Customer name", max_length=100) created_on = models.DateField(auto_now_add=True) # default true, schema will be automatically created and synced when it is saved auto_create_schema = True class Domain(DomainMixin): pass app sweet_tenant (models.py) from django.db import models from applications.sweet_shared.models import SweetType class Sweet(models.Model): sweet_type = models.ForeignKey(SweetType, on_delete=models.CASCADE) name = models.CharField(max_length=50) price = models.DecimalField(default=0, decimal_places=3, max_digits=8) def __str__(self): return self.name app sweet_shared (models.py) from django.db import models class SweetType(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name settings # Application definition SHARED_APPS = [ "django_tenants", # mandatory 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # shared apps "applications.clients", "applications.sweet_shared", ] TENANT_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # your tenant-specific apps "applications.sweet_tenant", ) INSTALLED_APPS = SHARED_APPS + [app for app in TENANT_APPS if app not in SHARED_APPS] BEHAVIOUR Public schema are shared with all tenants. Any tenant can see any data form public schema if you don't filter. This is a normal behavior Tenants (clients) are created … -
Django websocket connection failure
Websocket is refusing to connect in my project and showing me this message (index):12 WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/[object%20HTMLScriptElement]/' failed: here is my project repo link : Repository link -
Translation Django doesn't work in template and view
I am bulding an app in django, writing all interface messages in english to after translate them to other language. My first attempt is using the spanish as language target. I have been reading other questions, but I have not had success with translation in view and template. Some questions are: Localization doesn't work Django internationalization doesn't work in my project Django translations does not work Many others In the most of them, the problem is LOCAL_PATHS setting is bad set. However, I followed the recommendations of the answers, so I think this is not my problem and I can't figure out what it is. These are my settings. # Notice a LocalMiddleware MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] # I have a special directory to my templates TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, # Still needed for admin templates ... } # Language settings LANGUAGE_CODE = 'es' LANGUAGES = [ ('en', _('English')), ('es', _('Spanish')), ] # I use BASE/DIR to configure the paths... LOCALE_PATHS = [ BASE_DIR / 'locale', BASE_DIR / 'utils/locale', ] USE_I18N = True Project structure: In each app there are its own 'locale' directories and the tranlations … -
How can I preserve the python '%' character when adding to a string that will be run as html?
Here is some possibly important background info: I am parsing .js paths server-side in python, adding them to the context object. My goal is to reflectively load js packages based on the url endpoint used by the client. @api_view(["GET"]) def home(request, path="tutorial"): return render(request, "template.html", context={ "path" : "{% static '"+ path +".js' %}" }) The issue I've run into is that the '%' character does not convert correctly, as you can see from the server log: [23/Apr/2022 11:05:40] "GET /%7B/%%20static%20'tutorial.js'%20/%%7D HTTP/1.1" 404 2574 I know that '%' is used by python for string manipulation and therefore is added to strings as a multi-char code, but what I can't figure out is how to add a literal %. I've tried '/%', r'', and b'' variations, .encode() too, but none of them change the output. Here is what is being run client side: <script type="text/javascript" src="{{path}}"></script> I've tested everything else, and it all works perfectly. I just can't get python to send html friendly '%'s! -
How To Login A Custom User In Django
Hello This is my models of user app in django, class Customer(AbstractUser): phoneNumber = models.CharField(max_length=30,null=True, blank=True) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False,) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser groups = None user_permissions = None def __str__(self): return self.username class Supplier(AbstractUser): address = models.TextField(max_length=200) phoneNo = models.CharField(max_length=20) staff = models.BooleanField(default=False,) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser groups = None user_permissions = None def __str__(self): return self.username for which i want to implement a login page, i successfully did a signup page using forms class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = Customer fields = UserCreationForm.Meta.fields + ('phoneNumber',) class CustomUserChangeForm(UserChangeForm): class Meta: model = Customer fields = UserChangeForm.Meta.fields class CustomSupplierCreationForm(UserCreationForm): class Meta(UserCreationForm): model = Supplier fields = UserCreationForm.Meta.fields + ('address','phoneNo',) class CustomSupplierChangeForm(UserChangeForm): class Meta: model = Supplier fields = UserChangeForm.Meta.fields then used class SignUpPage(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' class SupplierSignUpPage(generic.CreateView): form_class = CustomSupplierCreationForm success_url = reverse_lazy('login') template_name = 'supplier_signup.html' but i am totally lost as how to implement the login stuff as the doc and google search was overwhelming for me, please help. -
How to give access different object of a model to different users in django by the creator of the object
I am working on a classroom project and I am completely new to Django. How to modify my models (course,user) so that I can add students to the course in two ways 1)By entering the class code by students. 2)By sending join invitations to students from a list of all students by selecting some by the teacher and if the student confirms/accepts he will be added. i am attaching the models below user model class CustomUser(AbstractUser): email = models.EmailField() is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) Course Model class Course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(25)]) classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) slug=models.SlugField(null=True, blank=True) def __str__(self): return self.course_name def save(self, *args, **kwargs): self.slug = slugify(self.classroom_id) super().save(*args, **kwargs) def is_valid(self): pass Teacher Views @login_required def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): course = form.save(commit=False) course.created_by = request.user course.save() messages.success(request, "Class Created Sucessfully") return redirect('/tdashboard') context['add_courses'] = form return render(request, 'teacherview.html', context) @login_required def view_courses(request, *args, **kwargs): courses = Course.objects.filter(created_by=request.user) dict = {'course': courses} return render(request, 'teacherhome.html', dict) -
How to Serialize only valid objects in Django Rest Framework with many=True?
I am asking this question after making a search on the Internet and found nothing of use. (Except for this question, which was not answered) I have the following serializer class StudentSerializer(Serializer): name = CharField(help_text="") age= IntegerField(min_value=0, help_text="") last_name = CharField(required=False, help_text="") def validate(self, attrs): return attrs And following data, to be serialized: data = [ { "name":"Burakhan", "age":27, "last_name":"Aksoy" }, { "name":"Mehmet", "age":27, "last_name":"Randomname" }, { "name":"Cevdet", "age":28 }, { "name":"Ahmet", "age":-2, # This is invalid "last_name":"Yilmaz" } ] When I want to serialize this as follows, serialzied.validated_Data returns an empty List even though only a single object is not valid. serialized = StudentSerializer(data=data, many=True) serialized.is_valid() >>> False serialized.errors >>>[{}, {}, {}, {'age': [ErrorDetail(string='Ensure this value is greater than or equal to 0.', code='min_value')]} serialized.validated_data >>> [] My question is, how can I have a serializer so that only valid ones are serialized and invalids are discarded? Thank you -
Django social-auth-app-django error after social login completed
AttributeError at /social-auth/complete/github/ 'NoneType' object has no attribute 'provider' Other solutions on this site did not solve the problem. Sorry if you see this as a dup. copied from reddit: Hello! Hope everybody is doing well. As the title suggest I keep getting this error every time I try to use the social login on my site. This is for a school and we are using github for the authorization. What I believe is happening is, the user social auth data is being sent somewhere else instead of the user social auth database. The reason I think this is because after github auths my account,and crashes, I can see it grabbed my user name and my email from github correctly in the database, I can see it in my admin. However, The user social auth remains empty.I'm pretty confident that there's a problem with my urlpatterns redirecting data into the damn sun instead of the user social auths database. Again I've got no idea how to fix this. I've been at it for about two weeks now and made no progress into solving this problem, Things I've tried: Social_auth_pipeline, dosen't work using django_allauth crashes the site I've changed my settings … -
login with existing users
I am doing a project in Django where I need to log in through existing users on another web page. For this I have a link to consume the web service and to be able to consume it I enter some parameters, among these is the user login (username) and the password, when the web service is consumed (I use the suds library to consume it), It gives me certain user data such as user, profile, name and status. I tried to search how to do this and I found that I can use the request.META['REMOTE_USER'] but I still don't understand how to implement it, is there an example? -
Server Error on connection for jquery.js and bootstrapmin.js
I am writing a Django project and trying to use jquery and bootstrap min js, but I got the error Failed to load resource: the server responded with a status of 404 (Not Found). When I refresh the page thing like this: GET http://localhost:63342/employeeSystem/app01/templates/%7B%%20static%20'plugins/bootstrap-4.0.0/js/bootstrap.min.js'%20%%7D net::ERR_ABORTED 404 (Not Found) GET http://localhost:63342/employeeSystem/app01/templates/%7B%%20static%20'js/jquery-3.6.0.min.js'%20%%7D net::ERR_ABORTED 404 (Not Found) Here is my implementation of code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheets" href="{% static 'plugins/bootstrap-4.0.0/css/bootstrap.min.css' %}"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <script src="{% static 'js/jquery-3.6.0.min.js' %}"></script> <script src="{% static 'plugins/bootstrap-4.0.0/js/bootstrap.min.js' %}"></script> </body> </html> Here is my file structure(I still need 3 reputation so … -
When i try to delete a model django gives FOREIGN KEY constraint failed
in django i am trying to delete a news in admin page but it gives FOREIGN KEY constraint failed error -
How to send email with pdf attachment using python Django?
I want to send an email with an invoice to the user after the payment process. How can I do it with Django. I tried a few codes but it is not working.