Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Django - I need to run collectstatic for every change I make in development
I have successfully deployed my web app to heroku. Now I want to continue development on the local host I get from 'python manage.py runserver', but it doesn't reload the CSS until I do 'python manage.py collectstatic'. (I have tried F5 and Ctrl+F5). Before deployment it would automatically reload all css on refresh. Here is my settings.py file: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.2.7. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path import environ # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent env = environ.Env() environ.Env.read_env() # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ '192.168.1.6', '127.0.0.1', 'mahmoudhamdyportfolio.herokuapp.com' ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
Do I really need to accommodate both GET and POST request formats in a django form?
I'm new to django but something I don't understand is the need for accommodating both the GET and POST request types when developing a form. Please refer to code below from django docs: from .forms import NameForm def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, 'name.html', {'form': form}) The reason this confuses me is because I have developed a GET based form and it is working and I have no need for the POST portion above? See below: # views.py def simplifier_form(request): form = LabelForm() return render(request, "simplifier.html", {"form": form}) # forms.py class LabelForm(ModelForm): labels = forms.ModelChoiceField( queryset=Label.objects.all(), to_field_name='label_name', widget=forms.Select(attrs={'class': 'labels'}), ) class Meta: model = Label fields = ['labels'] -
Use IntegerChoices in model Meta class
I'm creating some constraints in my Meta class that reference an IntegerChoices enum. The issue I'm having is that I can't seem to figure out how to reference that IntegerChoices enum. class MyModel(models.Model): States = models.IntegerChoices('States', 'PROGRESSING INSTALLED DELETED') state = models.PositiveSmallIntegerField(choices=States.choices, help_text='Defines the cluster\'s current state') class Meta: constraints = [ models.CheckConstraint(check=models.Q(state__in=States), name='cluster_state_valid'), ] self.States isn't working, no self object. MyModel.States isn't working either since MyModel isn't fully instantiated at this point. Any advice/recommendation would be appreciated, thanks! -
how to link django signals and ajax
I am trying to implement a data collection system using iot devices. currently the data transmission is through an API using django REST framewokrs. That works excellent I would like to know some approach so that a trigger is generated when it receives data and these on the user's website are refreshed using ajax. maybe the use of signals but would not know how to bind that signal with ajax. I am somewhat newbie to javascript. some path should I follow? -
AttributeError: 'WSGIRequest' object has no attribute 'get' heroku
Am having a get request but it's failing on heroku with this error : AttributeError: 'WSGIRequest' object has no attribute 'get' I have failed to get the root cause of it Below is my view : class PostDetail(generics.GenericAPIView): """Blog post details""" queryset = Post.objects.all() serializer_class = serializers.PostSerializer authentication_classes = (JWTAuthentication,) permission_classes = (PostsProtectOrReadOnly, IsMentorOnly,) lookup_field = 'slug' def get_post_object(self, slug): post = get_blog_by_slug(slug) return post def get(self, request, slug): post = self.get_post_object(slug) if not post: return response.Response({ 'errors': _('Sorry, Blog post with the specified slug does' 'not exist') }, status=status.HTTP_404_NOT_FOUND) # track views of a viewed blog post. ip_address = get_ip_address(request) obj = CustomIPAddress.objects.create(address=ip_address) post.address_views.add(obj) serializer = self.serializer_class(post, context=request) return response.Response(serializer.data, status=status.HTTP_200_OK) Methods am calling above : def get_blog_by_slug(slug: str): """Get post by slug.""" try: obj = Post.objects.get(slug=slug) return obj except Post.DoesNotExist: return None def get_ip_address(request): """get ip address.""" try: client_ip, is_routable = get_client_ip(request) if client_ip is None: return uuid.uuid4() else: return client_ip except AttributeError: return uuid.uuid4() except: return uuid.uuid4() Am wondering why on local it's working but on heroku server am getting this error. -
django sql server studio backend doesn't support altering from/to AutoField
Please help me I tried to connect to the database The connection was successful and the rules were lifted, but I have this problem raise NotImplementedError("the backend doesn't support altering from/to %s." % t.name) NotImplementedError: the backend doesn't support altering from/to AutoField. Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying account.0001_initial... OK Applying account.0002_email_max_length... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying profiles.0001_initial... OK Applying goals.0001_initial...Traceback (most recent call last): File "C:\Users\athamma.virtualenvs\src-NXdWuPOU\lib\site-packages\django\db\backends\utils.py", line 83, in _execute return self.cursor.execute(sql) File "C:\Users\athamma.virtualenvs\src-NXdWuPOU\li Apply all migrations: account, admin, auth, contenttypes, goals, notifications, profiles, sessions, sites, socialaccont Running migrations: Applying goals.0001_initial... OK Applying goals.0002_approvedgoals... OK Applying goals.0003_auto_20210928_1206... OK Applying goals.0004_goal_cer... OK Applying goals.0005_auto_20211027_1918...Traceback (most recent call last): -
Django Parameters in URL from POST Request
I'm trying to create a search bar in Django, where users can enter a value to search for, click enter / search button, and then the url redirects to https:localhost:3000/usearch/abc, if they for example search for abc. This is URL paramter can always change based on the search, and it should send the parameter to the views.py file to be processed, though I can't get it to work. urls.py urlpatterns = [ path('', views.index, name='index'), path('register/', views.register, name='register'), path('usearch/', views.usearch, name='usearch'), path('usearch/<str:query>', views.usearch_query, name='usearch_query' ] views.py def usearch(request): return render(request, 'myapp/usearch.html') def usearch_query(request, query): context = {'query': query} print(query) # Testing the search result return render(request, 'myapp/usearch_query.html'} usearch.html <form method="POST" action="{% url 'usearch_query' %} <input type="search" placeholder="Search here..."> <button type="submit"> Search </button> </form> usearch_query.html {{ query }} I essentially want the user to search something, have it navigate to usearch/<search_parameter> and process the search in the usearch_query function so I can do some computations with it. -
Filtering by length of substring of a name django queryset?
I am trying to find a efficient way of filtering based on a length range of a full name field in my model. E.g the full name is separated as "John-Doe" in the model. John is the first name and Doe is the last name My goal is to find all objects in the model whose first_name is greater than 2 but less than 5. One approach I thought was of adding two additional field in the model called first_name and last_name and running a management command to extract the first_name and last_name and save it in those fields. This is a legacy db. So, there are close to 1million records. number_of_character_filter |= Q(first_name__length__gte=start, first_name__length__lte=end) Is there any other efficient approach I can take to resolve this? -
Update data using Django and AJAX
I have an issue with making a choice field in the input field from Django data. the models.py is: class Manifold_monitoring(models.Model): MFD_type = models.ForeignKey(Manifo_types , on_delete=models.CASCADE) DATE_TEST = models.DateField() Pressure_MFD = models.DecimalField(max_digits=15, decimal_places=3,null=True, blank=True) Pressure_SP = models.DecimalField(max_digits=15, decimal_places=3,null=True, blank=True) ..... def __str__(self): return str(self.MFD_type.MFDsID.MFDsID +' '+ self.MFD_type.Type +' '+ self.MFD_type.Fluid_N) class Meta: ordering = ('-post_date',) unique_together=[['MFD_type','DATE_TEST']] and the updating views.py: class UpdManifold_Monto(View): form_class = Manifold_monitoring_F def get(self,request, pk, *args, **kwargs): if request.is_ajax(): task = Manifold_monitoring.objects.get(pk=pk) task.delete() return JsonResponse({"message":"success"}) return JsonResponse({"message": "Wrong request to delete"}) def post(self,request, pk, *args, **kwargs): if request.is_ajax(): task = Manifold_monitoring.objects.get(pk=pk) print('request.is_ajax()1', task.MFD_type_id) data = { "MFD_type_id": task.MFD_type_id, "DATE_TEST" :task.DATE_TEST, "Pressure_MFD":task.Pressure_MFD, "Pressure_SP":task.Pressure_SP } print('request.is_ajax()2', task.MFD_type ,data ) form = self.form_class(request.POST, initial=data) if form.is_valid(): MFD_type = form.cleaned_data['MFD_type'] DATE_TEST = form.cleaned_data['DATE_TEST'] Pressure_MFD = form.cleaned_data['Pressure_MFD'] Pressure_SP = form.cleaned_data['Pressure_SP'] print('request.is_ajax()3', MFD_type) if form.has_changed(): task.MFD_type_id = MFD_type task.DATE_TEST = DATE_TEST task.Pressure_MFD = Pressure_MFD task.Pressure_SP = Pressure_SP task.save() return JsonResponse({"message": "success"}) return JsonResponse({"message":"No change"}) return JsonResponse({"message":"Failed"}) return JsonResponse({"message": "Wrong request"}) The HTML code of the edit form: <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLable" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Edit</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form id="formEdit" action=""> {% csrf_token %} <div class="modal-body"> <div class="form-group validate"> … -
how can I calculate a value from user input which are not saved to database and value from database using django
I am doing the site with calculating of calories in products, so I need to do this action. I have different objects of products and for each - different value in "calories per 100 gram" field. So idk how to do the calculation not saving it to database, I am sure it is easy, but I am newer, so.. This is my code: views.py: class CurrentProductView(FormView): template_name = "cur_product.html" form_class = ProductForm success_url = reverse_lazy("product") def form_valid(self, form): obj = form.save(commit=False) calc_value = (obj.cur_weight * obj.calories) / 100 return HttpResponse(calc_value) forms.py: class ProductForm(forms.ModelForm): cur_weight = forms.IntegerField() class Meta: model = Product fields = ["calories"] models.py: class Product(models.Model): name = models.CharField(max_length=100) calories = models.PositiveIntegerField() #calories per 100 gram description = models.TextField(max_length=100, blank=True, null=True) image = models.ImageField(blank=True, null=True) html: {% block content %} <form method="post"> {% csrf_token %} {{ form.cur_weight }} <input type="submit" value="Count"> </form> {% endblock %} -
Django-rest-framework: 3rd Level Custom endpoints
I'm new to the Django rest framework and I'm trying to achieve 3rd level custom endpoints. I just want someone advice to solve 3rd level custom endpoints. I have read the official document: https://www.django-rest-framework.org/api-guide/routers/ but I'm confused to solve this. Please needs some advice. To achieve these endpoints: /admin/advisor/(default admin) /user/<user-id>/advisor /user/<user-id>/advisor/<advisor-id>/ /user/<user-id>/advisor/booking/ models.py from django.db import models class Advisor(models.Model): advisor_name = models.CharField(max_length=200) advisor_photo_url = models.ImageField(null=True, blank=True) def __str__(self): return self.advisor_name class User(models.Model): advisor_fk = models.ForeignKey(Advisor, related_name='advisors', on_delete=models.CASCADE) name = models.CharField(max_length=200) email = models.CharField(max_length=200) password = models.CharField(max_length=200) def __str__(self): return self.name class Booking(models.Model): user_fk = models.ForeignKey(User, related_name='users', on_delete=models.CASCADE) booking = models.DateTimeField() def __str__(self): return '{0}'.format(self.user_fk) serializers.py from rest_framework import serializers from usersite.models import Advisor, User, Booking from django.utils import timezone class DateTimeFieldWihTZ(serializers.DateTimeField): def to_representation(self, value): value = timezone.localtime(value) return super(DateTimeFieldWihTZ, self).to_representation(value) class AdvisorSerializer(serializers.ModelSerializer): class Meta: model = Advisor fields = ['advisor_name', 'advisor_photo_url', 'id'] class BookingSerializer(serializers.ModelSerializer): booking = DateTimeFieldWihTZ(format='%I:%M%p') #%b %d %Y %I:%M%p class Meta: model = Booking fields = ['user_fk', 'booking'] class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['advisor_fk', 'name', 'email', 'password'] -
How to delete label of a form in Django
How can I delete label of form in Django. I have something like this. class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['user_image'] widgets = { 'user_image': forms.FileInput(attrs={'class': 'image-upload', 'label': ''}), } image-upload class does not include label. I have a auto-generated label and is written 'user-image' -
I can't run a function from the service layer in Django
I am a novice programmer. I'm trying to integrate PayPal IPN into my project, implement recurring subscription payments. I wrote a function that works fine in the console, BUT I DO NOT KNOW HOW TO RUN THIS FUNCTION SO THAT IT WOULD WORK AUTOMATICALLY. The ideal option for me would be if, when the data I need appears in the PayPal table, the IPN function would automatically start and perform the actions I need. For example, when these conditions appear in the table: ipn = PayPalIPN.objects.filter(payment_status='Completed', txn_type='subscr_payment', txn_id__gt=0, mc_currency='USD', payment_gross__gt=0, signal_1=False, pometka_1=False).order_by("-pk")[:20] my function would start, bypass the data in the table and perform the actions that I needed. I have tried such methods: def Proverka_1(): ipn_12 = PayPalIPN.objects.filter(payment_status='Completed', txn_type='subscr_payment', txn_id__gt=0, mc_currency='USD', payment_gross__gt=0, signal_1=False, pometka_1=False).order_by("-pk")[:20] if ipn_12.exists(): return Podpiska() def Proverka_2(): ipn_12 = PayPalIPN.objects.filter(payment_status='Completed', txn_type='subscr_payment', txn_id__gt=0,mc_currency='USD', payment_gross__gt=0, signal_1=False, pometka_1=False).order_by("-pk")[:20] if ipn_12.count() > 0: return Podpiska() def Proverka_3(): ipn_12 = PayPalIPN.objects.filter(payment_status='Completed', txn_type='subscr_payment', txn_id__gt=0, mc_currency='USD', payment_gross__gt=0, signal_1=False, pometka_1=False).order_by("-pk")[:20] if len(ipn_12) > 0: return Podpiska() From the console, the Podpiska() function is launched, and works as expected. But when I write this in a python document, nothing works. I do not know how to run it all. I don't even know how to … -
Is it best practice to define a join table for Django many to many relationships?
I have the following code: class Tutors(models.Model): first_name = models.CharField(max_length=20, default=None, blank=False) #you need to add default none and blank false to enforce the Not-Null constraint last_name = models.CharField(max_length=20, default=None, blank=False) email = models.EmailField(max_length=254,default=None, blank=False) birth_day = models.DateField(auto_now=False, auto_now_add=False, default=False, blank=False) def __str__(self): return(self.first_name + ' ' + self.last_name) class ArtSubjects(models.Model): subject_name = models.CharField(max_length=20, default=None, blank=False) tutors = models.ManyToManyField(Tutors) def __str__(self): return self.subject_name My question is, should I define many to many relationships like this? Or should I define a new class for the table? The reason I ask is that I can get objects from the join table by querying by ArtSubjects class like so - adobeAI.tutors.all() returns <QuerySet [<Tutors: Matt Aird>, <Tutors: Tom John>]> But I can't think of a way for querying the join table by tutors to see what classes an individual tutor teaches. Any advice on this? -
`xhr.getAllHeaders()` is missing some headers in a browser extension context?
I am working on a browser extension. In a script running on the popup page, I am making an ajax request. On the first line of my handler for the xhr.onload event, I have console.log(xhr.getAllResponseHeaders()). However, some headers from the response are missing. I know that this could be a problem with my manifest.json file, so here it is, with some extra details removed: { "manifest_version": 2, "name": "...", "version": "1.0", "description": "...", "options_ui": { "page": "options.html" }, "icons": { "16": "icons/favicon-16x16.png", "32": "icons/favicon-32x32.png" }, "browser_action": { "default_popup": "popup.html", "default_icon": "./icons/favicon-32x32.png" }, "key": "...", "permissions": ["identity"], "content_security_policy": "script-src 'self' https://unpkg.com https://apis.google.com https://www.gstatic.com https://www.googleapis.com https://securetoken.googleapis.com; object-src 'self'", "content_scripts": ["..."] } These are the actual response headers, according to the network debugging tab: HTTP/1.1 200 OK Date: Wed, 27 Oct 2021 18:09:36 GMT Server: WSGIServer/0.2 CPython/3.9.6 Content-Type: text/html; charset=utf-8 Hx-Trigger: setupLogin X-Frame-Options: DENY Content-Length: 220 Vary: Cookie, Origin X-Content-Type-Options: nosniff Referrer-Policy: same-origin Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: chrome-extension://kcegdmcjklppcfbmfjgkkomecpaofoec However, this is the output of console.log(xhr.getAllResponseHeaders()) on the first line of the xhr.onloaded event handler: content-length: 220 content-type: text/html; charset=utf-8 CORS I should note that I have no obvious CORS errors. I am using Django with the django-cors-headers library, and I have all these headers, … -
Cannot authenticate in Django
I implemented my CustomUser model and as far as I have understood I need to override an authentication method. I've done it, but my login form always returns the message "incorrect login/password" The registration form works fine my new accounts appear in the database. By the way, I tried to add the print function in authenticating backend method and it didn't print anything setting.py AUTHENTICATION_BACKENDS = ['account.forms.CustomBackend'] AUTH_USER_MODEL = 'account.CustomUser' I use built-in Django LoginForm urls.py path('login/', LoginView.as_view(template_name='login.html', authentication_form=CustomLoginForm), name='login'), models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """Define a model manager for User model with no username field.""" def _create_user(self, email, password=None, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return … -
How to scroll a line chart with the help of a mouse in Django?
I have a line chart rendered with Chart.js 2.4.0. According to the business requirement, the user should be able to move data points shown in the line chart using the mouse. Particularly, clicking the data point, hold the mouse clicked and move the point somewhere. Like drag and drop. Any ideas how to start? -
TypeError problem when I create "context_processor" in django
what is wrong here? I created 2 classes in the context_processor file, this problem I was facing when I was trying to return none dictionary objects but now doesn't understand what is wrong here. settings.py TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'accounts.context_processor.CreateNotification', 'accounts.context_processor.NotificationFeatures' ], }, }, ] context_processor.py from accounts.models import Notification, User class CreateNotification: def __init__(self, from_user, to_user, notification_type, role_sender, role_receiver, read_notif=False, active=False): self.from_user = from_user self.to_user = to_user self.notification_type = notification_type self.role_sender = role_sender self.role_receiver = role_receiver self.active = active self.read_notif = read_notif def send(self): if self.notification_type == "register": self.active = True Notification.objects.create( from_user=self.from_user, to_user=self.to_user, notification_type=self.notification_type, role_sender=self.role_sender, role_receiver=self.role_receiver, read_notif=self.read_notif, active=self.active ) return {} def read(self, id=None): if id: if self.active == True: self.read_notif = True return Notification.objects.filter(id=id).update(read_notif=self.read_notif) return {} class NotificationFeatures: def NotificationObject(self, req): notifications = Notification.objects.all() user_request = User.objects.get(username=req.user.username) if req.user.is_authenticated: # who is sender three_roles = notifications.distinct() for roles in three_roles: print(user_request.roles) if user_request.roles == roles: notifications.filter(from_user__roles__id=roles) return {} the traceback is: init() missing 4 required positional arguments: 'to_user', 'notification_type', 'role_sender', and 'role_receiver' knowing that: when I use the same classes that are in "context_processor file" in other locations like index views, for example, it works. so, I think that the problem … -
How to use Django/Nodejs with DDEV
I work a lot with DDEV on my PHP projects and love the features DDEV offers. Since I also work with Django and NodeJS projects I would like to use them in combination with DDEV. Officially these are not yet supported in the current version (1.18) but maybe someone has already found a solution? -
como hacer para que automaticamente no busque los datos de primary key en una relacion en django para un proceso automatico
id_clie = models.ForeignKey( Cliente, on_delete=models.CASCADE,) -
Django Chat - Image upload before message on channels
I've a Chat application built on Django Channels It has the capability to send images, files (soon). I send my message data over channels And create my Message model object during that. Now I've to upload images as well. Uploading images via a REST API and creating/updating a ImageField is what I've done before. Now in this case, I create the message object when something is sent over the channel and uploading an image over a websocket isn't good as I've read. How do people send images and create the object upon image upload success? This is my model class Message(models.Model): message = models.TextField() image = models.CharField(max_length=64, null=True) reported = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="message_reported" ) time = models.DateTimeField(auto_now_add=True) -
Generating user-unique links and storing points on purchase in Django
I'm trying to create a user-unique link so that the user can give to others, if the other user visited the website a cookie would be set for them, if the user with the cookie purchasd an item for the first time, a point would be added to the first user(the person who invented the second user to the website) -
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 onle for example (sender =15, receiver=11) (sender =11, receiver=15) -
DRF nested serializer has validation over fields instead of ID
I have a PermissionSerializer and GroupSerializer, when I request to get data it works fine, but when I want to add a new group, it expects to receive all fields of PermissionSerializer while for the model it only needs ID. class PermissionSerializer(serializers.HyperlinkedModelSerializer): """Permission serializer.""" url = serializers.HyperlinkedIdentityField(view_name="account:permission-detail") content_type = ContentTypeSerializer(many=False, read_only=True) class Meta: model = Permission read_only_fields = ( "url", "id", "name", "content_type", "codename", ) fields = ( "url", "id", "name", "content_type", "codename", ) class GroupSerializer(serializers.HyperlinkedModelSerializer): """Group serializer.""" url = serializers.HyperlinkedIdentityField(view_name="account:group-detail") permissions = PermissionSerializer(many=True) class Meta: model = Group fields = ( "url", "name", "permissions", ) When I enable the read_only=True, it completely ignores the permissions field validation while I really need it to be validated as well. Sample request which I expected to work fine: { "name": "editors", "permissions": [ {"id": 8} ] } or { "name": "editors", "permissions": [8] } But I really have no clue how to fix it. If I change the PermissionSerializer, then my output will be changed which it shouldn't, and if I want to keep it as what it is now, then I have to feed it by all permissions fields: { "name": "editors", "permissions": [{ "name": "something", "url": "something", "content_type": "something", "codename": … -
setattr doesn't save the values of my class in Python script
I´ve working on a project that must save in a database the values provided by a json. The setattr function is not working when i try to save the values of each json concept in the database. I think that i have provided the function attributes correctly. This is my models.py: class Balance_sheet(models.Model): company_name = models.CharField(max_length=140) year = models.CharField(max_length=140) quarter = models.CharField(max_length=140) CashAndCashEquivalentsAtCarryingValue = models.IntegerField(null=True, blank=True) ... #Extra fields class Meta: ordering = ['year'] verbose_name = "Balance Sheet" verbose_name_plural = "Balance Sheets" def get_attribute_by_name(self, field): if hasattr(self,field): return getattr(self,field) else: return '' def set_attribute_by_name(self, field, value): if hasattr(self, field): return setattr(self, field, value) else: return '' def __str__(self): return "%s %s" % (self.company_name, self.year) This is my script.py: from types import SimpleNamespace from typing import AsyncGenerator from django.core.management.base import BaseCommand, CommandError from database.models import Balance_sheet class Command(BaseCommand): def handle(self, *args, **options): data = open('database/static/data/data-q1.json') jsonObjectQ1 = json.load(data) json_prettyQ1 = json.dumps(jsonObjectQ1, sort_keys=True, indent=4) data.close() x = json.loads(json_prettyQ1, object_hook=lambda d: SimpleNamespace(**d)) print(x.startDate, x.companyName, x.companyCIK) print(x.year) # Creating Objects balance_sheet = Balance_sheet.objects.create(company_name=x.companyName, year=x.year, quarter=x.quarter) for data in x.data.bs: concept = data.concept value = data.value fields = Balance_sheet._meta.get_fields() for field in fields: if concept == field.name: model_name = field.name setattr(balance_sheet, model_name, value) balance_sheet.save I …