Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError sayins module dot not exist, but is already installed
I had to install new package on my project to handle with Base64 images from my API, so i installed django-extra-fields, so far so good, i have made my testes locally, everything working just fine, when i pushed my changes to production and installed the new package running pip install django-extra-fields with right virtualenv on, i just keep getting the error ImportError at / No module named drf_extra_fields.fields That seens a silly mistake, so i checked my code like 100 times so far, and everything is right I'm using Django 1.11 with Python 2.7 My vm is called: vm-prod_cfr_nuvem When i run pip freeze show all my packages: (vm-prod_cfr_nuvem) [~ site-packages]$ pip freeze Django==1.11.6 django-cors-headers==2.1.0 **django-extra-fields==2.0.2** django-filter==1.1.0 And if i enter in vm site-packages path, i can see that is installed there /home/daniloitj/.virtualenvs/vm-prod_cfr_nuvem/lib/python2.7/site-packages django_cors_headers-2.1.0.dist-info **django_extra_fields-2.0.2.dist-info** django_filter-1.1.0.dist-info on my view where the show the error, as you can see, is the same path as the last one in list ImportError at / No module named drf_extra_fields.fields ... Python Path: ['/home/daniloitj/webapps/cfr_prod/lib/python2.7/Django-1.11.9-py2.7.egg', '/home/daniloitj/webapps/cfr_prod', '/home/daniloitj/webapps/cfr_prod/cfr_nuvem', '/home/daniloitj/webapps/cfr_prod/lib/python2.7', '/home/daniloitj/lib/python2.7', '/home/daniloitj/lib/python2.7', '/home/daniloitj/.virtualenvs/vm-prod_cfr_nuvem/lib64/python27.zip', '/home/daniloitj/.virtualenvs/vm-prod_cfr_nuvem/lib64/python2.7', '/home/daniloitj/.virtualenvs/vm-prod_cfr_nuvem/lib64/python2.7/plat-linux2', '/home/daniloitj/.virtualenvs/vm-prod_cfr_nuvem/lib64/python2.7/lib-tk', '/home/daniloitj/.virtualenvs/vm-prod_cfr_nuvem/lib64/python2.7/lib-old', '/home/daniloitj/.virtualenvs/vm-prod_cfr_nuvem/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7', '/usr/lib/python2.7', '/usr/lib64/python2.7/lib-tk', '/home/daniloitj/.virtualenvs/vm-prod_cfr_nuvem/lib/python2.7/site-packages'] Obs.: I thought that somehow my server is not using my VM or something like it... … -
when i use django-allauth,the website homepage is blocked. How to customize the configuration page block
enter image description here when i use django-allauth,the website homepage is blocked. How to customize the configuration page block -
The Cpanel framework is showing the deployed website source code
This is my first to deal with Cpanel with Django. I uploaded files of my web site in Django using the Cpanel framework. I am getting the Django source code of the index.html file such {% csrf_token'%} and {{ form.as_p}} while launching the app. Note that this index page is located in the public_html folder. The views.py, urls.py, and form.py are located in the App folder. And the other HTML pages are located in another folder in the App folder. So, how to solve this issue, please? Please assist me -
How to return JWT token after user created in Django?
I am using Model Serializer and I want to return JWT Token after the user is created. Is there any way of doing it? Thanks in advance class UserSerializer(ModelSerializer): """Serializers for User objects""" class Meta: model = get_user_model() fields = ('email', 'password') extra_kwargs = {'password': {'write_only': True, 'min_length': 5, 'style': { 'input_type': 'password' }}} def create(self, validated_data): """Create a new user with encrypter password""" user = get_user_model().objects.create_user(**validated_data) return user -
How to call a view function on button click in template in django?
I have a form in which there is a button . I want to call a view function named def recognize(): in my views.py but after clicking the page should not reload and the values filled in the inputs before the button should not be cleared. TEMPLATE FILE <form> <div class="form-row"> <div class="form-group col-md-6"> <label for="first_name">First Name</label> <input type="text" name="first_name" class="form-control" id="first_name" required/> </div> <div class="form-group col-md-6"> <label for="last_name">Last Name</label> <input type="text" name="last_name" class="form-control" id="last_name" required/> </div> </div> <button type="button" class="mybtn">Open Camera</button> // THIS IS THE BUTTON TO BE CLICKED <button type="submit" class="btn btn-danger">Submit</button> </form> VIEWS.PY (hiding extra details) def recognize(request): size = 4 haar_file = 'C:\\Users\\Aayush\\ev_manage\\face_detector\\haarcascade_frontalface_default.xml' datasets = 'C:\\Users\\Aayush\\ev_manage\\face_detector\\datasets' while True: (_, im) = webcam.read() gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2) face = gray[y:y + h, x:x + w] face_resize = cv2.resize(face, (width, height)) # Try to recognize the face prediction = model.predict(face_resize) cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 3) if prediction[1] < 90: cv2.putText(im, '% s - %.0f' % (names[prediction[0]], prediction[1]), (x - 10, y - 10), cv2.FONT_HERSHEY_PLAIN, 1, … -
Model form not being saved
I have created a modelform and would like to save the data when a user enters values in the template and clicks submit. I have tried following a tutorial to guide me. However, the form doesn't seem to be saving nor am I being redirected to the template I specified This is what I have on views.py class PaymentView(TemplateView): template_name = 'classroom/teachers/app-student-dashboard.html' def get(self, request): paymentform = MentorPaymentForm() return render(request, self.template_name, {'paymentform':paymentform}) def post(self, request): paymentform = MentorPaymentForm(request.POST) if paymentform.is_valid: payment = paymentform.save(commit=False) payment.user = request.user payment.save() address = paymentform.cleaned_data['address'] country = paymentform.cleaned_data['country'] invoice_name = paymentform.cleaned_data['invoice_name'] account_num = paymentform.cleaned_data['account_num'] bank_name = paymentform.cleaned_data['bank_name'] branch_code = paymentform.cleaned_data['branch_code'] paymentform = MentorPaymentForm() return redirect('teachers:app-instructor-dashboard') args = {'paymentform': paymentform, 'address': address, 'country': country, 'invoice_name': invoice_name, 'account_num': account_num, 'bank_name': bank_name, 'branch_code': branch_code} return render(request, self.template_name, args) forms.py class MentorPaymentForm(forms.ModelForm): class Meta: model = Mentor fields = ('address', 'country', 'invoice_name', 'account_num', 'bank_name', 'branch_code') models.py: class Mentor(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='mentor') COUNTRIES = ( ('SA', 'South Africa'), ('NG', 'Nigeria'), ('KE', 'Kenya'), ('OT', 'Other') ) address = models.CharField(max_length=500, null=True, blank=True) country = models.CharField(max_length=30, choices=COUNTRIES) invoice_name = models.CharField(max_length=200, null=False, blank=False) account_num = models.IntegerField(default=1234) bank_name = models.CharField(max_length=50, null=False) branch_code = models.IntegerField(default=1234) and my template: <form id="edit-payment-details", method="post",enctype="multipart/form-data" class="form-horizontal"> {% csrf_token … -
Python manage.py runserver admin page
i am working on the django tutorial polls app. I have done all the other parts and now on the last bit of part 7, where am modifying the admin page. I have all the codes as correctly undersigned from the documentation, but when i load the server admin page, from the terminal i can see that it breaks then i get the error this site cant be reached. i have really gone through every part of the coding and made comparisons but everything seems fine. enter image description here enter image description here enter image description here enter image description here -
JSON Decode error : Expecting value: line 1 column 1 (char 0)
I am running a website using Django . views.py : def febs_events(request): range_yearly=0 range_monthly=0 msg=False r=range(0,0) respo =requests.get(url='https://www.onebookingsystem.com/productionApi/API/Admin/admin_dashboard.php') data_dash=json.loads(respo.text) payments=requests.get(url='https://www.onebookingsystem.com/productionApi/API/Admin/payment_dashboard.php') pay_data=json.loads(payments.text) yearly=requests.get(url='https://www.onebookingsystem.com/API/Admin/dashboard_yearly_earning.php') yearly_data=json.loads(yearly.text) When i run, i am getting the error as: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) This is the error line : yearly_data=json.loads(yearly.text) Any help? -
Assign an array of values to an empty HTML tag with JavaScript
I have some values in a table with the same tag name: {% for groups in groupList %} <tr> <td id="checkboxes"> <input type="checkbox" name="check" id="check_{{groups.GroupID}}"> </td> <tr> {% endfor %} However I want this data to be somewhere else so I can use it in a form for a POST request. Here is my form HTML: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <button type="submit" name="create"> Create Report for Selected Items </button> <input type="hidden" name="selected" value="" /> </form> I want to transfer the values from check into selected using JavaScript. Here's what I have so far: function getChecked() { var checked = document.getElementsByName("check"); var i = 0; for (a in checked) { document.getElementsByName("selected")[i].value = checked.value; i = i + 1; } } I've checked Google Chrome console and I'm getting this error: Uncaught TypeError: Cannot set property 'value' of undefined at getChecked (1:75) That highlights this line: document.getElementsByName("selected")[i].value = checked.value; I'm not sure where I'm going wrong here. Can anyone help me out? -
I want to implement a news aggreator on my site - django
I want an app on my django website that is capable of displaying articles from a given website. So far I have this: views.py import requests from django.shortcuts import render, redirect from bs4 import BeautifulSoup as BSoup from .models import Headline requests.packages.urllib3.disable_warnings() def news_list(request): headlines = Headline.objects.all()[::-1] context = { 'object_list': headlines, } return render(request, "news/home.html", context) def scrape(request): session = requests.Session() session.headers = {"User-Agent": "Googlebot/2.1 (+http://www.google.com/bot.html)"} url = "https://www.theonion.com/" content = session.get(url, verify=False).content soup = BSoup(content, "html.parser") News = soup.find_all('div', {"class":"curation-module__item"}) for artcile in News: main = artcile.find_all('a')[0] link = main['href'] image_src = str(main.find('img')['srcset']).split(" ")[-4] title = main['title'] new_headline = Headline() new_headline.title = title new_headline.url = link new_headline.image = image_src new_headline.save() return redirect("../") My models.py from django.conf import settings from django.db import models # Create your models here. # Scrape data coming from websites # The posts will contain images, urls and titles # model - headline(title, image, url) # model - userprofile(user, last_scrape) class Headline(models.Model): title = models.CharField(max_length=200) image = models.URLField(null=True, blank=True) url = models.TextField() def __str__(self): return self.title I have an html page too and urls.py set. When ever I try to request the articles, it gives this error SSLError at /news/scrape/ HTTPSConnectionPool(host='www.theonion.com', port=443): Max retries exceeded … -
Add extra field to queryset serializer
I have a list API view: class ListRequisitesOfEnrollee(generics.ListAPIView): serializer_class = RequisiteSerializer def get_queryset(self): enrollee = Enrollee.objects.get(id=self.kwargs['pk']) requisites = enrollee.requisites.all() if isinstance(enrollee, OrganisationUnit): requisites = requisites | enrollee.org.requisites.all() elif isinstance(enrollee, ElsUser): org_unit_requisites = enrollee.organisation_unit.requisites.all() org_requisites = enrollee.organisation_unit.org.requisites.all() groups = Enrollee.objects.filter(group__users=enrollee) for group in groups: requisites = requisites | group.requisites.all() requisites = requisites | org_unit_requisites | org_requisites return requisites I want to add an extra "source" field to the queryset on specific objects For example , inside isinstance(enrollee, OrganisationUnit) , requisites = requisites + enrollee.org.requisites.all() The enrollee.org.requisites.all() queryset must contain an extra field source ="Org Name". I want to avoid adding any extra fields to Table -
communication between javascript and python (django)
i try to exchange data between javascript and python. I am currently using AJAX. (is there anything better?) I think one of the problems is that the data exchange happens after a user logs in, so that django adjusts the paths. in the .js the Ajax command is as follows: $.ajax({ url:'bla', type: "POST", data: {stock : 42}, success:function(response){}, complete:function(){}, error:function (xhr, textStatus, thrownError){} }); and in urls.py it says: path(r'bla/', views.YourViewsHere, name='bla'), when I do that the server tells me a 404 error that it cannot find the page because the username is in the path. Therefore I have expanded the Ajax url with the app names: $.ajax({ url:'blub:bla', type: "POST", data: {stock : 42}, success:function(response){}, complete:function(){}, error:function (xhr, textStatus, thrownError){} }); now i don't even get an error message. the views look like: def YourViewsHere(request): print("bla") if request.method == 'GET': print("blub") elif request.method == 'POST': print(request.POST.get('data')) what am I missing? -
Already set STATIC_ROOT but get Heroku error "You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path."
I'm trying to deploy my Django app to Heroku. Python version 3.7 and Django 3.0.1. I've set STATIC_ROOT in my settings.py already and I tried locally run "python manage.py collectstatic --noinput" and it worked. But when I tried to deploy on Heroku, I still got the error: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 21, in <module> remote: main() remote: File "manage.py", line 17, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 113, in collect remote: handler(path, prefixed_path, storage) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file remote: if not self.delete_file(path, prefixed_path, source_storage): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file remote: if self.storage.exists(prefixed_path): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 311, in exists remote: return os.path.exists(self.path(name)) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 43, in path remote: raise ImproperlyConfigured("You're using the staticfiles app " remote: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT … -
How to center a Leaflet Map forms in a Django template
after 2 days trying to do it by myself, I need some help please I'm using GeoDjango and Leaflet. I have a model "listing" having a field location as PointField, my form uses LeafletWidget as per below. As it is, it is working but when I create a new listing, there is nothing in location, so it shows a default world map. I would like in my template to setup the following: CENTER: ({{ user.lat }}, {{ user.lng }}) and zoom: 10 since I know that the New listing will be in the same geographical area as the user. And I have NO idea how to do it!!! Model.py location = models.PointField(null=True, blank=True) forms.py from leaflet.forms.fields import PointField from leaflet.forms.widgets import LeafletWidget ... LEAFLET_WIDGET_ATTRS = { 'map_height': '600px', 'map_width': '50%', 'display_raw': 'true', 'map_srid': 4326, } ... class ListingForm(forms.ModelForm): required_css_class = 'required' ... location = forms.PointField( widget=LeafletWidget(attrs=LEAFLET_WIDGET_ATTRS)) ... template.html <!-- form start --> <form action="{% url 'listing_new' %}" method="POST" class="listing-form" role="form" novalidate enctype="multipart/form-data" id="listingform"> {% csrf_token %} <div class="box-body"> {{ form.non_field_errors }} {% for field in listingform %} <div class="fieldWrapper form-group {% if field.errors %} field_error{% endif %} "> <label for="{{ field.id_for_label }}"> {{ field.label }}{% if field.field.required %}<span class="required-asterisk">*</span>{% endif … -
Django 1.9 SubFieldBase has been deprecated
Good day I am in the process of upgrading my Django version. I am rather far back, and trying to do it 1 version at a time. I have come across a deprecation warning that I am unable to find a solution for. /lib/python3.6/site-packages/django/utils/six.py:808: RemovedInDjango110Warning: SubfieldBase has been deprecated. Use Field.from_db_value instead. return meta(name, bases, d) /lib/python3.6/site-packages/jsonfield/fields.py:130: RemovedInDjango110Warning: SubfieldBase has been deprecated. Use Field.from_db_value instead. class TypedJSONField(JSONField): Does anyone know how I can go about fixing this? -
How to filter the additional model in DetailView?
class Source(models.Model): Name = models.CharField(max_length=150)`enter code here` Address = models.CharField(max_length=150) Office_Phone = PhoneField(blank=True, help_text='Office phone number') Main_Contact = models.CharField(max_length=150, blank=True, null=True) Contact_Email = models.EmailField(max_length=254, blank=True, null=True) Contact_Phone = PhoneField(blank=True, help_text='Main Contact phone number') Billing_Contact = models.CharField(max_length=150, blank=True, null=True) Billing_Email = models.EmailField(max_length=254, blank=True, null=True) Billing_Phone = PhoneField(blank=True, help_text='Billing Contact phone number') Notes = models.CharField(max_length=250, blank=True, null=True) def __str__(self): return self.Name def get_absolute_url(self): return reverse('sources-detail', kwargs={'pk': self.pk}) class Rate(models.Model): Source = models.ForeignKey(Source, on_delete=models.CASCADE) Report_Type = models.ForeignKey(ReportType, on_delete=models.CASCADE) Amount = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) class SourceDetailView(DetailView): model = Source template_name = 'intake/source_detail.html' context_object_name = 'source' def get_context_data(self, *args, **kwargs): context = super(SourceDetailView, self).get_context_data(*args, **kwargs) context['rates'] = Rate.objects.all.filter(***not sure what to put here***) return context Would it be better to filter it in the Template or do it in the View? I am able to get results if I don't filter it and just use Rate.objects.all(), and then I filter it in my template. Just think there is a better way to do this. -
Reason of django memory leak?
I have debian 10 server with venv django. Also mysql is installed. Django -> nginx -> uwsgi. Top and ps aux shows nothing. I have 4GB of Ram, mysql eats 400MB, and 6 uwsgi workers with 50 MB for each. Used - 3400MB. In django I have requests to external remote database in views.py and displaying data: db = MySQLdb.connect(host="192.168.100.50", user="main", passwd="pwd", db="static", charset="utf8") cur = db.cursor() cur.callproc('data', (ID)) return render(request, 'test.html', {'data': data}) Django project is a website for working with this external db. -
How to display attendance status for a month from the database?
AM new to Django, currently am working on a school management system particularly on attendance module, In this module after daily roll call attendance of the teachers, their status in the TeachersAttedance table changes to either Present, Late or Absent. Am able to submit teacher attendance status of the day in the TeachersAttedance table in the model. The problem is now on how to retrieve this data and show it in a table format considering days of the month as the header in the table. Essentially I want to show the teachers attendance on each day in the table depending on which month the use selects. Currently, am finding a problem to finding the solution to this. here is my views.py def teacher_attendance_report(request): context = {} form = TeacherAttendanceForm(request.POST) if request.method == 'POST': if request.POST.get('group_by'): grab_data_passed = request.POST.get('group_by') #create caledar with days of the grabbed month z=0 range=32 days=[] if z< range: dats = TeacherAttendance.objects.filter(date__month=grab_data_passed)[z].date z+=1 y=dats.month x=dats.year cal = calendar.TextCalendar(calendar.WEDNESDAY) for day in cal.itermonthdays(x, y): days.append(day) context['days']=days teacher = User.objects.filter(is_teacher=True) get_attendance=TeacherAttendance.objects.filter(date__month=grab_data_passed) context['get_attendance']=get_attendance context['teachers'] = teacher return render(request, 'Reports/teacher_attendance_report_details.html', context) context={'form':form} return render(request, 'Reports/teacher_attendance_report_index.html', context) here is the teacher attendance table that am using. models.py class TeacherAttendance(models.Model): teacher = models.ForeignKey(Teacher, … -
Making django app_list avaible for all admin template
I am trying to override django admin template in other to create new layout using bootstrap4. I need to get app_list on every template of the admin to form the sidebar menu. So far I am able to create the menu for the landing page (admin/index.html) alone and not for the other pages ... Since the app_list tag is not available for them. Note the app_list is suppose to list all apps and models under them. -
How to add a metronic react theme to a django project
I am unable to integrate metronic admin theme to django project. Currently trying with django-webpack-loader, i am able to bundle files but when i render the template it is not able to find assets path. I verified STATIC_URL seems nothing wrong there. Any example would be really helpful. -
running a service in django and doing some things when a specific event happens
Using Django I want to receive some input from the user and then read a webpage and look for some specific data like a number and do this for unlimited times(reading the webpage not receiving input) and when there is a change in this number, based on the user's input I want to insert a record into a table. It's like a service that the user enables it giving some inputs, and the service gets running for unlimited times and it doesn't stop unless user stops it. Like in the first run there is a number on the webpage which is for example 2 and next time the service reads the webpage it's increased to 3 then it inserts value 3 into a local database and runs again and again. I don't know what technologies I must use and what exactly I have to do. -
Migration not reflecting on Heroku
Note: This questions has been asked before, but none of the answers provided worked for me. I deployed a django app on heroku and then made changes to my model after which i run migrations locally(python manage.py makemigrations and python manage.py migrate). The app works fine after the changes locally, but on the server, I run into the programming error below: django.db.utils.ProgrammingError: column "product_owner_id" of relation "cart_cartitem" does not exist. I run python manage.py migrate on the server, but I still get the same error. I also run python manage.py makemigrations on the server and it says No Changes detected. What I am doing wrong? Thank you -
Nested dictionary need to serialized in Django
I have Model with dictionary object, in below example want to set and get daily availability example Currently I am able to read, want to make this to read and write, what should I do for this "teacher_date": [ { "day_available": "MON", "time_available": "Morning" }, { "day_available": "SAT", "time_available": "Afternoon" }, { "day_available": "SUN", "time_available": "Evening" } Here is my model.py class Availability(models.Model): uid = models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True) MONDAY = 'MON' TUESDAY = 'TUE' WEDNESDAY = "WED" THURSDAY = "THU" FRIDAY = 'FRI' SATURDAY = "SAT" SUNDAY = "SUN" DAY = ( (MONDAY, 'Monday'), (TUESDAY, 'Tuesday'), (WEDNESDAY, 'Wednesday'), (THURSDAY, 'Thursday'), (FRIDAY, 'Friday'), (SATURDAY, 'Saturday'), (SUNDAY, 'Sunday'), ) day_available = models.CharField( max_length=3, choices=DAY, default=MONDAY) MORNING = 'Morning' NOON = 'AfterNoon' EVENING = 'Evening' TIME = ( (MORNING, 'Morning'), (NOON, 'Afternoon'), (EVENING, 'Evening'), ) time_available = models.CharField( max_length=30, choices=TIME, default=MORNING) def __str__(self): return f"{self.day_available} {self.time_available}" Here is my serializer.py file class AvailabilityDetails(serializers.ModelSerializer): class Meta: model = Availability fields = ('day_available', 'time_available',) class TeacherProfileDetails(serializers.ModelSerializer): logger = logging.getLogger(__name__) teacher_date = AvailabilityDetails(many=True, read_only=True) first_name = serializers.CharField(source='user.first_name', read_only=True) last_name = serializers.CharField(source='user.last_name', read_only=True) cities = serializers.SlugRelatedField(many=True, slug_field='city', queryset=City.objects.all(),) subject = serializers.SlugRelatedField(many=True, slug_field='subject', queryset=Subject.objects.all(),) teacher_date = AvailabilityDetails(many=True, read_only=True) user = UserDetailsSerializer(read_only=True) class Meta: model = Teacher fields … -
filtering data in many to many field using multiple filters and models in django
models .py class ShopProfile(models.Model): restaurant_name = models.CharField(max_length=100, blank=True) slug = models.SlugField(max_length=140, unique=True) related_user = models.ForeignKey(User, on_delete=models.CASCADE) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() created_by = models.ForeignKey(ShopProfile, on_delete=models.CASCADE) class OrderItem(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) class Order(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) total = models.FloatField(blank=True, null=True) views.py class InComingOders(TemplateView): template_name = 'shop/incoming.html' model = Order def get_context_data(self, **kwargs): context = super(InComingOders, self).get_context_data(**kwargs) context['list_orders'] = Order.objects.filter( items=(OrderItem.objects.filter( item=(Item.objects.filter( created_by =created_by=ShopProfile.objects.get(related_user=self.request.user)))))) return context I need to get all the orders corresponded to each shop by relating the field created_by in the shop profile. if a customer places an order, that item created by shop profile it must display in the shop -
Celery not running at times in docker
I have been going bonkers over this one, the celery service in my docker-compose.yml just does not pick up tasks (sometimes). It works at times though Dockerfile: FROM python:3.6 RUN apt-get update RUN mkdir /web_back WORKDIR /web_back COPY web/requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY web/ . docker-compose.yml (Taken out a few services for the sake of understanding) version: '3' services: web_serv: restart: always build: . container_name: web_back_01 env_file: - ./envs/web_back_01.env volumes: - ./web/:/web_back depends_on: - web_postgres expose: - 8282 extra_hosts: - "dockerhost:104.10.4.11" command: bash -c "./initiate.sh" web_postgres: restart: always build: ./postgres container_name: web_postgres_01 # restart: unless-stopped ports: - "5433:5432" environment: # will be used by the init script LC_ALL: C.UTF-8 POSTGRES_USER: web POSTGRES_PASSWORD: web POSTGRES_DB: web volumes: - pgdata:/var/lib/postgresql/data/ nginx: restart: always build: ./nginx/ container_name: web_nginx_01 volumes: - ./nginx/:/etc/nginx/conf.d - ./logs/:/code/logs - ./web/static/:/static_cdn/ - ./web/media/:/media_cdn/ ports: - "80:80" links: - web_serv redis: restart: always container_name: web_redis_01 ports: - "6379:6379" links: - web_serv image: redis celery: build: . volumes: - ./web/:/web_back container_name: web_celery_01 command: celery -A web worker -l info links: - redis depends_on: - redis volumes: pgdata: media: static: settings.py CELERY_BROKER_URL = 'redis://redis:6379' CELERY_RESULT_BACKEND = 'redis://redis:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' Any help …