Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Resolution and customization of Django REST Framework permissions
I have a given url defined that's being managed by a single view. re_path(r'^something(?P<path>(/[^/]+)*)$', SomethingView.as_view(), name='something'), So, the view handles a matrix of ['POST','GET','PATCH','DELETE'] but it also has another matrix which is determined by the url path following the /something. examples: /something/color /something/shape so, the permission for POST /something/color can differ from POST /something/shape. I do have a custom permission set for the entire SomethingView but the has_permission is called before the view processes the full path of the URL and is completely in the dark if /color or /shape is part of the path, which defeats my purpose of having custom permissions for all combinations of METHOD + what's coming after /something My options: not using DJango REST permission classes and implementing permissions myself on the actual get/post/... methods Finding a way to customize Django REST permission classes to get real-time information from the actual pre-processing of the path + method used in the request. Any ideas on #2? -
Django REST framework .annotate(Count()) appears to return incorrect count
I have three models that look approximately like this: class Utterance(models.Model): id = models.SlugField(max_length=20, primary_key=True) class TransformationWav(models.Model): utt = models.ForeignKey(Utterance, on_delete=models.CASCADE, blank=True, null=True) parent_wav = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) trimmed = models.BooleanField(default=False) class TransformationMFBs(models.Model): utt = models.ForeignKey(Utterance, on_delete=models.CASCADE, blank=True, null=True) wav = models.ForeignKey('TransformationWav', on_delete=models.CASCADE) And I have a QuerySet generated with these filters that returns two Utterance objects with the same ID: >>> filters = {'transformationwav__trimmed': False, 'transformationwav__utt__id': "m00_00_040", 'transformationmfbs__wav__trimmed': False, 'transformationmfbs__utt__id': "m00_00_040"} >>> utterances = Utterance.objects.filter(**filters) >>> utterances <QuerySet [<Utterance: m00_00_040>, <Utterance: m00_00_040>]> I can successfully remove the duplicate utterance by using .distinct(), leaving only one utterance in the queryset: >>> utterances = utterances.distinct() >>> utterances <QuerySet [<Utterance: m00_00_040>]> >>> len(utterances) 1 >>> utterances.count() 1 However, when I then try to annotate the utterances with their counts by utterance ID, Count() finds two objects in the QuerySet: >>> utterances = utterances.annotate(count=Count('id')) >>> for utt in utterances: ... print(utt.id, utt.count) ... m00_00_040 2 So my question is, why does .annotate(Count()) find two objects here instead of one? Note: Though I can use .annotate(count=Count('id', distinct=True)) to get only one result, I feel like I shouldn't have to use distinct twice, because I already used it on the QuerySet. I have also … -
Trouble with ProxyPass of REMOTE_USER from nginx to Django
I have an nginx web server that's configured with client certificate authentication. Once authenticated, I proxy requests to a uWSGI Django application server. I've set-up my Django application to perform authentication using REMOTE_USER (https://docs.djangoproject.com/en/3.1/howto/auth-remote-user/), however it doesn't seem to be working as I receive the "'AnonymousUser' object is not iterable" error from Django. I'm assuming that I'm missing something in my nginx configuration: server { listen 80; server_name my.website.net; return 301 https://$server_name$request_uri; } server { listen 443 ssl; ssl_certificate /etc/letsencrypt/live/my.website.net/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/my.website.net/privkey.pem; ssl_verify_client on; ssl_verify_depth 2; ssl_client_certificate /etc/nginx/ssl/cas.pem; proxy_set_header X-SSL-Client-Serial $ssl_client_serial; proxy_set_header X-SSL-Client-Verify $ssl_client_verify; proxy_set_header X-SSL-Client-S-DN $ssl_client_s_dn; proxy_set_header X-Remote-User $remote_user; proxy_set_header REMOTE_USER $remote_user; location / { root /var/www/my.website.net; index index.html index.htm; } location /django { proxy_set_header Host 10.101.10.228; proxy_http_version 1.1; proxy_set_header Connection "Keep-Alive"; proxy_set_header Proxy-Connection "Keep-Alive"; proxy_pass http://10.101.10.228:8000/webapp; proxy_redirect http://10.101.10.228/django/ https://my.website.net/django/; } } I've also tried utilizing the nginx uwsgi_* directives with no luck: upstream django { server 10.101.10.228:8000; } location /django { include uwsgi_params; uwsgi_pass django; uwsgi_param SCRIPT_NAME /webapp; uwsgi_param REMOTE_USER $remote_user; uwsgi_param X-REMOTE-USER $remote_user; } Is there something that appears to be missing? -
Automatically adding inline formsets in django create view
I'm creating a questionnaire site with django, whereby a user can select a questionnaire to answer. There are two models - questionnaire and response - for storing the completed questionnaires. There are another two models - template and questions - which store details such as the questions contained in each questionnaire. I've got everything to work. When a user selects the questionnaire they want to complete, a function based view runs that fetches the necessary info from the template and questions model, saves those into the questionnaire and response models before returning an update view where the user can then answer the questions. This is done via an inline formset. My question is whether this can be replicated without having to save the questionnaire and response models first. This is so that if a user decides not to complete the questionnaire, it won't have been needlessly saved. How would I go about automatically adding inline formsets in the create view. I haven't added any of my code here as I'm only looking for some high-level guidance so I can then research further. -
Testing Ajax on Django
I'm trying to write a test for an Ajax get a request in Django. Here's how I tried. from django.test import TestCase from django.urls import reverse from .models import ResourcePost, User from register.models import DonorProfile from django.utils import timezone class getResourcePostTests(TestCase): def setUp(self): ResourcePost.objects.create( title="test1", description="test", quantity=10, dropoff_time_1=timezone.now(), dropoff_time_2=timezone.now(), dropoff_time_3=timezone.now(), date_created=timezone.now(), donor=createdonor_1(), resource_category="FOOD", status="AVAILABLE", ) ... def test_getResourcePost(self): rescource_post_1 = ResourcePost.objects.get(title="test1") rescource_post_2 = ResourcePost.objects.get(title="test2") rescource_post_3 = ResourcePost.objects.get(title="test3") response = self.client.get(reverse('donation:getResourcePosts')) self.assertEqual(response.status_code, 200) Here is my view: @login_required def getResourcePost(request): user = request.user curr_user_rc_1 = user.helpseekerprofile.rc_1 curr_user_rc_2 = user.helpseekerprofile.rc_2 curr_user_rc_3 = user.helpseekerprofile.rc_3 posts = ResourcePost.objects.all() passingList = [] for post in posts: if post.date_created >= user.helpseekerprofile.message_timer_before and ( post.resource_category == curr_user_rc_1 or post.resource_category == curr_user_rc_2 or post.resource_category == curr_user_rc_3 ): notiPost = { "id": post.id, "title": post.title, "description": post.description, } passingList.append(notiPost) context = {"resource_posts": passingList} return JsonResponse(context) This is my ajax code: $(document).ready(function () { setInterval(() => { $.ajax({ type: 'GET', url: "{% url 'donation:getResourcePosts' %}", success: function (response) { $("#display").html('<i class="fas fa-bell"></i>') let postCounter = 0 for (i = 0; i < response.resource_posts.length; i++) { postCounter += 1 } if (postCounter > 0) { $("#display").append('<span class="message-number">' + postCounter + '</span>') } }, error: function (response) { console.log("No DATA FOUND") } … -
Deduced attributes of a LazyAttribute using Factory Boy
Using Factory Boy and Faker in a Django project, i would like to create deduced attributes, meaning a method from Faker returns a set of values that are dependent of each other. These values will be utilized for the other attributes of the Factory Class. Example: The location_on_land method from faker.providers.geo returns a tuple of latitude, longitude, place name, two-letter country code and timezone (e.g. ('38.70734', '-77.02303', 'Fort Washington', 'US', 'America/New_York'). All values depend on each other, since the coordinates define the place, country, timezone, etc. Therefor i cannot use separated functions for the (lazy) attributes like faker.providers.latitude, faker.providers.longitude for my attributes. Is it possible to somehow access the return values from the lazy attribute to use them for other deduced attributes? Is there a better way to access the return values from location_on_land to use them on the other depending attributes My Factory-Class looks like this: # factory_models.py class OriginFactory(factory.django.DjangoModelFactory): """Factory for Origin.""" class Meta: model = models.Origin exclude = [ "geo_data", ] # not working since not a lazy attribute # lat, lon, place, iso_3166_alpha_2, _ = fake.location_on_land() # desired outcome (not working) geo_data = factory.Faker("location_on_land") # attributes using the return values of `location_on_land` from lazy attribute (pseudo-code, … -
OnetoMany relationship models: limiting the number of instances of a model that have the same foreign key in django
I am working on a Django project where a user is able to create instances of a model Route and can create instances of a model Address. I have related those 2 models by adding the rout_name from the route model as a foreign key in the address model. I want to limit the number of instances that belong to a certain route_name strictly in the range up 50 addresses. This means that the user can only add 50 addresses that belong to a specific route_name. SO if the user successfully adds 50 and then wants to add another address to the same route name, I want the app to give them a message saying " Sorry, Cannot add more addresses to this route". Any idea where I can put this condition so that the addresses added can only be 50 or less than 50 that belong to the same foreign key(which is route_name in my case)? Here is the models.py for both of my models: class Route(models.Model): username = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE) title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) number_of_locations = IntegerRangeField(min_value=2, max_value=50, default=None) def __str__(self): return self.title def get_absolute_url(self): return reverse('route-detail', kwargs={'pk': self.pk}) class Address(models.Model): route_name = models.ForeignKey(Route, on_delete=models.CASCADE) … -
How to setup Virtual Environment for Django development without internet?
Every time I create a Virtual Environment for Django, from inside the virtual environment, I need to run pip install django which requires internet access. Can I somehow install django globally on my machine and "pull" it from inside the Virtual Environment? I am running Zorion OS(Ubuntu-ish). -
Using Django on google colab
I am trying to start a new project on djago in google colab. In order to create a new one, I need to use cmd command line - $ django-admin startproject Project name. Is there another way to do it? Thank you -
Get max value from a set of rows
This question is in relation to project 2 of the cs50 course which can be found here I have looked at the following documentation: Django queryset API ref Django making queries Plus, I have also taken a look at the aggregate and annotate things. I've created the table in the template file, which is pretty straight forward I think. The missing column is what I'm trying to fill. Image below These are the models that I have created class User(AbstractUser): pass class Category(models.Model): category = models.CharField(max_length=50) def __str__(self): return self.category class Listing(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() initial_bid = models.IntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE) date_created = models.DateField(auto_now=True) def __str__(self): return self.title class Bid(models.Model): whoDidBid = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) list_item = models.ForeignKey(Listing, default=0, on_delete=models.CASCADE) bid = models.IntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True) def __str__(self): return_string = '{0.whoDidBid} {0.list_item} {0.bid}' return return_string.format(self) This is the closest I could come to after a very long time. But the result I get is just the number 2. Ref image below Listing.objects.filter(title='Cabinet').aggregate(Max('bid')) Where 'Cabinet' is a Listing object that I have created. And placed two bids on them. So the question is, how do I get the Maximum bid … -
Unknown issue in Django machine learning app
I loaded a basic machine learning model using joblib in my django app and there is no error but predict method is showing same value even for different user inputs views.py def myapp(request): if(request.method =='POST'): mylis=[] test=joblib.load('/mltestapp/test.sav') mylis.append(request.POST.get('day')) obj= test.predict([mylis]) return render(request,'mltestapp/myapp.html',{'obj':obj[0][2]}) return render(request,'mltestapp/myapp.html') -
ValueError at /accounts/profile/edit/,,,,, Field 'id' expected a number but got 'edit'
models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from phonenumber_field.modelfields import PhoneNumberField class UserprofileCity(models.manager): def get_queryset(self): return super(UserprofileCity,self).get_queryset().filter(city='surat') class UserProfile(models.Model): user= models.OneToOneField(User,on_delete=models.CASCADE) # you an add extra fields as per requirements after city = models.CharField(max_length=100,default='') description = models.CharField(max_length= 500,default='') phone_number = PhoneNumberField(default='+91',max_length=13,help_text='enter mobile number with country code') age = models.IntegerField(default=18) image = models.ImageField(upload_to='profile_image',blank=True) def __str__(self): return self.user.username def create_profile(sender,**kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile,sender=User) views.py: from django.shortcuts import render,redirect from django.urls import reverse from .forms import RegistrationForm,EditProfileForm,ProfileForm from django.contrib.auth.models import User from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth import update_session_auth_hash def register(request): if request.method =='POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect(reverse('accounts:login')) else: form = RegistrationForm() args = {'form':form} return render(request,'accounts/reg_form.html',args) def profile_view(request,pk=None): if pk: user = User.objects.get(pk=pk) else: user = request.user args = {'user':user} return render(request,'accounts/profile.html',args) def profile_edit(request): if request.method =='POST': form = EditProfileForm(request.POST,instance=request.user) profile_form = ProfileForm(request.Post,request.FILES,instance=request.user.userprofile) if form.is_valid() and profile_form.is_valid(): user_form = form.save() custom_form = profile_form.save(False) custom_form.user = user_form custom_form.save() return redirect(reverse('accounts:profile_view')) else: form = EditProfileForm(instance=request.user) profile_form = ProfileForm(instance=request.user.userprofile) args = { 'form':form, 'profile_form':profile_form } return render(request,'accounts/profile_edit.html',args) def password_change(request): if request.method=='POST': form = PasswordChangeForm(data = request.POST,user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request,form.user) return redirect(reverse('accounts:profile_view')) else: return redirect(reverse('accounts:change_password')) else: form = PasswordChangeForm(user = request.user) args … -
How to generate a new record based on the current new one and another one in the model in Django?
I need to create one record when user pass one and there is another one already in the model with same or suitable data. For example: models.py class Generated(models.Model): stage = models.PositiveSmallIntegerField() group = models.PositiveSmallIntegerField() and we already have a record Generated(stage=1, group=1) then we pass another one Generated(stage=1, group=2) and we need to generate one more record like Generated(stage=2, group=1) I just need to know how to get/find records in model when we check current passed record and then create one. -
Access to XMLHttpRequest at 'api url'' from origin 'client url'' has been blocked by CORS policy
i am working on full stack web and mobile projects with Django as backend and react/react-native as frontend. i am trying to post a form, it works great on react but it shows error in my react-native app. how can i post this form successfully? error screenshot below users.js export const CreateMerchantDetails = (formValues) => async (dispatch) => { console.log(formValues); const token = await AsyncStorage.getItem("token"); console.log(token); const config = { headers: { Authorization: "Token ".concat(token), }, }; axios .post(`${ROOT_URL}api/merchant/create`, formValues, { headers: config, }) .then((res) => { dispatch({ type: actionTypes.CREATE_MERCHANT_DETAILS, payload: res.data, }); }) .catch((err) => { console.log(err); const error = { msg: err.response, // status: err.response.status, }; dispatch({ type: actionTypes.CREATE_MERCHANT_DETAILS_ERROR, payload: error.response, }); }); }; screenshots settings.js import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'secret_key_here' DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'corsheaders', 'rest_auth', 'rest_auth.registration', 'rest_framework.authtoken', 'phonenumber_field', 'merchant', 'orders', 'notifications' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', '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 = 'romex.urls' AUTH_USER_MODEL = 'merchant.MerchantDetails' REST_AUTH_REGISTER_SERIALIZERS = { "REGISTER_SERIALIZER": "merchant.api.serializers.CustomRegisterSerializer", } REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10 } REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': … -
Secure file sharing
I'm doing a project on secure file sharing using django framework. Can anyone answer my questions?? where should I upload my file's After uploading a file it must encrypt in aes format. 3)the uploaded files could only be retrieved when 2nd user having the key whic was generated during encryption. Now can anyone answer how to do these tasks using django. -
Django Deployment on CPanel Error "Apache doesn't have read permissions to that file. Please fix the relevant file permissions."
I am trying to deploy a django application on cpanel. I cloned my github repository and all dependencies have been installed and everything is complete but when I try to open the website it gives me this page... What do I need to do in order to fix this? I don't have any knowledge about these file permissions and am just looking to host a small project. -
Django show name of reference not id
this simple database i created then this my code for showing the data in view.py ... def get (request, photo_id) tag = PhotoTag.objects \ .values('tag_id') \ .filter(photo_id = photo_id) \ .all() context = { ... 'my_tag': tag } and this is in my template {% for data in my_tag %} {{ my_tag.tag_id }} {% endfor %} the result is number, what I need is showing the data of another table (tag table) like my_tag => tag_id => name (of another table) when I do another way in view.py like tag = PhotoTag.objects \ .values('tag_id') \ .filter(photo_id = photo_id) \ .all() for data in tag: tag_name = Tag.objects \ .values('name') \ .filter(id=data.get('tag_id')) \ context = { ..., 'my_tag': tag_name, } then in template {% for data in my_tag %} {{ my_tag.name }} {% endfor %} the result is what I need (showing the text name of references table) but it's only 1 data, it's not perfectly loop So Can someone help me solve this problem, or have a magic trick for solve it? -
How to add a foreign key to the username. Django REST framework
During serialization, i noticed that the post_author Foreign Key of the Post model is referencing the id of the creator and thus, i can't display the username of the creator in the REST API, only the post_author id. How can i add the username of the post_creator, so that it is readable to other users, when i fetch the data on the frontend? models.py // CustomUser = the Creator of the post. class CustomUser(AbstractUser): fav_color = models.CharField(blank=True, max_length=120) class Post(models.Model): post_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posts') post_title = models.CharField(max_length=200) post_body = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.post_title views.py @api_view(['GET']) def post_list(request): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data) serializers.py user model and post model serialization class CustomUserSerializer(serializers.ModelSerializer): """ Currently unused in preference of the below. """ email = serializers.EmailField(required=True) username = serializers.CharField() password = serializers.CharField(min_length=8, write_only=True) class Meta: model = CustomUser fields = ('email', 'username', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) # as long as the fields are the same, we can just use this instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = … -
Presenting ForeignKey Field As Radio Choices
I have the following setup: MODELS.PY class MeatMenu(models.Model): MEAT_CHOICES = ( ('chicken', 'Chicken'), ('beef', 'Beef'), ) meat_type = models.CharField(max_length=20, choices=MEAT_CHOICES) meat_price = models.DecimalField(max_digits=10, decimal_places=2) In the same model file, I use the MeatMenu model as a fk to allow users to buy the meat they want (can calc total cost using price [hence the need for a fk as opposed to direct model choices]) class BuyMeat(models.Model): client = models.ForeignKey(User, on_delete=models.CASCADE) meat_needed = models.ForeignKey(MeatMenu, on_delete=models.SET_NULL, blank=True, null=True) date_created = models.DateTimeField(default=timezone.now) class Meta: ordering = ('-date_created',) def __str__(self): return str(self.meat_needed) FORMS.PY In my form, I'm trying to have a user execute an order for the meat they want as follows: class BuyMeatForm(forms.ModelForm): meat_needed = forms.ModelChoiceField(queryset=None, to_field_name='service_name', widget=forms.RadioSelect, empty_label=None) class Meta: model = BuyMeat fields = '__all__' exclude = ('client', 'date_created') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['service_needed'].queryset = MeatMenu.objects.all() VIEWS.PY def buy_meat(request): if request.method == 'POST': form = BuyMeatForm(request.POST) if form.is_valid(): new_purchase = form.save(commit=False) new_purchase.client = request.user new_purchase.date_created = timezone.now() new_purchase.save() else: form = BuyMeatForm() context = {'buy_form': form} .................... PROBLEM The problem comes in customizing my "meat_needed" field in the form. As you can see in my forms.py file, I would like to customize the foreignkey dropdown-select into radio buttons whereby … -
Django static files not served with Docker
please find below my app architecture. static files are located at /my_project/app/static/ when i 'jump' into my web container docker exec -it my_project sh /usr/src/app/static folder do not contain static files I guess problem is path to serve static files but what is wrong with my configuration? - my_project |_app |_core |_wsqi.py |_settings |_base.py |_dev.py |_prod.py |_urls.py |_requirements |_static |_base.txt |_dev.txt |_prod.txt |_Dockerfile.prod |_entrypoint.prod.sh |_manage.py |_.dockerignore |_nginx |_Dockerfile |_nginx.conf |_.env.prod |_.gitignore |_docker-compose.prod.yml prod.py SITE_ID = 1 STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static") MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") docker-compose.prod.yml version: '3.7' services: web: restart: always build: context: ./app dockerfile: Dockerfile.prod restart: always command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 volumes: - ./app:/usr/src/app - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media expose: - 8000 env_file: - ./.env.prod extra_hosts: - "db:192........" nginx: build: ./nginx restart: always volumes: - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media ports: - 1338:80 depends_on: - web volumes: static_volume: media_volume: nginx.conf upstream app { server web:8000; } server { listen 80; server_name localhost; location / { proxy_pass http://app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /usr/src/app/static/; } location /media/ { alias /usr/src/app/media/; } } -
Rest Framework Ordering Filter for Models Method
I have a model that has method for calculating average rating. How can I add this method to ordering filter fields? I tried to do custom filter with FilterSet but I cannot manage to do that. I received error when I tested my attempts. There are no any example for Order Filtering. I added a filter for average rating with greater than lookup as it is shared below but I couldnt way to add it for order filtering. Model Class: class Establishment(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=255, null= False, blank = False, unique=True) description = models.TextField(max_length=360, blank = True, null=True) address = models.TextField(max_length=360, blank = True, null=True) phone = PhoneNumberField(null=False, blank=False) city = models.CharField(max_length=15, null= False, blank = False) district = models.CharField(max_length=50, null= False, blank = False) latitude = models.DecimalField(max_digits=9, decimal_places=6, null=False, blank=False) longitude = models.DecimalField(max_digits=9, decimal_places=6, null=False, blank=False) cuisine = models.CharField(max_length=255, null= False, blank = False) zipcode = models.IntegerField(null=True, blank=True) average_price = models.IntegerField(blank = True, null=True) profile_photo = models.ImageField(blank=True, null=True, upload_to=upload_path('profile_image')) def no_of_ratings(self): ratings = EstablishmentRating.objects.filter(establishment=self) return len(ratings) def average_rating(self): ratings = EstablishmentRating.objects.filter(establishment=self) return sum(rate.rating for rate in ratings) / (len(ratings) or 1) def __str__(self): return self.name Related ViewSet: class EstablishmentViewSet(viewsets.ModelViewSet): queryset = Establishment.objects.all() serializer_class = EstablishmentSerializer … -
Django Dump Json Data for recommended recipes
Hi everyone I'm looking for help on how to accomplish this. I'm building a Rest API and want to dump an existing db table filled with recipes. this table can be search by users and have recipes selected from the table. Can this be done? is there a command to dump a existing db to json data? I know django will auto create the models, do i then just have to write the serializer and views to search this data and have an authenticated user be able to add a recipe from this to their own list? NOT LOOKING FOR CODE BEYOND SIMPLE COMMANDS. Looking for advice on how to accomplish this? Thanks -
Pop-up message after submiting a form in django
I'm building a website with django, and I have the newsletter functionality. I'm not so good on the frontend but I want to implement a toggle message after the submit button is clicked. I'm not sure how am I suppose to handle this. I've connected the newsletter form with the pop-up message, but the problem is that when the submit is clicked the page is reloaded because of the view function, I tried to not return a redirect but in this case and in the first with the redirect function it doesn't display me the message. the view function def newsletter_subscribe(request): if NewsletterUser.objects.filter(email=request.POST['newsletter_email']).exists(): messages.warning( request, 'This email is already subscribed in our system') else: NewsletterUser.objects.create(email=request.POST['newsletter_email']) messages.success(request, 'Your email was subscribed in our system, you\'ll hear from us as soon as possible !') return redirect('index') newsletter form <section class="bg-gray section-padding"> <div class="container"> <div class="section-intro pb-5 mb-xl-2 text-center"> <h2 class="mb-4">Subscribe To Get Our Newsletter</h2> <p>We post very often on the blog and bring updates on the platform, if you will subscribe you will hear from us everything as soon we made the changes</p> </div> <form class="form-subscribe" action="{% url 'newsletter-subscribe' %}" method="POST"> {% csrf_token %} <div class="input-group align-items-center"> <input type="text" class="form-control" name="newsletter_email" placeholder="Enter … -
How to build a registration and login api using function based views in django rest framework?
I want to create a token authenticated registration and login api using django's built in User model with django rest framework(DRF) using function based views (FBV). Most of the articles which I found in the web are for class based views and there are not much resources available for FBV in the web. From whatever resources including CBV I found in the net, I coded this, # project/settings.py INSTALLED_APPS = [ ... 'rest_framework.authtoken' ] # app/serializers.py from django.contrib.auth.models import User class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user class LoginSerializer(serializers.ModelSerializer): # TO DO # app/views.py @api_view(['POST'],) def register(request): if request.method == 'POST': register_serializer = RegisterSerializer(data=request.data) if register_serializer.is_valid(): print("Its working") return Response({'Failed':'Failed to create'}) @api_view(['POST'],) def login(request): if request.method == 'POST': login_serializer = # TO DO if login_serializer.is_valid(): print("Its working") return Response({'Failed':'Failed to login'}) # app/urls.py urlpatterns = [ path('register/', views.register, name="register"), path('login/', views.login, name="login"), ] The above register and login are not complete and lacks a proper serilizers object and user creation/validation methods. I still tried to run the above code with this post request {id:,username:"user1", email:"email@email.com",password:"password123"}, id was kept … -
I need help regarding structuring django models and quering them with ease
please I need your help with this: I am building a Django web App that will count the total number of persons entering and exiting a school library in a day, week and year and then save to DB. The Web App uses a camera that is controlled by OpenCv to show live feed on frontend (I have successfully implemented this already). My problem is: How can I design and structure my models to store each data by day, week, month and year? And how can I query them to display them on different Bar Charts using chart.js? Thanks.