Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use same serializer class but with different action in a view in Django rest framework
I have a modelset view in which different customs functions are defined based on the requirement. I have to write another get function in which I want to use the same serializer class. But the field which I have defined in the serializer class in pkfield but for the get function, I want it as a stringfield rather than pk field. How to achieve that?? Also, I have defined depth=1, which is also not working. class Class(TimeStampAbstractModel): teacher = models.ForeignKey( Teacher, on_delete=models.CASCADE, null=True, related_name="online_class", ) subject = models.ForeignKey( Subject, on_delete=models.SET_NULL, null= True, related_name= "online_class", ) students_in_class = models.ManyToManyField(Student, related_name="online_class") My view: class ClassView(viewsets.ModelViewSet): queryset = Class.objects.all() serializer_class = ClassSerializer serializer_action_classes = { 'add_remove_students': AddStudentstoClassSerializer, 'get_all_students_of_a_class': AddStudentstoClassSerializer, } def get_serializer_class(self): """ returns a serializer class based on the action that has been defined. """ try: return self.serializer_action_classes[self.action] except (KeyError, AttributeError): return super(ClassView, self).get_serializer_class() def add_remove_students(self, request, *args, **kwargs): """ serializer class used is AddStudentstoClassSerializer """ def get_all_students_of_a_class(self,request,pk=None): """ for this I function too, I want to use the same AddStudentstoClassSerializer class but there is a problem. The field students_in_class is already defined as pkfield, whereas I want to use it as a stringfields in the response of this function """" My … -
Django combining tables
I have main table name Location class Location(models.Model): id = UUIDField(primary_key=True, default= uuid.uuid4, editable=False) participant_id = ForeignKey('Participant', on_delete=CASCADE, related_name="locations") country_id = ForeignKey(Country, on_delete=CASCADE, related_name="country") and this is the sterilizer class LoactionSerializer(serializers.ModelSerializer): country_id = RelatedFieldAlternative(queryset = Country.objects.all(), serializer=CountrySerializer) class Meta: model = Location fields = "__all__" Now I have 6 models that each one of them contain location id (Forging key) and different properties example class LocationCanada(models.Model): id = UUIDField(primary_key=True, default= uuid.uuid4, editable=False) province = CharField(max_length=255) location_id = ForeignKey(Location, on_delete=CASCADE) class LocationSwitzerland(models.Model): id = UUIDField(primary_key=True, default= uuid.uuid4, editable=False) canton = CharField(max_length=255) assumptio = CharField(max_length=255) resident = BooleanField(default=False) location_id = ForeignKey(Location, on_delete=CASCADE) How do I mange to Combine all the related model to the location model -
Django OneToOneField looses relation by returning None after save()
I'm a bit confused by a Django behavior and I couldn't find this in any related questions or the official documentation. For example, in the code below: from django.db import models class Category(models.Model): name = models.CharField(max_length=255) class Post(models.Model): title = models.CharField(max_length=255) category = models.OneToOneField(Category) post = Post(title='My Title') post.category = Category(name='My Category') post.category.save() # Here: post.category => Category(pk=1, name="My Category") 🎉 post.save() # Here: post.category => None 😭 I create a Post object. I then create a category on it that I save prior to saving the post. But when I call the post.save() method, the post.category is cleared and set to None. Why is that ? I've fixed it by doing the following which introduces an additional variable: post = Post(title='My Title') category = Category(name='My Category') category.save() post.category = category # Here: post.category => Category(pk=1, name="My Category") 🎉 post.save() # Here: post.category => Category(pk=1, name="My Category") 🎉 Why does introducing an additional variable change the behavior of the save() method ? -
Django Rest Framework - Jwt - Multiple types of user
I am learning django rest framework and I started Linkedin clone project I am confused what to use / how to implement I have multiple user types : Company, Worker class User(AbstractUser): class Types(models.TextChoices): WORKER = "WORKER", "Worker" COMPANY = "COMPANY", "Company" type = models.CharField("Type", max_length=50, choices=Types.choices, default=Types.WORKER) class CompanyManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(type=User.Types.COMPANY) class WorkerManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(type=User.Types.WORKER) class Worker(User): objects = WorkerManager() class Meta: proxy = True def save(self, *args, **kwargs): if not self.pk: self.type = User.Types.WORKER return super().save(*args, **kwargs) class CompanyProfile(models.Model): user = models.OneToOneField( User, related_name="profile", on_delete=models.CASCADE) year = models.IntegerField() class Company(User): objects = CompanyManager() @property def profile(self): return self.profile class Meta: proxy = True def save(self, *args, **kwargs): if not self.pk: self.type = User.Types.COMPANY return super().save(*args, **kwargs) And I want to use JWT I have an experience with djoser Jwt and react and now i am bit confused how to make it here Ps: Thanks for your time! -
how to host 2 django project using the same Apache
I am new to XAMPP and i want to host 2 of my django project using APACHE, however, only one of my project is able to work, when I add a second project, the second project won't work and the server will only run based on the first project even though I set 2 port number, 1 is 8000 and 1 is 8080. httpd.conf AcceptFilter http none AcceptFilter https none # AJP13 Proxy <IfModule mod_proxy.c> <IfModule mod_proxy_ajp.c> Include "conf/extra/httpd-ajp.conf" </IfModule> </IfModule> LoadFile "c:/users/scs/appdata/local/programs/python/python38/python38.dll" LoadModule wsgi_module "c:/users/scs/appdata/local/programs/python/python38/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win_amd64.pyd" WSGIPythonHome "c:/users/scs/appdata/local/programs/python/python38/" WSGIPythonPath C:\Users\SCS\PycharmProjects\trackMCO\venv\Lib\site-packages <IfModule wsgi_module> ServerName http://127.0.0.1:8000 WSGIScriptAlias / C:\Users\SCS\PycharmProjects\trackMCO\tracker\tracker\wsgi.py WSGIPythonPath C:\Users\SCS\PycharmProjects\trackMCO <Directory C:\Users\SCS\PycharmProjects\trackMCO > Allow from all </Directory> Alias /static/ C:/Users/SCS/PycharmProjects/trackMCO/tracker/mcoTrack/static/ <Directory C:/Users/SCS/PycharmProjects/trackMCO/tracker/mcoTrack/static/> Allow from all Require all granted </Directory> </IfModule> LoadFile "c:/users/scs/appdata/local/programs/python/python38/python38.dll" LoadModule wsgi_module "c:/users/scs/appdata/local/programs/python/python38/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win_amd64.pyd" WSGIPythonHome "c:/users/scs/appdata/local/programs/python/python38/" WSGIPythonPath C:\Users\SCS\PycharmProjects\Role_based_login_system-master\venv\Lib\site-packages <IfModule wsgi_module> ServerName http://127.0.0.1:8080 WSGIScriptAlias / C:\Users\SCS\PycharmProjects\Role_based_login_system-master\Role_based_login_system\wsgi.py WSGIPythonPath C:\Users\SCS\PycharmProjects\trackMCO <Directory C:\Users\SCS\PycharmProjects\Role_based_login_system-master> Allow from all </Directory> Alias /static/ C:/Users/SCS/PycharmProjects/Role_based_login_system-master/static <Directory C:/Users/SCS/PycharmProjects/Role_based_login_system-master/static> Allow from all Require all granted </Directory> </IfModule> It will still run the server, but when i enter 127.0.0.1:8000 and 127.0.0.1:8080, it will just load into my first project, how do I fix this issue and host 2 project successfully. -
django reverse admin disable delete for inline
This is my ModelAdmin class ComputerAdmin(ReverseModelAdmin): list_display = ('employee', 'ip', 'mac', 'name', 'hardware') list_filter = ('employee__branch', ) inline_type = 'tabular' inline_reverse = ['hardware', ] show_full_result_count = False This is how it shows when adding a new computer As you can see I don't want to have delete column and delete icon, because I have a foreign key so only one element is allowed. How can I do that ? Does django-reverse-admin have anything like has_delete_permisison for inlines only and not the whole ModelAdmin ? I have already searched in documentation with no results, which is why I am posting here. Thanks -
How to find duplicate and deactivate duplicates for user attributes
Suppose we have a model in django defined as follows: class DateClass: user_id = models.IntegerField(...) sp_date = models.DateField(...) is_active = models.BooleanField(...) ... I follow insert policy here, i.e, for a specific user there will be only one specific active date. That means, there will be only one active row for user=1 at date table for sp_date values 27/10/2021, 28/10/2021 and so one. There shouldn't be two active rows for 27/10/2021 for user=1, but for other users have there rows for 27/10/2021. Whenever a date has to be updated, I deactivate (is_active=False) the previous row and add a new row for specific date. I want to find duplicate active dates for each users in one single query, and then deactivate (set is_active=False) all the duplicate values except the last row (The row which was last inserted). Two rows will be duplicate if the values of user_id and sp_date are equal and both have is_active=True. I know how to find duplicates for a specific column which is fairly easy. But I can't think of something which can do the above task elegantly. I can only think of following approach: for user in users: dates = DateClass(user_id=user.id, is_active=True) for date in dates: days … -
In Django, remove options in a choice-field dropdown based on the valuse selcted in other field in a model
I'm new to Django and any help is appreciated, How can I restrict the choice option in one field based on a previous field. For example, if I select 'dog' for animal, I want to remove 'chocolate' from the FOOD_CHOICE. Thank you!!! ANIMAL_CHOICE = ( ('a','cat'), ('b','dog'), ('c','fish'), ) FOOD_CHOICE = ( ('a', 'chocolate'), ('b', 'kittySnack'), ('c', 'steak'), ) class Animal(models.Model): animal = models.CharField(max_length=1, choices= ANIMAL_CHOICE) food = models.CharField(max_length=1, choices= FOOD_CHOICE) -
Flatpicker defaultHours and defaultMinute not working
I am trying to change the default time when a date is selected in Flatpicker, but every time I select a date, the time is always 12:00 or another value if the time was already there when retrieved by Django. I cannot find a way to set the current time upon selection of the date. $('.datepicker').flatpickr({ dateFormat: "d-m-Y H:i:S", enableTime: true, // enableSeconds: true, allowInput: true, time_24hr: true, minuteIncrement: 1, defaultHour: new Date().getHours(), defaultMinute: new Date().getMinutes(), }); -
How to add username and password for xml format with python
def test(login,password): data="""<?xml version="1.0"?> <soap-env> <soap-env:Body> <Auth> <Login>login</Login><password>password</password> </Auth> <Ping> </Ping> </soap-env:Body> </soap-env:Envelope>""" return data i can't add login and password when i use '+login+' and i can't do format string like this " " -
I have a problem with class-based views create a view
I need help or guidance on where to find a solution. The following code does not run properly and returns an error. class TaskCreate(CreateView): model = Task fields = '__all__' success_url = reverse_lazy('tasklist') template_name = 'create.html' class_form = 'create' The create.html file is in the main templates folder where the static folder is. The code will work when I change the name from create.html to task_form.html and move it to the application folder.But I don't want to do this Question. What do I have to do for the above code to work for me? Thank you for every reply. -
Fullcalendar error rendering Unexpected token
Going through a new django 3 project, newbie on that, so sorry me if my code is not so clean. The problem is when i try to render calendar... without events it loads nicely, but when loading'em it stops rendering the whole calendar. Console throes an Uncaught SyntaxError: Unexpected token '{', but i can´t find the problem, neither is a comma into my loop. Any help welcome. My calendar script: <script> document.addEventListener('DOMContentLoaded',function(){ var cUI= document.getElementById('calendar'); var c= new FullCalendar.Calendar(cUI,{ themeSystem: 'bootstrap', headerToolbar:{ left:'prev,next today', center:'title', right:'', }, events:{ {% for v in vacation %} { title:"{{ v.reason }}: {{ v.starth }}-{{ v.endh }}", start: "{{ v.start | date:'Y-m-d' }}", end: "{{ v.end | date:'Y-m-d' }}", }, {% endfor %} }, }); c.render(); c.setOption('locale','es'); }); </script> Thank you -
django ORM aggregate for count
**i want to get count of scheduled test ride and completed test ride of user** obj= TestRide.objects.filter(feature=feature_obj).aggregate( scheduled_count=( Count('status', filter=Q(status='Scheduled')) ), completed_count=( Count('status', filter=Q(status='Completed')) ), ) i am getting same count value in scheduled_count and completed_count i think my filter is not working can anyone help me out thanks -
Bulk user import in Django
I like to bulk import users to my original User model. I don't use AbstractUser or AbstractBaseUser and I don't like to because my site is working and I don't want to abuse my schema. I'am using the original User model where I add the users (no user registration allowed) and I store the extra filed in my Profile model with a OneToOne relation. I'm not so experienced so I tried to use code snippets that I found but I am still not able to achieve my goal. If I try to use import-export module in my admin panel it works with other models but not with the User model. Tablib or other solutions would be also interesting to me. models.py (I'm using the original User model that sends a signal to Profile model when a user is created) class Profile(models.Model): def __str__(self): return str(self.user) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) projekt = models.ForeignKey(Projekt, on_delete=models.CASCADE, default=1) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'last_name', 'first_name', 'password1', 'password2'] admin.py from django.contrib.auth.models import … -
How to make multiple tables inside one Model in Django?
I have made a model class for Stocks database which has Date Open High Low and Close fields in Django. I uploaded one CSV file into that which is working fine. But now I want to upload multiple stock files data into this same model. How to do it ? -
How can set withdrawal limit? Django, Python
i have a project where users deposit, play game, and withdraw. I want to set withdraw limit for specific user groups. this is my User Model: class User(AbstractBaseUser, PermissionsMixin): class PlatformStatus(models.TextChoices): NOT_REQUESTED = 'not requested' REQUESTED = 'requested' PENDING = 'pending' CREATED = 'created' class Status(models.TextChoices): PENDING = 'pending' ACTIVE = 'active' DEACTIVATED = 'deactivated' BLACK_LIST = 'blacklist' class UserRole(models.TextChoices): REGULAR = 'regular' SILVER = 'silver' GOLD = 'gold' PLATINUM = 'platinum' VIP = 'vip' class ReadStatus(models.TextChoices): READ = 'read' UNREAD = 'unread' ACTIVE = 'active' """" Custom user model that uses email instead of username """ id = models.AutoField(primary_key=True, editable=False) email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, unique=True, null=True, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) status = models.CharField(max_length=250, choices=Status.choices, default="pending") role = models.CharField(max_length=250, choices=UserRole.choices, default='regular') created_at = models.DateTimeField(auto_now_add=True, null=True) first_name = models.CharField(max_length=150, unique=False, null=True) last_name = models.CharField(max_length=150, unique=False, null=True) phone = models.CharField(max_length=20, unique=True, null=True, blank=False) user_ip = models.CharField(max_length=120, null=True, blank=False) is_phone_verified = models.BooleanField(default=False) is_id_verified = models.BooleanField(default=False) id_number = models.CharField(max_length=250, unique=True, null=True) id_issued_state = models.CharField(max_length=250, null=True) id_self = CompressedImageField(upload_to="user-id/self/", null=True, default=None, max_length=500, quality=50, validators=[validate_file]) id_front = CompressedImageField(upload_to="user-id/front/", null=True, default=None, max_length=500, quality=50, validators=[validate_file]) id_back = CompressedImageField(upload_to="user-id/back/", null=True, default=None, max_length=500, quality=50, validators=[validate_file]) btc_address = models.CharField(max_length=500, unique=True, null=True, blank=True) referral_code = models.CharField(max_length=10, … -
Django not saving the data to database
I have a very basic knowledge of Django and having come across a problem, it has rendered me totally confused. I am trying to construct a 3D plotter. Everything is rendering properly but when I click Submit, it never saves to the database except the specified default value that I have provided. My models.py from django.db import models class Value(models.Model): eq_input = models.CharField(max_length=20, default='x**2 + y**2') color = models.CharField(max_length=20, default='Magma') My forms.py from django import forms from .models import Value class ViewForm(forms.ModelForm): Equation = forms.CharField(max_length=20, label='Equation') Color = forms.CharField(max_length=20,label='Color') class Meta: model = Value fields = { 'Equation', 'Color' } My views.py from django.shortcuts import render from django.http import HttpResponse from .models import Value from .forms import ViewForm def home_view(request): if request.method == "POST": form = ViewForm(request.POST) if form.is_valid(): form.save() else: form = ViewForm() context = { 'form': form } return render(request, "home.html", context) My home.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>3D Graph Plotter</title> </head> <body> <center><h1>This is a 3D plotter</h1></center> <center> <form action="." method="POST">{% csrf_token %} {{ form.as_p }} <input type="submit" name="Save" /> </form> </center> </body> </html> and my urls.py from django.contrib import admin from django.urls import path, include from equation.views import eq, home_view urlpatterns = [ path('admin/', … -
How to get distinct data in Django views queryset?
I have the following records in table I want to get all sender_id where receiver_id is 15 and all receiver_id where sender_id is 15. How can I define queryset. I have tried following class ContactListAPI(GenericAPIView, ListModelMixin ): def get_queryset(self): return Messages.objects.filter(Q(sender=15) | Q(receiver=15)) serializer_class = ContactsSerializer permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.list(request, *args, **kwargs) but this is giving me all the records but I want Distinct values only. simply I want to get all the receiver id's where sender is 15 and all sender ids where receiver is 15. here my expected output is 11,17. tell me how can I get these by defining query set. -
Toggle Switch Not working in all rows in Django
I am intending to implement activating and deactivating a user by changing the value of is_active in the database which is a boolean to True or false depending on the the status of the Toggle switch.I have implemented this but the problem is that the toggle switch only works in on raw only the rest doesnt work looped output from database <main class="page-content"> <div class="path"> <h5>Administration <i class="fa fa-chevron-right"></i> Users <i class="fa fa-chevron-right"></i> All user</h5> </div> {% for message in messages %} {% if 'success' in message.tags %} <script> swal("Success", "{{ message }}", "success"); </script> {% elif 'error' in message.tags %} <script> swal("Error!", "{{ message }}", "error"); </script> {% endif %} {% endfor %} <hr/> <div class="container-fluid pl-0 pr-2"> <table id="myTable" class="table table-bordered table-hover table-sm"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Role</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> {% if all_users %} {% for user in all_users %} <tr> <td>{{ user.first_name }}</td> <td>{{ user.last_name }}</td> <td>{{ user.email }}</td> <td>{{ user.role }}</td> <td>{% if user.is_active %} <i class="fas fa-check-circle" style="color:green"></i> {% else %} <i class="fas fa-times-circle" style="color: red;"></i> {% endif %} </td> <td><a href="{% url 'admin:edit_user' user.id %}" ><i class="fas fa-edit" style="color:limegreen ;"></i></a>&nbsp;<input type="checkbox" name="is_active" data-toggle="toggle" id="statuschange" data-on="Activate" checked data-off="Deactivate" data-size="xs" … -
Data format for text/plain requests in DRF API
Building an API to be used by A9G for communication. As a result, text/plain is desired. The API currently works well with application/json and other Content-Type, however, I am finding it hard getting the correct format for posting text/plain data. Tried: meter_id=OND123 timestamp=2019-08-24T14:15:22Z current=45.6 voltage=240.0 frequency=50 power_factor=0.6 energy=78 and different variations of it but I always get: { "non_field_errors": [ "Invalid data. Expected a dictionary, but got bytes." ] } My plaintext parser is: class PlainTextParser(parsers.BaseParser): """ Plain text parser. """ media_type = "text/plain" def parse(self, stream, media_type=None, parser_context=None): """ Simply return a string representing the body of the request. """ return stream.read() And only those fields are required. Can anyone help me out with the correct data format for this? -
In SQLAlchemy, Which is better to fetch the data in descending order or reverse list the fetched data?
I have to fetch data in descending order. So what would be faster? fetch the data in descending order or reverse() the list of fetched data. Note: I have been using SQLAlchemy in Flask framework. My application has to fetch hundreds of data from MySQL. -
Streaming opencv frame with django frame is not working on all
I'm trying to stream OpenCV frames to web browser like is described in answer here: How to stream opencv frame with django frame in realtime?. I don't know why in Firefox is all working all the time, but when I tried Safari the stream is sometimes not working. Exist any universal solution of this problem for Firefox, Safari, Chrome and so on. Thanks. -
Getting Next/Prev item from database Django
I have read Getting next and previous objects in Django and How to access the next and the previous elements in a Django template forloop?, but I am still confused how to get the next item. I have tried these suggestions, and I've read the documentation. I can't find any youtube videos really. Can someone explain it to me? -
error occur while run url.py in django in pycharm
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. why this error occured .how can I solve this error. please give me an answer -
Django linking files together
I'm trying to build a PWA inside a Django project. Myfolderstructur inside the pwa app: pwa->static->pwa->serviceworker.js and pwa->templates->indexPWA.html How can i load the indexPWA.html in the serviceworker.js? var filesToCache = ["indexPWA.html",... gives the error: ` /static/pwa/indexPWA.html HTTP/1.1" 404` If i copy another indexPWA.html inside the static folder, the error is removed, but my PWA is not installable and 2 identical files in one project it's not the way it should be. In the indexPWA.html i load the serviceworker.js like: if ("serviceWorker" in navigator) { navigator.serviceWorker.register("{% static 'pwa/serviceworker.js' %}"); }