Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channels create a separate task that sends message to group at intervals
Essentially I am trying to create a real time applications for teams with Django channels. What happens is that there is a physics simulator that runs on the server and then sends the game state to be displayed on the client machines. What I need is a function that runs every 1/20 seconds on the server and then sends an output to each socket in a group. What I am currently thinking of doing is using threading to spin up a task (only needs to run for 60s total) which runs the physics simulation and then waits for the remaining time until the next execution. But I can guess that there is a real way to do this with Django channels which I can't find in the documentation. -
Django: Open a form from admin action
I'm trying to change some things inside this logic, so for now I'm only able to send a push notification to one user at the time and I'm trying to make that I would be able to select multiple users. So I have created an admin action which let's me to select some users and now I'm struggling about creating a form which would fulfill the users that I selected. This is what I have now (Sending push notification to one user at the time). Select users that I want to send the push notification. This is my code: class CustomUserAdmin(UserAdmin): fieldsets = ( (None, {'fields': ('password',)}), (_('Personal info'), {'fields': ('email', 'phone', 'companies', 'active_company', 'avatar', 'completed_registration', 'language')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined', 'work_hours_until', 'work_hours_from')}), (_('Terms and conditions agreement'), {'fields': ('agreement_date', 'agreement_text')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('phone',), }), ) list_display = ['id', 'phone', 'email', 'is_active', 'is_staff', 'is_superuser', 'date_joined', 'last_login'] ordering = ('-id',) search_fields = ('email', 'phone') exclude = [] actions = ('send_push_notification', ) def send_push_notification(self, request, queryset): # Create some kind of form and logic..?? queryset.update(is_staff=False) # This is just to test -
Doesn't save form in django python foreignkey
There is a form with input text, which is not saved and throws a ValidationError, because there is no such value in the foreignkey model. The problem is that the check goes against pk, but the name. How to do it? (via select it is impossible, since this is entered and ajax gives him options). models class Orders(models.Model): service = models.ForeignKey('Service', null=True, blank=True, on_delete=models.PROTECT) class Service(models.Model): name = models.CharField(max_length=150, db_index=True, unique=True) def __str__(self): return self.name forms class SimpleOrderAddForm(forms.ModelForm): class Meta: model = Orders fields = ['service'] def clean_service(self): name = self.cleaned_data['service'] try: get_service = Service.objects.get(name=name) return get_service.pk except get_service.DoesNotExist: return name picture html form: UPD: a question in a different vein: how to change validation from pk to name field in input forms? UPD2: when entering the correct value into input, it outputs: Choose the correct option. Your option is not among the valid values. the error is that when entering, you must specify the pk field for the Service model and then the model is saved. And how to make the comparison by the name field take into account when writing the form? UPD3: already asked this question in a different vein here: here and here -
How to change the dbsqlite file ownership in gcp?
I have hosted my Django app to gcp. I am able to access the url aswell. But I am not able to login to the django admin panel. It gives me the following message. As per what I read it seems to be a permission issue. How can I fix this problem? NOTE: I dont want to use any cloud database. I want to stay with dbsqlite. Any help is appreciated. -
Django sending email with pdf
How to send an email with pdf or attachment and html using django i received no error but no email send from django.core.mail import EmailMessage send_mail=EmailMessage(email_template, [settings.EMAIL_HOST_USER, Email] , [Email]) send_mail.attach_file('static/pdf/ENROLLMENT-PROCEDURE-2021-.pdf') send_mail.send() print(send_mail) -
How to get count of model objects in django
Would anyone try to explain to me why I can't get a count of what is the query. I'd like to get count for all the books borrowed by every student def view_student(request): issues = Student.objects.all() for issue in issues: borroweds = Issue.objects.filter(borrower_id__student_id = issue.student_id).count() print(borroweds) return render(request, 'view_student.html', {'borroweds':borroweds}) And the tml code is this. {% for student in students %} <tr> <td>{{ forloop.counter }}</td> <td>{{ student.student_id }}</td> <td>{{ student.name }}</td> <td>{{ student.batch }}</td> <td>{{ student.semester }}</td> <td><a href="{% url 'all_borrowed' student.student_id %}"> {{ borroweds }}</a> </td> </tr> {% endfor %} This gives me a list of all students with books borrowed print(borroweds) while in the template {{ borroweds }} gives me 0's Am I calling it the wrong way of the code in the views???? -
centre the contents of a login page
I'm having trouble centring the contents of my login page Can you help me with the styling? I basically want the long input fields to be in the centre and be short like a typical login page. I had another question regarding bootstrap, I found a code snipped for some component for which I used version 3.4 but I am not able to use the other features of the higher versions for my other components..is there a way around that? the code is: {% extends "auctions/layout.html" %} {% block body %} <h2>Login</h2> {% if message %} <div>{{ message }}</div> {% endif %} <form action="{% url 'login' %}" method="post"> {% csrf_token %} <div class="form-group"> <input autofocus class="form-control" type="text" name="username" placeholder="Username"> </div> <div class="form-group"> <input class="form-control" type="password" name="password" placeholder="Password"> </div> <input class="btn btn-primary" type="submit" value="Login"> </form> Don't have an account? <a href="{% url 'register' %}">Register here.</a> {% endblock %} -
Updation of fileds in Django
I am looking to update the profile of my user in Django. However, after clicking the submit button on my webpage, the changes are not reflected into the database and backend. Below, are my models.py, views.py, urls.py, forms.py and html page files containing details of the same. How can I fix this issue. models.py: class User_profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="userprofile") Address = models.CharField(max_length=150) Skills = models.CharField(max_length=150) Work_Experiences = models.CharField(max_length = 150) Marital_Status = models.CharField(max_length = 150) Interests = models.CharField(max_length = 150) Edcucation = models.CharField(max_length = 150) category = models.ForeignKey("Category.Category",on_delete=models.CASCADE,default="demo") sub_category = models.ForeignKey("Category.SubCategory",on_delete=models.CASCADE,default="demo") phone_number = models.CharField(max_length=11) Aadhar_Card = models.FileField(upload_to="user_aadhar_card/",default="") def __str__(self): return str(self.user) views.py: def myaccount(request): instance1 = User_profile.objects.get(user=request.user) if request.method == "POST": user_form = UserForm(request.POST,instance=request.user) profile_form = UserProfileForm(request.POST,instance=instance1) if user_form.is_valid(): user_form.save() messages.success(request,('Your profile was successfully updated!')) elif profile_form.is_valid(): profile_form.save() messages.success(request,('Your profile was successfully updated!')) else: messages.error(request,('Unable to complete request')) return redirect('dashboard') user_form = UserForm(instance=request.user) profile_form = UserProfileForm(instance=instance1) return render(request=request, template_name="userprofile.html", context={"user":request.user, "user_form":user_form, "profile_form":profile_form }) forms.py: class UserForm(forms.ModelForm): class Meta: model = User fields = ["username", "email", "password","first_name","last_name"] class UserProfileForm(forms.ModelForm): class Meta: model = User_profile fields = '__all__' exclude = ['user'] def _init_(self, *args, **kwargs): super()._init_(*args, **kwargs) self.fields['first_name'].widget.attrs.update({'id':'fname','class': 'form-control'}) self.fields['last_name'].widget.attrs.update({'id':'lname','class': 'form-control'}) self.fields['email'].widget.attrs.update({'id':'email','class': 'form-control'}) self.fields['username'].widget.attrs.update({'id':'uname','class': 'form-control'}) self.fields['password'].widget.attrs.update({'id':'password','class': 'form-control'}) self.fields['Address'].widget.attrs.update({'id':'address','class': 'form-control'}) self.fields['Skills'].widget.attrs.update({'id':'skills','class': 'form-control'}) self.fields['Work_Experiences'].widget.attrs.update({'id':'we','class': … -
how to get data with product id in django
i am working on oms django i stuck at getting data of product with product id in order form how to get data of product in neworderForm with product id i added some models called new_product and new_orders i want data of new_product in new_orders field in django anyoe can help* models.py code i added some models called new_product and new_orders i want data of new_product in new_orders field in django anyoe can help class new_order(models.Model): Product_Name = models.CharField(max_length=250, null=True) Product_Id = models.CharField(max_length=10, null=True) Free_Size = models.IntegerField(default=0, null=True) S = models.IntegerField(default=0, null=True) M = models.IntegerField(default=0, null=True) X = models.IntegerField(default=0, null=True) XL = models.IntegerField(default=0, null=True) L = models.IntegerField(default=0, null=True) # customer details Name = models.CharField(max_length=250, null=True) Address = models.TextField(null=True) Pincode = models.IntegerField(null=True) Mobile = models.IntegerField(null=True) Alt_Mobile = models.IntegerField(null=True) Date_Of_Order = models.DateField(auto_now=True) Order_Type = ( ("Prepaid", "Prepaid"), ("C.O.D", "C.O.D"), ) Order_Type = models.CharField(max_length=30, null=True, choices=Order_Type) Order_Id = models.CharField( max_length=5, blank=True, null=True, default=random_string ) Total_Amount = models.PositiveIntegerField(null=True, blank=True) Track = models.CharField(max_length=50, null=True) Courier_Partner = models.CharField(max_length=50, null=True) Status = ( ("Pending", "Pending"), ("Dispatched", "Dispatched"), ("Cancelled", "Cancelled"), ) Status = models.CharField(max_length=50, null=True, choices=Status, default="Pending") def __str__(self): views.py code from django.shortcuts import render, redirect, HttpResponseRedirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from … -
How to solve Session matching query does not exist in Django sessions
I added a one user instance functionality to my web app, where a user is logged-out whenever they login in another browser. It worked well, until I updated the logged in user information. whenever I try loggin in- my app throws a DoesNotExist error; stating that Session matching query does not exist. and does not login or even create a new user. How do I get over this error, I will attach codes if need be. -
I want to post a list of JSON values to a model's field in Django
I want to post a movie into the collection's movie field( list of movies). I define the model as class Movie(models.Model): # collection = models.ForeignKey(Collection, on_delete = models.CASCADE) #, related_name='reviews' title = models.CharField(max_length=200) description = models.CharField(max_length=200) genres = models.CharField(max_length=200) uuid = models.CharField(max_length=200) def __str__(self): return self.title class Collection(models.Model): title = models.CharField(max_length=200) uuid = models.CharField(max_length=200, primary_key = True) description = models.CharField(max_length=200) movie = models.ForeignKey(Movie, on_delete = models.CASCADE) def __str__(self): return self.title this is how i am using the viewset class CollectionViewSet(viewsets.ModelViewSet): queryset = models.Collection.objects.all() serializer_class = serializers.CollectionSerializer but i am not able to enter values for the movie field enter image description here -
Django migration problem with long traceback
I have a strange and frustrating problem with migration that I can't figure out. I'm not experienced in debugging. The steps before python3 manage.py makemigrations was OK. This is the log I kept. Could you please help me? ruszakmiklos@Ruszak-MacBook-Pro firm % python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, stressz Running migrations: Applying stressz.0050_auto_20210504_0757...Traceback (most recent call last): File "/Library/Python/3.8/site-packages/django/db/models/fields/__init__.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Python/3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Python/3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Python/3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Library/Python/3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/Library/Python/3.8/site-packages/django/core/management/commands/migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "/Library/Python/3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Library/Python/3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Library/Python/3.8/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/Library/Python/3.8/site-packages/django/db/migrations/migration.py", line 124, … -
please solve this DLL load failed
Process Process-1: Traceback (most recent call last): File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import * File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "imp.py", line 243, in load_module File "imp.py", line 343, in load_dynamic ImportError: DLL load failed: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "multiprocessing\process.py", line 258, in bootstrap File "multiprocessing\process.py", line 93, in run File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\DeepFaceLab\core\leras\device.py", line 101, in get_tf_devices_proc import tensorflow File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow_init.py", line 24, in from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python_init.py", line 49, in from tensorflow.python import pywrap_tensorflow File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in raise ImportError(msg) ImportError: Traceback (most recent call last): File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import * File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "C:\DeepFaceLab_NVIDIA_up_to_RTX2080Ti_internal\python-3.6.8\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "imp.py", line 243, in load_module File "imp.py", line 343, in load_dynamic ImportError: DLL load failed: The specified module could not be found. Failed to load the native TensorFlow runtime. See https://www.tensorflow.org/install/errors for some common reasons and solutions. Include the entire stack trace above … -
Django: AttributeError: 'int' object has no attribute 'cafe_name'
Hey I am trying to return a set of objects that belong to "friends" the logged in user follows and are within a specific geographic space. But I get this error: AttributeError: 'int' object has no attribute 'cafe_name' views.py def get_friends(request): template_name = 'testingland/electra.html' neLat = request.GET.get('neLat', None) neLng = request.GET.get('neLng', None) swLat = request.GET.get('swLat', None) swLng = request.GET.get('swLng', None) ne = (neLat, neLng) sw = (swLat, swLng) xmin = float(sw[1]) ymin = float(sw[0]) xmax = float(ne[1]) ymax = float(ne[0]) bbox = (xmin, ymin, xmax, ymax) geom = Polygon.from_bbox(bbox) friends = UserConnections.objects.filter( follower=request.user ).values_list('followed__pk', flat=True) mapCafes.objects.filter( geolocation__coveredby=geom, uservenue__user_list__user__pk__in=friends ).distinct() return JsonResponse([ [cafe.cafe_name, cafe.cafe_address, cafe.geolocation.y, cafe.geolocation.x] for cafe in friends ], safe=False) Models class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation = models.PointField(geography=True, blank=True, null=True) venue_type = models.CharField(max_length=200) source = models.CharField(max_length=200) description = models.CharField(max_length=1000) image_embed = models.CharField(max_length=10000) class Meta: managed = False db_table = 'a_cafes' def __str__(self): return self.cafe_name [...] class UserConnections(models.Model): follower = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) followed = models.ForeignKey(User, related_name="followers", on_delete=models.CASCADE) Traceback: Internal Server Error: /electra/get_friends/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, … -
SSO with roles and permissions
We have projects that interacts with regular users (general app) and company users (companies app). Therefore, in our projects, generally, we have two types of Users: Regular - authenticates with phone_number as identifier. Regular users are any Users that can do common staff in our system. Staff - authenticates with email as identifier. Staff Users belong to some company and they have some roles. So, we built SSO app, that keeps all users, because there are apps that need about any user and having separate app that handles users in one place was for us better choice. However, there are troubles with our idea... The company app has its SUPERUSER that can create some company, company branch and director of that company and etc. We create company-apps superuser in our SSO app and give it COMPANY APP SUPERUSER role. SSO app does not hold the specific roles of company for users, we don't want it. That is the responsibility of company app. So, there is the problem when director of company wants to invite (create) employee, he/she requests company-app, which in the box calls SSO app endpoint to create user. Inside of SSO app we don't know who is requesting … -
showing same output for different list views
i am making a html page which shows list of companies follow by its product. i used 2 models(company, product) for 1st html and it worked but when i tried creating the same 2 models for different type it shows the output of 1st model my models.py: class HydraulicCompany(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class HydraulicProduct(models.Model): company = models.ForeignKey(HydraulicCompany, on_delete=models.CASCADE, related_name='company') name = models.CharField(max_length=200) def __str__(self): return self.name class Industrial_Company(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Industrial_Product(models.Model): company = models.ForeignKey(Industrial_Company, on_delete=models.CASCADE, related_name='ind_company') name = models.CharField(max_length=200) def __str__(self): return self.name my views.py: class Hydraulic(ListView): template_name = 'hydraulics.HTML' context_object_name = 'hydraulic' queryset = models.HydraulicProduct.objects.select_related('company').order_by('company') class igo(ListView): model = Industrial_Product template_name = 'industialgear.html' context_object_name = 'igo' queryset = models.HydraulicProduct.objects.select_related('company').order_by('company') my html: {% extends "base.HTML" %} {% load static %} {% block title %}industrial gear oil{% endblock %} {% block extra_head %} <link rel="stylesheet" href="{% static 'css/data.css' %}"> {% endblock %} {% block content %} <br><br><br><br><br><br> {% for item in igo %} {% ifchanged item.company %} <h1> {{ item.company }} </h1> {% endifchanged %} <div> {{ item }} </div> {% endfor %} {% endblock %} THANKS! -
How to Sum same product's product _Volume value at with ORM-Query
I need to sum all different product's "product_volume" in one for this my model is class Product(BaseModel, models.Model): name = models.CharField(max_length=256) category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL, related_name='product_category') description = models.CharField(max_length=1000) hs_code = models.CharField(max_length=256, unique=True) photo = models.ImageField(upload_to='media/product/%Y/%M/', null=True, blank=True) production_unit = models.ForeignKey(MeasurementUnit, related_name='product_unit', null=True, blank=True, on_delete=models.SET_NULL) class Production(BaseModel, models.Model): product = models.ForeignKey(Product, related_name='production_product', on_delete=models.CASCADE) district = models.ForeignKey(DistrictLevel, related_name='production_district', on_delete=models.CASCADE) production_volume = models.FloatField() production_year = models.ForeignKey(FiscalYear, related_name='production_year', null=True, blank=True, on_delete=models.SET_NULL) seasons = models.ManyToManyField(Season) Here, I'm trying to do is that, sum of the product_volume of product at one like, product1, product_volume=20 product2, product_volume = 40 product3, product_volume = 60 in my table i need to show product1, product_volume = 80 product2, product_volume = 40 Here is my table I'm getting result by using for loop but, is there any better solution for this using ORM. sorry for my English, I'm little weak in English -
Using Django Session ID from cookies to authenticate Vue app
I'm trying to use the session id generated when logging in a users on a Django site, to then automatically login a user on a Vue site. Both the Vue site and Django site run on different servers, but Vue uses the Django site as an api. Is this safe and recommended and how can this be achieved? Would if be safer to use the session id and then generate a token for the vue site? -
How to pass model instance to serializer?
I have a view: def create(self, request): serializer = OrderPostSerializer(data=request.data) if serializer.is_valid(): instance = serializer.save() serializer = OrderDetailsSerializer(instance) return AppResponse.success( "Order created successfully.", serializer.data, http_success_code=status.HTTP_201_CREATED, ) return AppResponse.error( serializer.errors, None, http_error_code=status.HTTP_422_UNPROCESSABLE_ENTITY, ) Serializers: class CustomerDetailsPostSerializer(serializers.Serializer): id = serializers.IntegerField( required=False, error_messages={"invalid": "id should be a valid integer."} ) name = serializers.CharField(required=False, max_length=80) email = serializers.EmailField(required=False) mobile = serializers.CharField( required=False, max_length=15, error_messages={ "max_length": "mobile field should not exceed more than 15 characters." }, ) company_name = serializers.CharField( required=False, max_length=255, allow_null=True, error_messages={ "max_length": "company name field should not exceed more than 255 characters." }, ) def validate_email(self, value): customer = Customer.objects if self.instance: customer = customer.exclude(pk=self.instance.pk) if customer.filter(email__iexact=value): raise serializers.ValidationError( "Customer with this email already exists." ) return value def validate_company(self, value): customer = Customer.objects if self.instance: customer = customer.exclude(pk=self.instance.pk) if customer.filter(company_name__iexact=value): raise serializers.ValidationError( "Customer with this company name already exists." ) return value def validate_mobile(self, value): if validate_phone_number(value) is None: customer = Customer.objects if self.instance: customer = customer.exclude(pk=self.instance.pk) if customer.filter(mobile__iexact=value): raise serializers.ValidationError( "Customer with this phone number already exists." ) return value def validate(self, data): data = dict(data) if ("id" not in data.keys() or not data.get("id")) and ( ("name" not in data.keys() or not data.get("name")) or ("email" not in data.keys() or not … -
CustomUser matching query does not exist. ERROR( DJANGO)
when i save the form in template. The error says: CustomUser matching query does not exist. Line number 104: teacher=CustomUser.objects.get(id=teachers_id) Model.py class Subjects(models.Model): id=models.AutoField(primary_key=True) subject_name=models.CharField(max_length=255) course_id=models.ForeignKey(Courses,on_delete=models.CASCADE,default=1) teachers_id=models.ForeignKey(CustomUser,on_delete=models.CASCADE) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() views.py def add_subject_save(request): if request.method!="POST": return HttpResponse("<h2>Method Not Allowed</h2>") else: subject_name=request.POST.get("subject_name") course_id=request.POST.get("course") course=Courses.objects.get(id=course_id) teachers_id=request.POST.get("teacher") teacher=CustomUser.objects.get(id=teachers_id) try: subject=Subjects(subject_name=subject_name,course_id=course,teachers_id=teacher) subject.save() messages.success(request,"Successfully Added Subject") return HttpResponseRedirect("add_subject") except: messages.error(request,"Failed to Add Subject") return HttpResponseRedirec("add_subject") I dont know where this error is coming from. -
Failed to send email using gmail as client (django, graphene)
I am trying to set up email client to be gmail in my django project. When i register a user it gives me the following error: { "data": { "register": { "success": false, "errors": { "nonFieldErrors": [ { "message": "Failed to send email.", "code": "email_fail" } ] }, "token": null } } } My settings.py looks like this EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = "youremail@gmail.com" EMAIL_HOST_PASSWORD = "yourpassword" I have already enabled 2 step authentication with google. My AuthMutation looks like this: class AuthMutation(graphene.ObjectType): register = mutations.Register.Field() verify_account = mutations.VerifyAccount.Field() login = mutations.ObtainJSONWebToken.Field() update_account = mutations.UpdateAccount.Field() resend_activation_email = mutations.ResendActivationEmail.Field() send_password_reset_email = mutations.SendPasswordResetEmail.Field() password_reset = mutations.PasswordReset.Field() password_change = mutations.PasswordChange.Field() Thanks in advance to the amazing stackoverflow community -
TypeError at /myaccount/ myaccount() missing 1 required positional argument: 'id'
I am looking to update the profile of my user in Django. However, I am getting a strange errorTypeError at /myaccount/ myaccount() missing 1 required positional argument: 'id' as Error when I open the webpage. Below, are my models.py, views.py, urls.py and forms.py files containing details of the same. How can I fix this issue. models.py: class User_profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="userprofile") Address = models.CharField(max_length=150) Skills = models.CharField(max_length=150) Work_Experiences = models.CharField(max_length = 150) Marital_Status = models.CharField(max_length = 150) Interests = models.CharField(max_length = 150) Edcucation = models.CharField(max_length = 150) category = models.ForeignKey("Category.Category",on_delete=models.CASCADE,default="demo") sub_category = models.ForeignKey("Category.SubCategory",on_delete=models.CASCADE,default="demo") phone_number = models.CharField(max_length=11) Aadhar_Card = models.FileField(upload_to="user_aadhar_card/",default="") def __str__(self): return str(self.user) forms.py: class UserForm(forms.ModelForm): class Meta: model = User fields = ["username", "email", "password","first_name","last_name"] class UserProfileForm(forms.ModelForm): class Meta: model = User_profile fields = '__all__' exclude = ['user'] def _init_(self, *args, **kwargs): super()._init_(*args, **kwargs) self.fields['first_name'].widget.attrs.update({'id':'fname','class': 'form-control'}) self.fields['last_name'].widget.attrs.update({'id':'lname','class': 'form-control'}) self.fields['email'].widget.attrs.update({'id':'email','class': 'form-control'}) self.fields['username'].widget.attrs.update({'id':'uname','class': 'form-control'}) self.fields['password'].widget.attrs.update({'id':'password','class': 'form-control'}) self.fields['Address'].widget.attrs.update({'id':'address','class': 'form-control'}) self.fields['Skills'].widget.attrs.update({'id':'skills','class': 'form-control'}) self.fields['Work_Experiences'].widget.attrs.update({'id':'we','class': 'form-control'}) self.fields['Marital_Status'].widget.attrs.update({'id':'ms','class': 'form-control'}) self.fields['Interests'].widget.attrs.update({'id':'inte','class': 'form-control'}) self.fields['Edcucation'].widget.attrs.update({'id':'edu','class': 'form-control'}) self.fields['category'].widget.attrs.update({'id':'category','class': 'form-control'}) self.fields['sub_category'].widget.attrs.update({'id':'subcategory','class': 'form-control'}) self.fields['phone_number'].widget.attrs.update({'id':'phonenumber','class': 'form-control'}) self.fields['Aadhar_Card'].widget.attrs.update({'id':'aadhar','class': 'form-control'}) views.py: def myaccount(request,id): instance1 = User_profile.objects.get(id=id) if request.method == "POST": user_form = UserForm(request.POST,instance=request.user) profile_form = UserProfileForm(request.POST,instance1=instance1) if user_form.is_valid(): user_form.save() messages.success(request,('Your profile was successfully updated!')) elif profile_form.is_valid(): profile_form.save() messages.success(request,('Your profile was successfully updated!')) else: messages.error(request,('Unable to … -
How to overwrite data from a model that is linked to the main model through a o-t-m relationship?
I have three models that are related to each other, namely: models.py class Shop(models.Model): number = models.PositiveSmallIntegerField() name = models.CharField(db_index=True) city = models.ForeignKey(ShopCity, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(db_index=True) price = models.DecimalField(max_digits=10, decimal_places=2) class ProductQuantity(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) shop = models.ForeignKey(Shop, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField(default=None) In the admin panel they are linked in this way: admin.py class ProductQuantityInline(admin.TabularInline): model = ProductQuantity extra = 0 @admin.register(Product) class ProductAdmin(ImportExportActionModelAdmin): fields = ['name', 'price'] list_display = ['name', 'price'] inlines = [ProductQuantityInline] There is a need to overwrite data with REST API serializers.py class QuantitySerializer(serializers.ModelSerializer): class Meta: model = ProductQuantity fields = ('shop', 'quantity') class ProductSerializer(serializers.ModelSerializer): productquantity = serializers.SerializerMethodField(read_only=False) class Meta: model = Product fields = ('name', 'price', 'productquantity') def get_productquantity(self, obj): return [QuantitySerializer(s).data for s in obj.productquantity_set.all()] And finally my handler for REST API: views.py @api_view(['GET', 'PATCH', 'PUT', 'DELETE']) def api_product_detail(request, pk): product = Product.objects.get(pk=pk) if request.method == 'GET': serializer = ProductSerializer(product) return Response(serializer.data) elif request.method == 'PUT' or request.method == 'PATCH': serializer = ProductSerializer(product, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': product.delete() return Response(status=status.HTTP_204_NO_CONTENT) As a result, data such as the name and price are overwritten, and the productquantity is not overwritten. What am I … -
How is front end generated when creating web applications using python Django? [closed]
First off, bare with me if my question seems odd as i have no experience in developing web applications. I know Django is used for the backend and the logic of a web application i.e website. But how is the front end and HTML, CSS, JS and all those UI stuff created when working with Django? Does the programmer separately write the UI with those mark up languages or does the Django framework create web pages automatically? -
how to display data from json response django
i want to add a function to my project to return json data and display it in the main template (base.html) using ajax , this is my function @login_required def alerts(request): if request.is_ajax: sender = Post.objects.filter(active=False) return JsonResponse(sender) my models.py class Post(models.Model): title = models.CharField(max_length=50) active = models.BooleanField(default=True) #others and this is my base.html $(document).ready(function(){ $('.btn-click').click(function(){ $.ajax({ url:'/ajax/alerts/', type:'get', success:function(data){ document.getElementById('alerts').append(data.title) } }) }) }) <div x-data="{ dropdownOpen: false }"> <button @click="dropdownOpen = !dropdownOpen" class="relative z-10 block rounded-md text-black p-2 focus:outline-none btn-click"> <i class="fas fa-bell"></i> <!-- <img src="icon/bell.svg" class="w-5" alt=""> --> </button> <div x-show="dropdownOpen" class="absolute left-2 top-10 text-right py-2 w-59 grayBG rounded-md shadow-xl z-20 h-48 overflow-y-scroll "> <p class="whiteCOLOR text-center border-b border-red-500 p-2" id="alerts"></p> </div> </div> and my urls.py path('ajax/alerts', alerts,name='alerts'), but it shows nothing !? i want to display those posts which not accepted in an alert , thank you ..