Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django makemigrations thrown an error if I add a custom model (Tenant) with app_label='auth'
This is the model that I have class Tenant(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.TextField(unique=True) class Meta: app_label = "auth" When I makemigrations in a new venv or run pytest. I always get an error saying django.db.migrations.exceptions.NodeNotFoundError: Migration nqm_core.0001_initial dependencies reference nonexistent parent node ('auth', '0013_tenant') I tried the following ways to resolve this issue Remove migrations files and re migrate Fake migrations with zero and then re migrate Create new database and migrate Update django and migrate Create new venv and migrate None of the above ways worked. The issue got resolved only after I removed the app_label from class Meta for that model. Also I tried removing dependency in the initial migration file but the DB won't migrate at all. Is this a bug or is there a certain way with which I have to run the migration Currently, I only use the following commands ./manage.py makemigrations ./manage.py migrate -
Django Admin automatically logout after get data from user
I am facing an problems in django admin panel. My django admin panel autumatically logout When any user submitting contact-form. How to stop automatically logout? I am facing this problems after add session in my views.py. here is my code: #views.py from django.shortcuts import render,HttpResponseRedirect,redirect from contact.forms import ContactForm from contact.models import Contact from django.views.decorators.csrf import csrf_exempt from django.urls import reverse # Create your views here. @csrf_exempt def home_view(request,*args,**kwargs): name = None obj = None if request.method == "POST": contact_form = ContactForm(request.POST) if contact_form.is_valid(): name = request.POST['name'] email = request.POST['email'] subject = request.POST['subject'] message = request.POST['message'] save_details = Contact(name=name,email=email,subject=subject,message=message) save_details.save() request.session['name'] = name request.session.set_expiry(1) return redirect(home_view) #return render(request, 'index.html',{'message_name':name}) else: print("not submitted") else: contact_form = ContactForm() return render(request, 'index.html',{'form':contact_form,'message_name':obj}) #urls.py from django.urls import path from pages import views urlpatterns = [ path('', views.home_view, name="home"), ] root urls.py from django.contrib import admin from django.urls import path,include from pages import urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), ] #index.html {% if request.session.name %} <div class="centerTest"> <h1> Thanks {{ request.session.name }} for your message. We will get back to you very soon</h1> </div> {% else %} <div class="contact__container bd-grid"> <form action="#contact" method = "POST" class="contact__form"> {% for error in form.non_field_errors %} <div … -
Django - Dealing With Integrity Error And Showing Error Pop up
I have my model.py file as below. I've created a conjugate primary key date & station. Models.py from django.db import models from django import forms # Create your models here. from django.db import models from django.conf import settings from django.contrib.auth.models import User # Create your models here. class ManHour(models.Model): class Meta: unique_together = (('date', 'station'),) station_choices = ( ('KHI','Station1'), ('ISB', 'Station2'), ('LHE','Station3'), ) station = models.CharField( max_length=3, choices=station_choices, ) date = models.DateField() date_time = models.DateTimeField(auto_now=True) imports_airside = models.DecimalField(max_digits= 5, decimal_places= 3, default = 0) imports_landside = models.DecimalField(max_digits= 5, decimal_places= 3, default = 0) exports = models.DecimalField(max_digits= 5, decimal_places= 3, default = 0) Form.py from django import forms from manhourapp.models import ManHour from datetime import date class DateInput(forms.DateInput): input_type = 'date' class InputForm(forms.ModelForm): class Meta: model = ManHour fields = ['date','station', 'imports_airside', 'imports_landside', 'exports'] widgets = { 'date':forms.widgets.DateInput(attrs={'type': 'date', 'max':str(date.today())}) } Views.py def form_page(request): context = {} try: man_hour = ManHour.objects.get(pk=request.GET.get("pk")) except ManHour.DoesNotExist: man_hour = None if man_hour: context["Total_Imports"] = man_hour.imports_airside + man_hour.imports_landside if man_hour: context["Total_Hours"] = man_hour.imports_airside + man_hour.imports_landside + man_hour.exports if request.method == 'POST': properties_Form = InputForm(request.POST, instance=man_hour) if properties_Form.is_valid(): obj = properties_Form.save() return redirect("%s?pk=%s" % (reverse('form'), obj.pk)) else: context['form']= InputForm(instance=man_hour) return render(request, "form.html", context) HTML <!DOCTYPE html> <html> … -
How to solve this Django server launch problem?
I'm trying to launch an e-commerce Django project that I downloaded but I'm getting an error when I execute the command: py manage.py runserver on Powershell. I would need help, please. Here's the command I type followed by the error message: PS C:\Users\Niguel Boss\Documents\Warren\ecommerce> py manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Niguel Boss\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Niguel Boss\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Niguel Boss\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Niguel Boss\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\Niguel Boss\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Niguel Boss\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\Niguel Boss\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Niguel Boss\AppData\Local\Programs\Python\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Niguel Boss\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Niguel Boss\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\Niguel Boss\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'widget_tweaks' Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line … -
Django Http404 message not showing up
I am currently on Django documentation part 3 where I have to create the polls app. However, when I make a request to the url having path like http://127.0.0.1:8000/polls/3/, I was supposed to get the message 'Question does not exist.' But I don't. Here is my code polls/views.py from django.shortcuts import render from django.http import HttpResponse, Http404 from .models import Question # Create your views here. def index(request): # - sign to get more recent, list is ordered from 0 to 4 latest_question_list = Question.objects.order_by('-pub_date')[:5] context = { 'latest_question_list': latest_question_list, } return render(request, 'polls/index.html', context) def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) polls/urls.py from django.urls import path from . import views urlpatterns = [ # ex: /polls/ path('', views.index, name='index'), # ex: /polls/5/ path('<int:question_id>/', views.detail, name='detail'), # ex: /polls/5/results/ path('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ path('<int:question_id>/vote/', views.vote, name='vote'), ] mysite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] The error is … -
Other methods on class based views in Django
I currently have a class based view with get(), post() and delete() methods for the following URL: /property/<str:property_uuid> This works fine and is great. However, I now want URLs such as /property/<str:property_uuid>/publish and /property/<str:property_uuid>/publish to make my API easier to use. These will be GET methods. I was hoping to have corresponding publish() and unpublish() functions and put these within my class. However, I'm not sure how to do this or if this is even posible with class based views? Would I have to go back to function based views with all my functions defined in a "property.py" file for ease of reference and then include this in my urls.py file? -
Using WebDriver to take screenshots with always on process
I have a service that takes screenshots of given url using Selenium Web Driver. It workes Ok, raises a process -> takes the screenshot -> closes the process. the problem is - it takes too long to return. is there a way that the web driver process stays always-on and waits for requests? here is my code class WebDriver(webdriver.Chrome): def __init__(self, *args, **kwargs): logger.info('Start WebDriver instance.') self.start_time = datetime.now() self.lock = threading.Lock() kwargs['chrome_options'] = self.get_chrome_options() super().__init__(*args, **kwargs) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): logger.info(f'Quiting Webdriver instance {id(self)}, took {datetime.now() - self.start_time}') self.quit() @staticmethod def get_chrome_options(): chrome_options = ChromeOptions() chrome_options.headless = True chrome_options.add_argument('--start-maximized') chrome_options.add_argument("--no-sandbox") # Bypass OS security model chrome_options.add_argument('--disable-dev-shm-usage') # overcome limited resource problems chrome_options.add_argument("--lang=en") chrome_options.add_argument("--disable-infobars") # disabling infobars chrome_options.add_argument("--disable-extensions") # disabling extensions chrome_options.add_argument("--hide-scrollbars") return chrome_options def capture_screenshot_from_html_string(self, html_str, window_size): with tempfile.TemporaryDirectory() as tmpdirname: html_filename = tmpdirname + f'/template.html' with open(html_filename, 'w') as f: f.write(html_str) url = 'file://' + html_filename img_str = self.capture_screenshot(url, window_size) return img_str def capture_screenshot(self, url, window_size): self.lock.acquire() try: self.set_window_size(*window_size) self.get(url) self.maximize_window() self.set_page_load_timeout(PAGE_LOAD_TIMEOUT) img_str = self.get_screenshot_as_png() except Exception as exc: logger.error(f'Error capturing screenshot url: {url}; {exc}') img_str = None finally: self.lock.release() return img_str -
Django Complicated Query
I am using django restframework with my Django app and I need to create quite specific query. Here is the models.py: class TaskHours(models.Model): name = models.CharField(max_length=100) hours = models.FloatField() task = models.CharField(max_length=100) date = models.DateField() views.py: class TaskHoursView(generics.ListAPIView): serializer_class = TaskHoursSerializer queryset = TaskHours.objects.all() def get_queryset(self): start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') return TaskHours.filter(date__range=[start_date, end_date]) and serializer is default one with class Meta with all fields. This qurey is working fine but I need to alter it. In the data there are entries which have same name and same date, but different tasks. What I would need is get all the tasks and hours worked with the same name and date to one object like this: { "name": "John", "date": "2021-04-14", "task": "cleaning", "hours": "4.5", "task": "hoovering", "hours": "2.0" } Now I am receiving it like this: { "name": "John", "date": "2021-04-14", "task": "cleaning", "hours": "4.5", }, { "name": "John", "date": "2021-04-14", "task": "hoovering", "hours": "2.0" } Is there any way how to merge the two objects into one? -
Nested serializer with different models using Django Rest Framework
I am fetching record from two different models called coursesModel and categoryCoursesModel. I need to get data in JSON format in the form of array of objects or array of list. I have created two different APIs for fetching record from 2 different tables but how to integrate both in single API. My first API is working perfectly but in my second API I need format like this Please click on this link to get the picture : I need to get data like this Here is my code : models.py: class coursesModel(models.Model): student_id = models.ManyToManyField('userRegistrationModel') # Another table options = (('IIT JEE', 'IIT JEE'), ('NEET', 'NEET'), ('SCHOOL PREP', 'SCHOOL PREP'), ('FOUNDATION', 'FOUNDATION')) courseName = models.CharField(max_length=100, null=True, blank=False, unique=True) courseIcon = models.ImageField(upload_to='icons/',blank=False) status_option = ((1, 'Existed'), (0, 'Deleted')) status = models.SmallIntegerField(choices=status_option,default=1) def __str__(self): return self.courseName class categoryCoursesModel(models.Model): courses = models.ForeignKey(coursesModel, related_name='courses', max_length=20, null=True, on_delete=models.CASCADE) options = ( ('JEE Mains', 'JEE Mains'), ('JEE Advanced', 'JEE Advanced'), # IIT-JEE ('Category1', 'Category1'), ('Category2', 'Category2'), ('Category3', 'Category3'), # NEET ('SPREP1', 'SPREP1'), ('SPREP2', 'SPREP2'), ('SPREP3', 'SPREP3'), # SCHOOL PREP ('Class 6', 'Class 6'), ('Class 7', 'Class 7'), ('Class 8', 'Class 8'), ('Class 9', 'Class 9'), ('Class 10', 'Class 10'), ('Class 11', 'Class 11'), ('Class 12', … -
Django form.save(commit=False) not adding user_id
I am trying to add created by whoever is logged in user but not getting that saved even though I am logged in. form.created_by = request.user is not adding logged in user. def create_table_allotment(request): form = TableAllotmentForm(request.POST or None) context = {'form': form} if request.method == 'POST': if form.is_valid(): try: form.save(commit=False) form.created_by = request.user form.save() return redirect('order_management:table_allotment_home') except IntegrityError as err: print('err => ', err) context['unique_error'] = 'User has already assigned table for today' return render(request, 'orders/table_allotment/create.html', context) Here are my models class QOTs(models.Model): name = models.CharField(max_length=50) alias = models.CharField(max_length=10) def __str__(self): return str(self.name) class Meta: verbose_name_plural = "QOTs" class TableAllotment(models.Model): employee = models.ForeignKey(User, on_delete=models.PROTECT) qot = models.ForeignKey(QOTs, on_delete=models.PROTECT) club = models.CharField(max_length=20, default='POS-0001') from_table = models.IntegerField() to_table = models.IntegerField() working_date = models.DateField(default=timezone.now) created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='qot_creator') created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) class Meta: ordering = ('-id',) unique_together = ('employee', 'working_date',) Here is my form class TableAllotmentForm(forms.ModelForm): class Meta: model = models.TableAllotment fields = ["employee", "qot", "from_table", "to_table"] Please help -
Running two Django sites on the same server. Linode with Ubuntu 18.04
Cant get one of the two sites to work. Systemctl status nginx & gunicorn, nginx-t shows no error. One website is working fine but other one fails to load. Below is my config file for gunicorn & nginx. server { listen 80; server_name domain; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/RFT_Shop; } location /media/ { root /var/www/RFT_Shop; } location / { include proxy_params; proxy_pass http://unix:/var/www/RFT_Shop/RFT_Shop.sock; } } server { listen 81; server_name domain; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/NDD/NDD; } location /media/ { root /var/www/NDD/NDD; } location / { include proxy_params; proxy_pass http://unix:/var/www/NDD/NDD/NDD.sock; } } i have tried using port 80 for both, also tried putting project-name before domain some tutorials suggested that, both these files are separately stored in sites-available directory in /etc/nginx/ & then linked to sites-enabled. Gunicorn config -- .service files [Unit] Description=gunicorn daemon Requires=RFT_Shop.socket After=network.target [Service] User=root Group=root WorkingDirectory=/var/www/RFT_Shop ExecStart=/venv/bin/gunicorn --workers 3 --bind unix:/run/RFT_Shop.sock \ RFT_Shop.wsgi:application [Install] WantedBy=multi-user.target [Unit] Description=gunicorn daemon Requires=NDD.socket After=network.target [Service] User=root Group=root WorkingDirectory=/var/www/NDD/NDD ExecStart=/var/www/NDD/venv/bin/gunicorn --workers 3 --bind unix:/run/NDD.sock \ NDD.wsgi:application [Install] WantedBy=multi-user.target the RFT_Shop ExecStart works with both /var/www & /bin directory structure but NDD only works … -
Django-RQ having a hard time adding items to Django Model
I'm using django-rq to setup background tasks using Redis. Redis is working great and the code is sending the request to Redis - but it is throwing an exception. Exception: Traceback (most recent call last): File "/Users/jeremyenglert/Documents/Sites/showzone/.venv/lib/python3.8/site-packages/rq/worker.py", line 1003, in perform_job self.prepare_job_execution(job, heartbeat_ttl) File "/Users/jeremyenglert/Documents/Sites/showzone/.venv/lib/python3.8/site-packages/rq/worker.py", line 893, in prepare_job_execution self.procline(msg.format(job.func_name, job.origin, time.time())) File "/Users/jeremyenglert/Documents/Sites/showzone/.venv/lib/python3.8/site-packages/rq/job.py", line 254, in func_name self._deserialize_data() File "/Users/jeremyenglert/Documents/Sites/showzone/.venv/lib/python3.8/site-packages/rq/job.py", line 222, in _deserialize_data self._func_name, self._instance, self._args, self._kwargs = self.serializer.loads(self.data) File "./api/models.py", line 5, in <module> class PlayerProfile(models.Model): File "/Users/jeremyenglert/Documents/Sites/showzone/.venv/lib/python3.8/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/jeremyenglert/Documents/Sites/showzone/.venv/lib/python3.8/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/Users/jeremyenglert/Documents/Sites/showzone/.venv/lib/python3.8/site-packages/django/apps/registry.py", line 135, in check_apps_ready settings.INSTALLED_APPS File "/Users/jeremyenglert/Documents/Sites/showzone/.venv/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/Users/jeremyenglert/Documents/Sites/showzone/.venv/lib/python3.8/site-packages/django/conf/__init__.py", line 64, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings Here is a simplified version of the code. # views.py class PlayerProfileView(viewsets.ModelViewSet): ... def get_queryset(self): ... @action(methods=['get'], detail=False) def update_all_profiles(self, request, pk=None): update_player_profiles.delay(PlayerProfile) return Response(status=status.HTTP_200_OK) # update_player_profiles.py @job def update_player_profiles(model): a_long_running_request_for_a_csv_file() a_long_running_task_to_process_data() a_long_running_task_to_save_the_data_to_a_django_model() How can I make it so django-rq can interact with the django models? Or is there a different problem at play? -
Using the URLconf defined,Django tried these URL patterns with i18n
I'm getting the following error message: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/en/sitepages/news-events/ Using the URLconf defined in zainiac.urls, Django tried these URL patterns, in this order: i18n/ ar/ ar/ 404/ [name='404'] 500/ [name='500'] ^media/(?P<path>.*)$ The current path, en/sitepages/news-events/, didn't match any of these. obviously when I try to access this url en/sitepages/news-events/, my root urls.py is: urlpatterns = [ path("i18n/", include("django.conf.urls.i18n")), ] urlpatterns += i18n_patterns( path("bad/", bad), path("sitepages/", include("sitepages.urls")), path("", include("djvue.urls")), path("django-admin/", admin.site.urls), path("documents/", include(wagtaildocs_urls)), path("newsletter/", include("newsletter.urls")), path("tinymce/", include("tinymce.urls")), path("search/", search_views.search, name="search"), path("api/v1/", include("api_urls")), path("user/", include("user.urls", namespace="user")), path("api/v1/general/", include("general.urls", namespace="general")), ) urlpatterns += i18n_patterns( path(f"{settings.ADMIN_URL}/", include(wagtailadmin_urls)), path("", include(wagtail_urls)), ) my sitepages/urls.py is: app_name = "sitepages" urlpatterns = [ path("news-events/", sitepages_view, name='listing'), ] and my sitepages/views.py is: def sitepages_view(request): template = loader.get_template('sitepages/news_events_page_listing.html') context = { 'news_pages': NewsDetails.objects.all(), 'events_pages': EventsDetails.objects.all(), 'listing_page': NewsEventsListing.objects.first(), } return TemplateResponse(request,template,context) what am i doing wrong? if I tried to return a simple HttpResponse containing a string it works, also if I moved the line path("sitepages/", include("sitepages.urls")), from inside the i18n patterns in the root urls.py and put it instead in the normal url patterns like this: urlpatterns = [ path("i18n/", include("django.conf.urls.i18n")), path("sitepages/", include("sitepages.urls")), ] I can access the template using the url sitepages/news-events/ … -
is there any way to make payment gateway site like razorpay using django?
Hi i am just trying to make a a payment gateway site like razorpay using html css and django . is it possible to make such a website using django -
AttributeError at /login/ 'WSGIRequest' object has no attribute 'sessions'
I cant handle this problem thanks for helping me , here's my views.py file : def auth_view(request): form =AuthenticationForm() if request.method=='POST': username=request.POST.get('username') password = request.POST.get('password') user=authenticate(request,username=username,password=password) if user is not None: request.sessions['pk']=user.pk return redirect('verify_view') return render(request,'auth.html',{'form':form}) -
How can I make my Django App *do* something when I run the server?
first q here. I'm a beginner in Python and for my final project I'm making a scraping app in Django. When I run my server I want it to start a BackgroundScheduler that calls my scraping app every 10 minutes. Right now I have my Scheduler on a button but I don't want it to be on a button, I want it to work right when I run my server, is this possible? What I've tried: writing my logic into apps.py then adding the appconfig to settings to INSTALLED_APPS but I get: ModuleNotFoundError: No module named 'finance_app.apps.FinanceAppConfig'; 'finance_app.apps' is not a package making an scheduler.py file where my logic lives and adding it to INSTALLED_APPS but still won't work The BackgroundScheduler that works: scheduler = BackgroundScheduler() scheduler.add_job(scrape, 'interval', second=30) scheduler.start() Scheduler inside my view that calls the scraper def scraper_view(request): scrape() scheduler = BackgroundScheduler() scheduler.add_job(scrape, 'interval', minutes=10) scheduler.start() return redirect("../") Button with the view that I want to get rid of <div style="text-align: center;"><h2 class="subtitlu"> <a href="{% url 'scraper' %}">Scrape News</a> </h2> </div> -
Language cookie in django
I have 3 cookies i.e., django_language, session, csrf. I want secure and http field of each of these to be true. For session and csrf cookie, its working fine but the django_language cookie's httponly and secure is not set to true. My code in settings file is as following :- CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_PATH = '/' SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_PATH = '/;HttpOnly' LANGUAGE_COOKIE_HTTPONLY = True LANGUAGE_COOKIE_SECURE = True LANGUAGE_COOKIE_NAME = 'django_lang' LANGUAGE_COOKIE_PATH = '/' screenshot of browser cookies -
Django AttributeError at /customer/2/ 'ReverseManyToOneDescriptor' object has no attribute 'all'
Hi I am trying to resolve my error issues that I am trying to filter in my customer template. In my views if I place entry_objects= Entry.objects.all(). It is fine, but I want to be able to filter by customer. My query set worked but I can't do reverse bottom to up. :( Models.py: class customer(models.Model): name = models.CharField(max_length= 200, null = True) phone = models.CharField(max_length= 200, null = True) email = models.CharField(max_length= 200, null = True) date_created = models.DateTimeField(auto_now_add=True, null= True) def __str__(self): return self.name class UserTopic(models.Model): #category for user to chose #User interest text = models.CharField(max_length=120, null =True) #we want to display characters with max 250 date_added = models.DateTimeField(auto_now_add=True, null=True ) #allows realtime accuracy upon upload #string representation of model def __str__(self): return self.text class Tag(models.Model): tag_name = models.CharField(max_length=15, null=True) def __str__(self): return self.tag_name #entry model class Entry(models.Model): cust_name = models.ForeignKey(customer, null= True, on_delete=models.SET_NULL) tags = models.ForeignKey(Tag, null = True, on_delete=models.CASCADE) topic = models.ForeignKey(UserTopic, null = True, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text[:10]+"..." # ... on_delete=models.DO_NOTHING, Views.py: def customer_page(request, pk_test): customer_objects = customer.objects.get(id=pk_test), entry_objects = customer.entry_set.all() #entry = Entry.objects.all() context = { 'entry_objects': entry_objects, 'customer_objects': customer_objects, } return render(request, 'user_log/customer.html', context) -
Want to join Three models and get API output
I have Three models. User which is Django default and Blogs and UserActive. I want to get an APi Output Like this: [ { "blog_id": 1, "user": { "id": 1, "username": "superuser", "email": "superuser@email.com", "first_name": "", "is_staff": true "last_active": "2021-04-12T13:36:47.367153Z" }, "title": "first blog", "description": "hola", "image": "/images/phone.jpg", "create_at": "2021-04-08T14:24:51.122272Z", "update_at": "2021-04-08T14:37:00.287746Z" } ] But I am only getting this output on api using get_blogs(request): from views.py Where last_active from UserActive model is not included I want to include it: [ { "blog_id": 1, "user": { "id": 1, "username": "superuser", "email": "superuser@email.com", "first_name": "", "is_staff": true }, "title": "first blog", "description": "hola", "image": "/images/phone.jpg", "create_at": "2021-04-08T14:24:51.122272Z", "update_at": "2021-04-08T14:37:00.287746Z" } ] Here is my models.py class UserActive(models.Model): user_active_id = models.AutoField(primary_key=True, editable=False, null=False) user = models.OneToOneField(User, on_delete=models.CASCADE,null=False) last_active = models.DateTimeField(auto_now_add=True, editable=False) class Blog(models.Model): blog_id = models.AutoField(primary_key=True, editable=False) title = models.CharField(max_length=128,null=False,blank=False) description = models.TextField(null=True,blank=True) image=models.ImageField(null=True,blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) create_at = models.DateTimeField(auto_now_add=True, editable=False) update_at = models.DateTimeField(auto_now=True,editable=False) Here is views.py: @api_view(['GET']) def get_users(request): user = User.objects.all().select_related('useractive') serializer = UserSerializer(user, many=True) return Response(serializer.data) @api_view(['GET']) def get_blogs(request): blogs = Blog.objects.all() serializer = BlogSerializers(blogs, many=True) return Response(serializer.data) here is serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'first_name', 'is_staff', ] class UserActiveSerializer(serializers.ModelSerializer): … -
Django render_to_string does not render javascript
I'm working on a Django project in which I used render_to_string to pre-render HTML templates from the backend, and then I send them to the frontend as a response to an ajax call. rendered_html.append( [render_to_string("webapp/popup.html", context=shop_context), location['Logo'], location['LONG'], location['LAT'], location['id']]) return JsonResponse({"rendered_html": rendered_html}) I am appending this rendered_html into the frontend with javascript. The HTML code and the Django context variable work fine but the javascript in the file does not work at all. If I see the elements section from the developer's console, I can see that javascript is included but it does not work, not even a small console.log works. Is there a workaround to this or am I doing something wrong? Any help will be appreciated. -
ModuleNotFoundError: No module named 'allauth.socialaccount.providers.Apple'
I have gone through this post to implement login with apple. When I used below code from allauth.socialaccount.providers.apple.views import AppleOAuth2Adapter from allauth.socialaccount.providers.apple.client import AppleOAuth2Client from rest_auth.registration.views import SocialLoginView class AppleLogin(SocialLoginView): adapter_class = AppleOAuth2Adapter callback_url = 'https://anycallbackurlhere' client_class = AppleOAuth2Client serializer_class = CustomAppleSocialLoginSerializer the I am getting this error from allauth.socialaccount.providers.Apple.views import AppleOAuth2Adapter ModuleNotFoundError: No module named 'allauth.socialaccount.providers.Apple' Where I did wrong? I am using this and this packages. -
How to find tags and replace inner content with python regex
I am developing an application in Django, where the User inputs data through CK editor, Other than CK editor generated HTML I need to convert few extra tags provided by user, for the sentence having '~@' symbol input I need to create a hyperlink with a popup for example : if user input 1) ~@title~@content~@ expected output will be <a href="#" data-toggle="popover" data-placement="top" title="notification" data-content="content" >title</a> I have written a function, it works, but I am looking for is there any optimized way to implement this by using regex or any other way. Please help me Code i have written def popUpBuilder(self,content): sign_mode_string='~@' index=0 while(content.find(sign_mode_string,index)!=-1): hash_mode_start_position=content.find(sign_mode_string,index) index=hash_mode_start_position+1 hash_mode_second_position=content.find(sign_mode_string,index) index=hash_mode_second_position+1 hash_mode_third_position=content.find(sign_mode_string,index) complete_string=(content[hash_mode_start_position:hash_mode_third_position+2]) title=(content[hash_mode_start_position+2:hash_mode_second_position]) content_string=(content[hash_mode_second_position+2:hash_mode_third_position]) content_string=content_string.replace('<span>','') content_string=content_string.replace('</span>',' ') replacing_string='<a href="#" data-toggle="popover" data-placement="top" title="notification" data-content="'+content_string+'" >'+title+'</a>' content=content.replace(complete_string,replacing_string) return content -
Updating to Django 3.2 broke almost all Django-Pages
I'm developing on a Page which runs Django (with DRF) in backend and ReactJS in frontend. I recently updated to Django v. 3.2. After this, whenever I wanted to open any Django specific pages, it gives me the following error. The only Page I can open is the admin-login page, but after entering my credentials i get the error messsage. The pages which are made with ReactJS aren't broken. https://dpaste.com/HDXFRD2RM Now reverting it back to v. 3.1, no issues occur, but since that version won't be supported for long, I really want to change to version 3.2. I figure, the error is relevant to something with the database connection. These are the DB settings in Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'shifts-db', 'USER': 'user', 'PASSWORD': 'passworrd', 'HOST': 'localhost', 'PORT': '3306', } } If I need to elaborate more, please tell me so. -
Django Channels send to group from view
i am trying to send a message to a group from outside the consumer "from view ..." documentation saying async_to_sync(channel_layer.group_send)("chat", {"type": "message_handler"}) but what i don't get is how to define the message_handler in the view because i am getting this error No handler for message type message_handler -
ImportError: cannot import name 'BoundField' from 'django.forms.forms'
I am having ImportError: cannot import name 'BoundField' from 'django.forms.forms'. I was facing ImportError: cannot import name 'pretty_name' from 'django.forms.forms' error, then I changed 'from django.forms.forms import pretty_name' to 'from django.forms.utils'. Now the error changed. Anyone having a solution for this?