Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framwork allow only to my android application
I am using rest_framework and allowing CORS_ORIGIN_ALLOW_ALL = True. Is there any way I can restrict my rest APIs to work only in my android application. I am using django-simplejwt for authentication. In the browser or postman, the view should be different. Is there any way I can do this? -
Django check if form field is not empty
I'm working on a function when the customer enters the scheduled date and updates the form, the status of the form should change to Scheduled.My function is not working with if order.scheduled_date is not None: statement. views.py def update_order(request, pk): order = Order.objects.filter(id=pk).first() form = OrderForm(request.POST or None, user=request.user,instance=order) if request.method == 'POST': form = OrderForm(request.POST or None, user=request.user,instance=order) order.updated_by = request.user order.date_updated = timezone.now() if order.scheduled_date is not None: order.status = 'Scheduled' order.save() if form.is_valid(): form.save() return redirect('/orderlist/') context = {'form':form} t_form = render_to_string('update_form.html', context, request=request, ) return JsonResponse({'t_form': t_form}) class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) address = models.CharField(max_length=100) scheduled_date = models.DateField(max_length=100, null=True) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ('Ready to ship', 'Ready to ship'), ('Shipped','Shipped'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") -
Why Does This 'is' Comparison Fail
Why does this test fail? I am logged in as the same Father that the Child has a foreign key to. class Child(models.Model): user = models.OneToOneField(User) father = models.ForeignKey(Father) object = get_object_or_404(Child, id=id) if request.user is object.father: print("Yes") Thank you. -
How to have a follower count on django
I have been working on a follow system like in instagram in which a user can follow and unfollow other users, also a profile has to display the number of followers the selected user has and the number of people that user is following. Everything is working fine except for the followers count which is not displaying any number rather than 0 which is the default even tho the user has one or more followers. How can a count function be added to this django project? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png') bio = models.CharField(max_length=400, default=1, null=True) connection = models.CharField(max_length = 100, blank=True) follower = models.IntegerField(default=0) following = models.IntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' class Following(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed = models.ManyToManyField(User, related_name="followed") follower = models.ManyToManyField(User, related_name="follower") @classmethod def follow(cls, user, another_account): obj, create = cls.objects.get_or_create(user = user) obj.followed.add(another_account) print("followed") @classmethod def unfollow(cls, user, another_account): obj, create = cls.objects.get_or_create(user = user) obj.followed.remove(another_account) print("unfollowed") def __str__(self): return f'{self.user.username} Profile' views.py def profile(request, username=None): profile, created = Profile.objects.get_or_create(user=request.user) user = User.objects.filter(username=username) if user: post_owner = get_object_or_404(User, username=username) profile_bio = Profile.objects.filter(user_id=post_owner) user_posts = Post.objects.filter(user_id=post_owner) user = user[0] is_following = Following.objects.filter(user=request.user, followed=user) following_obj = Following.objects.get(user=user) follower … -
How to update Order Status in Template if changed by Admin
Hi I have a beginners question I have an e-commerce project and I have BooleanField with different status for the orders. I want to be able to show user the Order Status after being changed from the admin. Here is the models.py class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, blank=True, null=True) ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem) ordered_date = models.DateTimeField() out_for_delivery = models.BooleanField(default=False) received = models.BooleanField(default=False) Here is the template: {% for order in orders %} Order Reference: {{order.ref_code}} <br> Ordered on: {{order.ordered_date}}<br> Order Status: {% if order is out_for_delivery %} Order is out for delivery {% else if order is received %} Order is received {% endif %} {% endfor %} here is the views.py class OrderList(LoginRequiredMixin, ListView): model = Order template_name = "user_orders.html" context_object_name = 'orders' paginate_by = 2 ordering = ['-ordered_date'] queryset = Order.objects.filter(ordered=True).order_by('-ordered_date') def get_queryset(self): return Order.objects.filter(user=self.request.user, ordered=True).order_by('-ordered_date') Thank you all -
Django: Can I translation with variables inside in views
I'm trying to use variables with from django.utils.translation import gettext_lazy I wrote this code. However it didn't work. from django.utils.translation import gettext_lazy as _ name = "Bob" _(f"Hello {name}")) My environment is Python 3.7 How can I use variables in gettext_lazy? -
Django simple jwt to record all user activities along with its ip
I am using django-rest-framework-simplejwt for my application. I want to record each and every user activities along with there IP address for security aspects. https://github.com/SimpleJWT/django-rest-framework-simplejwt I want to store the records in database not in log file. Is there any way I can implement it. -
Field for Order in Django Model
I have a model called Employee: Employee: Name: CharField Email: EmailField Age: IntegerField Ranking: IntegerField My problem comes with the Ranking field. The Ranking field is supposed to determine an order for the employees, which I determine based on how much work they do. I set this value in Django admin. The problem is that if I add an employee and I put them at Ranking = 2, I have to adjust every single other employee's Ranking after 2. Does this make sense. How can I avoid this? Thanks! -
New Django virtual environment shows modules previously installed on system
I have started a new Django project and created a virtual environment. After creating this virtual environment I used the pip freeze command to verify that no modules had been installed within it. However, I found that all of the modules that I have previously installed in my system are now within my new virtual environment. Obviously they aren't supposed to be there.. Where did I go wrong I followed this websites instructions exactly: https://realpython.com/django-setup/ Thank you to anyone who is willing to help. -
Django migrations are not migrating at all
class Charity(models.Model): name = models.CharField(max_length=50, null=True, unique=True) pictureurl = models.URLField(max_length=500, null=True) description = models.CharField(max_length=100, null=True) tags = models.ManyToManyField(CharityTag) def __str__(self): return f"{self.name}, {self.pictureurl},{self.description}, {self.tags}" class Donor(models.Model): first = models.CharField(max_length=50, null=True) last = models.CharField(max_length=50, null=True) recc = models.ForeignKey(Charity, null=True, on_delete=models.SET_NULL) frequency = models.IntegerField(null=True) def __str__(self): return f"{self.first}, {self.last}, {self.recc}, {self.frequency}" So I have made a couple of models like these. I did python manage.py makemigrations and all i get is ModuleNotFoundError: No module named 'donationss' I am CD into the Startproject directory, not the Startapp one In the settings in Installed_Apps i put 'donationss.apps.DonationssConfig', I have upgraded pip and django and the migrates still don't happen. Never had this issue. -
Follow / Unfollow button on django template
I have a django follow system in which a user can follow other users and also unfollow them such like in instagram. In order to follow a user, the person has to visit someone's profile and press the follow button, if the user already follows that person then the user can press the unfollow button. Also in a profile there is a follower count whcih displays the number of followers a user has and a following count that displays the number of users that user is following(again like in instagram). Well everything was almost done and I was just missing the follower count in which I added a signals.py file to do it. When that file was finished I realized that now the buttons are not working because when the user presses the follow button it doesnt follow the user. What can I do to make this buttons do their job which is follow and unfollow people? please any idea helps. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png') bio = models.CharField(max_length=400, default=1, null=True) connection = models.CharField(max_length = 100, blank=True) follower = models.IntegerField(default=0) following = models.IntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' class Following(models.Model): user = … -
Extra action in Django rest framework returning not found
I'm trying to add extra actions to an existing system, but when I call that endpoint I get the following error: Page not found at /api/user/5/mood Here is the code: views.py class UserListAPIView(ListAPIView): permission_classes = [] serializer_class = UserSerializer # pagination_class = PostLimitOffsetPagination def get_queryset(self, *args, **kwargs): queryset_list = User.objects.all() page_size = 'page_size' if self.request.GET.get(page_size): pagination.PageNumberPagination.page_size = self.request.GET.get(page_size) else: pagination.PageNumberPagination.page_size = 10 query = self.request.GET.get('q') if query: queryset_list = queryset_list.filter( Q(email__icontains=query) | Q(username__icontains=query) ) return queryset_list.order_by('-id') @action(detail=True, methods=['get']) def mood(self, request, pk=None): return Response({'mood': '1'}) url.py from django.urls import path from .views import ( UserListAPIView, UserCreateAPIView, UserDetailAPIView, UserDeleteAPIView, UpdateAPIView ) urlpatterns = [ path('', UserListAPIView.as_view(), name='user-list'), path('create', UserCreateAPIView.as_view(), name='user-creator'), path('profile/<int:pk>/', UserDetailAPIView.as_view(), name='user-profile'), path('delete/<int:pk>/', UserDeleteAPIView.as_view(), name='user-destroyer'), ] -
How to trace circular import error Django never solved
I am working Django rest framework api project, where I had multiple apps in the project. I got a circular import error when I am adding the app URLs to the main URLs. I Tried everything checked spellings, checked app structure but no use. Its been really frustrating with issue..please help to solve the problem. The app is working fine when I take off newly added line path("covid/", include("Covid.urls")), I am using python3.6, django 3.0.4 and django-rest-framework 3.11.0 Here is project urls.py from django.contrib import admin from django.conf.urls import url from django.urls import path, include from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='TmmrwInc API Documentation') urlpatterns = [ path('admin/', admin.site.urls), # path('', include('django.contrib.auth.urls')), # path('rest_auth/', include('rest_auth.urls')), path('api/password_reset/', include('django_rest_passwordreset.urls', namespace='password_reset')), # url(r'^invitations/', include('invitations.urls', namespace='invitations')), path('', include('rest_invitations.urls')), path("", include("UserAuth.urls")), path("doctors/", include("Administration.urls")), path("appointments/", include("Appointments.urls")), path("messaging/", include("messaging.urls")), path("meet/", include("meet.urls")), path("api_documentation/", schema_view), path("covid/", include("Covid.urls")), ] This is app urls.py file from django.urls import path from . import views app_name = 'Covid' urlpatterns = [ path('event/', views.EventBookingView.as_view()), ] settings.py installed apps ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.sites", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "UserAuth", "rest_framework", "corsheaders", 'rest_framework.authtoken', 'rest_auth', 'Appointments', 'messaging', 'Administration', 'channels', 'invitations', 'rest_invitations', 'django_rest_passwordreset', 'django_celery_beat', 'meet', 'rest_framework_swagger', 'Covid', ] This is a … -
How to get 2 respondents to answer a survey simultaneously while using session in Django?
I want to store data of multiple respondents of a Django survey in a session, so that I can later save the data. If one respondent answers the survey, I can easily store the data with request.session['age'] = form.cleaned_data['age'] saving_all = survey.objects.create( age=request.session['age'], ) saving_all.save() However, I am collecting the input data (age, gender, etc.) on multiple urls and at the end, I create survey objects and save the data. But if another respondent answers the survey simultaneously, then the data which is stored in request.session is overwritten. How can I create individual sessions, so that multiple respondents can participate in the survey simultaneously? One of my functions looks like that: def home(request): # Trying to create multiple/unique sessions here global user_id user_id = random.randint(0,10000) # this was added because someone suggested it as a solution. However, I dont understand it 100%, especially what initial does request.session['user_id'] = user_id initial={user_id:request.session.get(user_id, None)} # SURVEY form = SurveyForm(request.POST or None, initial=initial) if request.method == 'POST': # Save input data in session if form.is_valid(): request.session['age'] = form.cleaned_data['age'] request.session['gender'] = form.cleaned_data['gender'] request.session['education'] = form.cleaned_data['education'] request.session['alternative1'] = 0 request.session['alternative2'] = 0 request.session['alternative3'] = 0 request.session['alternative4'] = 0 request.session['alternative5'] = 0 request.session['alternative6'] = 0 request.session['alternative7'] = … -
Graphene Django with Django_Filters - Filterset on field outside of model. Do I need to refactor with ContentType?
I'd like to describe my current setup before asking any questions. I have the following classes: class MyExampleType(DjangoObjectType): class Meta: model = Models.MyExample interfaces = (Node,) filterset_class = MyExampleFilter class MyExampleFilter(django_filters.FilterSet): # various 'in' filters example_field__In = django_filters.BaseInFilter(field_name'example_field', lookup_expr='in') class Meta: model = MyExample fields = { # various field names as keys, lookup expressions in list as their value "example_field": ["exact", "in"], } Lastly, I have the root Query class of the app: import graphene_django_optimizer as gql_optimizer class Query(ObjectType): my_example = DjangoFilterConnectionField(MyExampleType) def resolve_my_example(self, info, **kwargs): return gql_optimizer.query(Models.MyExample.objects.all(), info) I have multiple foreign keys that are defined in MyExample model class, and I've had no trouble with using double underscore relation traversing in order to filter upon values in related tables. The issue that has come up is that now I need to use one of the Models.ForeignKey fields of MyExample in order to reach other tables. Through my searches I've found that some suggest rewriting models to use the Django ContentTypes in order to allow the use of GenericForeignKey, I think. Though, I also read that it somehow limits or disables the ability to filter that model based on the generic foreign key. Is that right? My main … -
What is the general structure for a realtime news web app using Django, channels, celery, a message queue system and a mySQL database?
I am working on building a financial web application that provides realtime news as well as several other features such as realtime or near-realtime stock info. I'm having problems conceptualizing the architecture of a program that would do the following: scrape news/other data from several websites at regular intervals upload the scraped data to an SQL database (AWS RDS MySQL) push the data via SSE/Django channels My question is how do celery, AWS SQS, and channels fit into all this? I understand what each service does individually but I have trouble putting them together. In other words, how does a web app like Robinhood which utilizes Django, celery, and Rabbitmq put these services together to have realtime stock charts but at the same time realtime newsfeed? I'm having trouble finding resources online that discuss this kind of architecture. I realize that my method of getting the data via webscraping is not realtime but the idea would be to push an update as soon as the data is scraped every arbitrary number of minutes. Also I understand that a lot of web apps today utilize microservices architecture so how would the above scenario work if for example the news and stock … -
What causes pylint import errors
Please what happens if you set your virtual environment after starting your application with django. Can that result to pylint import error -
How To Get My inlineformset_factory Working
I have many Tests, each Test has three Results. They can be pass or fail. On one page I will display a number of Tests, each with it's three related Results so Users can select the related checkbox if they pass. I believe I should use inlineformset_factory. Below are my two most logical (I think) attempts, neither of which work. The first one I expect should work, returning a formset of all Results belonging to all Tests of the current User, however I get queryset contains no pk error. For the next attempt I was trying to build a formset of the three Results of just a single Test. This doesn't throw an error, but prints 4 (not 3) checkboxes with seemingly random values. class Test(models.Model): user = models.ForeignKey(Users, related_name='test') # three of these are created and attached to a Test, result_number: 1,2,3 class Result(models.Model): test = models.ForeignKey(Test, related_name='result') result_number = models.CharField() pass_fail = models.BooleanField() initial_form_set = inlineformset_factory(Test, Result, fields=('result_number', 'pass_fail'), form=ResultForm) # this one causes error: queryset contains no pk #result_formset = initial_form_set(instance=Test.objects.filter(user_id=user.id)) # this one returns checkboxes not reflective of this Test's Result's checkboxes #result_formset = initial_form_set(instance=Test.objects.get(id=287)) Thank you. -
Is there a way to query reverse in django models?
I know this question has been answered in different ways but i'm still unable to see the clear picture. I have the following tables with following relationships: class Category(models.Model): name = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return self.name class SubCategory(models.Model): sub_name = models.CharField(max_length=100, null=False, blank=True, default='None') category = models.ManyToManyField(Category, default=1) class Product(models.Model): name = models.CharField(max_length=150, null=False, blank=False) brand = models.CharField(max_length=100, null=False, blank=False) price = models.FloatField(null=False, blank=False) weight = models.CharField(max_length=100,null=False, blank=False) sub_category = models.ForeignKey(SubCategory, on_delete=models.SET_DEFAULT, default=13) category = models.ForeignKey(Category, on_delete= models.CASCADE) I am trying to solve two queries as follows: Fetch all the category and subcategories to a specific category where the brand is given. Display structure that i'm making is Brand(Men->Shirts,Pants etc. Women->Shirts,Pants etc). NOTE: Each brand can sell products of multiple categories and subcategories. Fetch all the subcategories where the category name must be taken out from the result of Category.objects.all(). Display structure that i'm making here is Men(its sub categories) , Women(its sub categories) -
Signals.py file not being recognized in django
I am working on follow/unfollow system and I need to add a signals.py file to make the follower count workl, but after I started investigating, I realized that the signals.py file was not being called because it is not on the pycache folder of the app. What can I do to make this file be recognized by django?? If you need to see more code or have any questions please let me know in the comments;) -
Django , models object not displayed in views
im newbie in django. I have some question related to models. So, i was trying to display the model name and date to the views by iterating to all of them. But somehow they dont show up in the views, i tried to search in google but none fixed my problem. Im sorry if i asked some ridiculous question, but here is my code. And also i already checked my models and theyre valid Models from django.db import models from django.utils import timezone from django.utils.text import slugify class Post(models.Model): title = models.CharField(max_length=30) body = models.TextField() time_post = models.DateTimeField(auto_now_add=True) time_edit = models.DateTimeField(editable=False,blank = True) slug = models.SlugField(editable=False, blank=True) def save(self): self.slug = slugify(self.title) self.time_edit = timezone.now() super(Post, self).save() def __str__(self): return "{}. {}".format(self.id, self.title) urls from django.shortcuts import render from .models import Post def blog(request): posts = Post.objects.all(), context = { 'title':'Blog ', 'contributor':'Chris', 'img':'blog/img/BlogBanner.jpg', 'Post':posts, 'nav': [ ['/blog/recent','Recent'], ['/blog/news','News'], ['/blog','Blog'], ['/about','About'], ['/', 'Index'] ] } return render(request,'blog/blog.html',context) My blog.html {% extends "base.html" %} {% load static %} {% block app_css %} <!-- Custom CSS per app !--> <link rel="stylesheet" types="text/css" href = "{% static "blog/css/styleblog.css" %}"> <!-- CSS OVERIDE !--> {% endblock app_css %} {% block header %} <h1 class="display-4">Welcome … -
Django How do you pass a field attribute after the __init__ function
i would like to pass this: client_satisfaction = forms.DecimalField(widget=forms.NumberInput( attrs={ 'type':'range', 'class':'form-control-range', 'step': '1', 'min': '1', 'max': variable}), label='Client Satisfaction', required=False) After this: def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) pk_num_project = User.objects.filter(pk = user.id) company_objective = CompanyObjectives.objects.get(user_rel_objectives=user.id) super(ProcessForm, self).__init__(*args, **kwargs) Currently, in my forms I have the first client_satisfaction then I do def init how can inverse this. I want to do this because I am running a query that is finding the results and putting it into a variable. so I need to run the query first and then put it into my variable. Any ideas, I am new to Django so it it makes little sense plz let me know or point me in the right direction -
django template and vews functions
how can I pass a list of items into a template in my views: from django.shortcuts import render, render_to_response from django.http import HttpResponse from django.template import loader from django.views.decorators.csrf import csrf_exempt from .models import Question from .forms import usersData1, usersData2, usersData3 def start_pr(response): name = ["Name","Phone Number","Email"] form = usersData1() return render_to_response(response, "start_pr/start.html", {"form":form}, {"name":name}) in my HTML: {% block content %} <form action="/start/" method="post"> <legend> {%for items in form %} {% for obj in name %} <p> {{ obj }} </p> {% endfor %} <input type="text" name="name" maxlength="20" required="" id="id_name" placeholder="{{items.name}}"> <br> {% endfor %} <a href="#">next</a> </legend> </form> {% endblock %} in my forms: from Django import forms class usersData1(forms.Form): name= forms.CharField(label="name", max_length=20) phoneNum= forms.IntegerField(label="phoneNum") email= forms.EmailField(label="email", max_length=50) the list is in my views as name. i have used {% for obj in name %}<p>{{obj}}</p> when I go to localhost:8000 it shows an HTML form as the out product. witch is weird(like opening up google view page sources when right-clicked ). im also new to Django but know how to make views and link them and most of the basics. what I don't know is this {%%} what is that called, where can I find documentation on the … -
Add module to django admin panel
enter image description here I have a problem when importing a personal module to the django administration panel admin.py from django.contrib import admin from facturas.models import Factura # Register your models here. admin.site.register(Factura) models.py from django.db import models from django.db.models import UUIDField, IntegerField, CharField, EmailField, DateTimeField from django.utils import timezone class Factura(models.Model): # id_asi = models.UUIDField(primary_key=True) #campo interno para consulta en la base de datos ambiente = models.CharField(max_length=1) tipoEmision = models.CharField(max_length=1) razonSocial = models.CharField(max_length=300) nombreComercial = models.CharField(max_length=300) .serializers.py from rest_framework import serializers from facturas.models import Factura #agregado de campos necesarios para una factura class FacturaSerializer(serializers.ModelSerializer): class Meta: model = Factura fields = '__all__' When I am in the admin panel of django i can only add the module but not modify -
Artificially limit memory available for celery worker
I have a (what I think fairly standard) setup with a Django server + redis + celery. Depending on the task being delegated to the celery worker, sometimes I get: [2020-07-21 19:58:17,401: ERROR/MainProcess] Process 'ForkPoolWorker-1' pid:31695 exited with 'signal 9 (SIGKILL)' [2020-07-21 19:58:17,469: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: signal 9 (SIGKILL).',) Traceback (most recent call last): File "/path/to/venv/lib/python3.6/site-packages/billiard/pool.py", line 1267, in mark_as_worker_lost human_status(exitcode)), billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 9 (SIGKILL). From what I can tell, the worker is being killed because the system ran out of memory. I would like to be able to simulate that problem in a testing environment. How can I artificially limit the memory available to a celery worker (or all workers) or simulate a worker exiting this way?