Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
502 bad gateway error pointing django model.py to other database
i'v setup a wagtail website. I altered models.py from my home-page model. In this models.py i try to acces a database running on another external server. Before i altered models.py the website was running fine, but after altering models.py i get a 502 bad-gateway error. I'm using Nging and gunicorn to serve the website. I followed this tutorial to set it up: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-22-04 I noticed this error in gunicorn: Dec 05 22:36:50 ip-172-31-30-62 gunicorn[1853]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Dec 05 22:36:50 ip-172-31-30-62 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Dec 05 22:36:50 ip-172-31-30-62 systemd[1]: gunicorn.service: Start request repeated too quickly. Dec 05 22:36:50 ip-172-31-30-62 systemd[1]: gunicorn.service: Failed with result 'exit-code'. This is my models.py for accessing the external database. (With help of @Richard Allen) class CasPage(Page): .... @property def plot(self): try: conn = psycopg2.connect( database="xxxx", user="xxxx", password="xxxx", host="xxxxxxxxxxxxx", port=xxxxx, ) cursor = conn.cursor() strquery = (f'''SELECT t.datum, t.grwaarde - LAG(t.grwaarde,1) OVER (ORDER BY datum) AS gebruiktgas FROM XXX''') data = pd.read_sql(strquery, conn) fig1 = go.Figure( data = data, layout=go.Layout( title="Gas-verbruik", yaxis_title="aantal M3") ) return plotly.plot(fig1, output_type='div', include_plotlyjs=False) except Exception as e: print(f"{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}") return None I can acces the external database (no … -
how to call kedro pipline or nodes in Django framework
I have to call Kedro nodes or pipelines in Django API, and need to use Kedro pipelines or nodes output as input in Django API. Not getting any solution. Please suggest some solution for this. How to call Kedro pipeline or nodes in Django APIs? -
how to create a time limit object in django
In this project I create some objects and I want to filter only objects that are created 120 seconds ago . I tried this Line : Model.objects.filter(start_time__gte=Now() - timedelta(minutes=2) , user = request.user , code = data['code']) But It does not work for me . any other solution? (and django timezone is set on Asia/china) -
DJANGO - Unable to refresh my edit profile page
Good day, I am making a Django application, I want to call my data that the user signs up with and to display the information they submitted as: Name Email Then I want to be able to change that data and then I want to save it, and reload back into the dashboard, but when I am updating my 'update_profile.html' the info is not updating, I can; add form data and change it What am I doing wrong? My code below: views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib import messages, auth from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from contacts.models import Contact def register(request): if request.method == 'POST': # Get form values first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] # Check if passwords match if password == password2: # Check username if User.objects.filter(username=username).exists(): messages.error(request, 'That username is taken') return redirect('register') else: if User.objects.filter(email=email).exists(): messages.error(request, 'That email is being used') return redirect('register') else: # Looks good user = User.objects.create_user( username=username, password=password, email=email, first_name=first_name, last_name=last_name) # noqa # Login after register auth.login(request, user) messages.success(request, 'You are now logged in') return redirect('index') # user.save() # messages.success( # request, 'You … -
django : AttributeError: 'str' object has no attribute 'utcoffset'
template: <h2>Summary Details</h2> <table class="center"> <thead> <tr> <th>scrapper_id</th> <th>scrapper_jobs_log_id</th> <th>external_job_source_id</th> </tr> </thead> <tbody> {% for stud in scrappers %} {% csrf_token %} <tr> <td>{{stud.scrapper_id}}</td> <td>{{stud.scrapper_jobs_log_id}}</td> <td>{{stud.external_job_source_id}}</td> </tr> {% endfor %} views.py from django.db.models import Q from django.utils import timezone import pytz import warnings warnings.filterwarnings("ignore") get_records_by_date = "" def index(request): if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) new_records_check_box_status = request.POST.get("new_records", None) print(new_records_check_box_status) error_records_check_box_status = request.POST.get("error_records", None) print(error_records_check_box_status) drop_down_status = request.POST.get("field",None) print(drop_down_status) global get_records_by_date if new_records_check_box_status is None and error_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)) get_records_by_date = check_drop_down_status(get_records_by_date,drop_down_status) elif new_records_check_box_status and error_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(new_records__gt=0) get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status) elif error_records_check_box_status and new_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(error_records__gt=0) get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status) else: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(Q(new_records__gt=0)|Q(error_records__gt=0)) get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status) # print(get_records_by_date) else: roles = Scrapper.objects.all() return render(request, "home.html",{"scrappers": roles}) return render(request, "home.html", {"scrappers": get_records_by_date}) AttributeError: 'str' object has no attribute 'utcoffset'. It was running correctly when I run another project and change the url the error is showing. Is there any solution what is the reason for the error. Its showing error in view page and html page return render(request, "home.html",{"scrappers": roles}) . … -
How to refer to main database instead test one Django TestCase
I am using Django TestCase class to run some test in my project. Few of these test using selenium driver to test forms via browser. Creation of new instance of database table (Recipe for ex.) Point is. Since im using a browser and fill forms fields with Selenium driver, new recipe instance is creating for main database, not test one. I am trying to delete last added row from Recipe table with Recipe.objects.using('default').latest('id').delete() after successful test run. 'default' is single database connection. But this query is targeting test database, which us creating while tests run. How make query refer to main database instead? -
Django AUTO INCREMENT for PK
I have some models in my Django app and I saw the field 'auto_increment_id' (as PK) doesn't work as 'AUTO INCREMENT' (the DB is Postgres). I made 2 records with auto_increment_id 1 and 2, delete record 2 and make a new one with auto_increment_id=3 instead of auto_increment_id=2. models.py class Testme(models.Model): auto_increment_id = models.AutoField(primary_key=True) year = models.ForeignKey( Year, verbose_name="Year", blank=False, on_delete=models.CASCADE, ) def __str__(self): return str(self.auto_increment_id) How can I fix it? Thanks a lot! -
Django I can't pull data from database. DoesNotExist error in web
Admin can change the web title,keywords or description. But it's not working rn. When i entry website i have a error: DoesNotExist at / Setting matching query does not exist. This is my home/models.py from django.db import models class Setting(models.Model): title = models.CharField(max_length=150) keywords = models.CharField(max_length=255) description = models.CharField(max_length=255) company = models.CharField(max_length=50) address = models.CharField(blank=True, max_length=150) phone = models.CharField(blank=True, max_length=15) fax = models.CharField(blank=True, max_length=15) email = models.CharField(blank=True, max_length=50) smptpserver = models.CharField(blank=True, max_length=30) smptemail = models.CharField(blank=True, max_length=30) smptpassword = models.CharField(blank=True, max_length=150) smptport = models.CharField(blank=True, max_length=15) icon = models.ImageField(blank=True, upload_to='images/') facebook = models.CharField(blank=True, max_length=50) instagram = models.CharField(blank=True, max_length=50) twitter = models.CharField(blank=True, max_length=50) aboutus = models.CharField(max_length=50) contact = models.CharField(max_length=50) contact_map = models.CharField(max_length=50) references = models.CharField(max_length=50) status = models.CharField(max_length=10, choices=STATUS) create_at = models.DateTimeField(auto_now_add=True) uptade_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title This is my home/views.py from django.http import HttpResponse from django.shortcuts import render from home.models import Setting def index(request): setting=Setting.objects.get(pk=1) context={'setting':setting} return render(request,'index.html',context) This is my home/temp/index.html {% block title %} {{ setting.title }} {% endblock %} {% block keywords %} {{ setting.keywords }} {% endblock %} {% block description %} {{ setting.description }} {% endblock %} -
Django csrf ajax form not submitting data on server but working on local
I am working on a form submission process. Everything is working fine on my local server but when I am hosting the site on my server then the form submission doing nothing. Here is my template file : ` {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/> <meta name="description" content=""/> <meta name="author" content=""/> <link href="{% static 'css/bootstrap.css'%}" rel="stylesheet"/> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <!-- <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script> --> <script src="{% static 'js/emp1.js'%}" type="text/javascript"></script> <link href="{% static 'css/style.css'%}" rel="stylesheet"/> <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script> <link rel="shortcut icon" href="{% static 'images/favicon.ico' %}"> <!-- <meta name="csrf_token" content="{{ csrf_token }}"> --> <title>Application Upload</title> </head> <body> <header> <section class="bg-white"> <div class="container"> <div class="row"> <nav class="bg-dark mt-1 navbar navbar-expand-lg navbar-light p-1 sticky-top"> <div class="bg-dark container-fluid "><a class="navbar-brand text-white" href="/">Nitin Mandhare <br/> Law Associates LLP</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarColor01"> <ul class="mb-2 mb-lg-0 ms-auto navbar-nav "> <li class="nav-item"><a class="nav-link active" aria-current="page" href="/">Home</a> </li> <li class="nav-item"><a class="nav-link" href="#">Features</a> </li> <li class="nav-item"><a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item"><a class="nav-link" href="#">About</a> </li> </ul> </div> </div> </nav> </div> </div> </section> </header> <main> <section> <div class="bg-secondary container mb-3 mt-3"> <div … -
PyCharm debugger can't connect to Django app inside docker
I try to debug a Django app inside Docker container, the app is launched under uWSGI. Unfortunately, PyCharm debugger can't connect to the container and stops by timeout. My run configuration: I've added up --build to run all containers in debug mode. docker-compose.yml: version: "2.4" services: rabbitmq: image: rabbitmq:3.10.7-management-alpine container_name: bo-rabbitmq rsyslog: build: context: . dockerfile: docker/rsyslog/Dockerfile image: bo/rsyslog:latest container_name: bo-rsyslog platform: linux/amd64 env_file: - .env volumes: - shared:/app/mnt api: build: context: . dockerfile: docker/api/Dockerfile image: bo/api:latest container_name: bo-api platform: linux/amd64 ports: - "8081:8081" - "8082:8082" env_file: - .env volumes: - shared:/app/mnt apigw: build: context: . dockerfile: docker/apigw/Dockerfile image: bo/apigw:latest container_name: bo-apigw platform: linux/amd64 ports: - "8080:8080" env_file: - .env volumes: - shared:/app/mnt depends_on: - api volumes: shared: Dockerfile (for api): FROM nexus.custom.ru/base/python27:2.7.17 # CentOS 7 with Python 2.7 # Environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PYTHONPATH /app/ ENV PATH /app/:$PATH ENV PIP_DEFAULT_TIMEOUT=100 \ PIP_DISABLE_PIP_VERSION_CHECK=1 \ PIP_NO_CACHE_DIR=1 # Install required software RUN yum -y install enchant # Working directory WORKDIR /app # Install and configure Poetry RUN pip install --no-cache-dir poetry \ && poetry config virtualenvs.create false # Install project dependencies COPY pyproject.toml . COPY poetry.lock . RUN poetry install --no-root --no-interaction # Copy project files COPY … -
Is it possible to use Django ORM with JSON object?
I got two json objects that I need to do sorts of ORM operations, such as count, filter, all Here is the first object comments: in views.py comments_response = requests.get('https://jsonplaceholder.typicode.com/comments') comments_data = json.loads(comments_response.text) so below is what print(comments_data) looks like: [ { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 1, "id": 2, "title": "qui est esse", "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" }, ] This is second json object: in views.py posts_response = requests.get( 'https://jsonplaceholder.typicode.com/posts') posts_data = json.loads(posts_response.text) so below is what print(posts_data) looks like: [ { "postId": 1, "id": 1, "name": "id labore ex et quam laborum", "email": "Eliseo@gardner.biz", "body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium" }, { "postId": 1, "id": 2, "name": "quo vero reiciendis velit similique earum", "email": "Jayne_Kuhic@sydney.com", "body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati … -
Exclude django-simple-history from a child model
I am actually stuck in a problem where I need to exclude HistoricalRecords (django-simple-history) from a child class without making any changes in the parent class. Here is my code looks like from simple_history.models import HistoricalRecords class BaseModel(models.Model): id = models.UUIDField(...some args...) created_at = models.DateTimeField(...some args...) created_by = models.ForeignKey(...some args...) history = HistoricalRecords(inherit=True) class Meta: abstract = True default_permissions = Constants.STANDARD_ACTIONS def save(self, suppress_modified=False, from_publish=False, **kwargs): super(BaseModel, self).save(**kwargs) class CommonWithExtraFieldsWithoutVersioning(BaseModel, CommonWithoutVersioning, models.Model): class Meta(CommonWithoutVersioning.Meta): abstract = True class Manager(CommonWithExtraFieldsWithoutVersioning): from_branch = models.CharField(...some args...) to_branch = models.CharField(...some args...) from_version = models.IntegerField(...some args...) to_version = models.IntegerField(...some args...) history = None # this is also not working for me def __init__(self, *args, **kwargs): # this I have tried but not working super(DSLJourneyMergeHistory, self).__init__(*args, **kwargs) self.clean_fields('history') But when I try to makemigration it is creating HistoricalRecords for the manager as well and I want HistoricalRecords should not be maintained for the class manager. How do I exclude this as BaseModel and CommonWithExtraFields Models are used across the application and I cannot make any modification in that model -
is possible open python file with os.path.join and execute some function
I work with Django Framework, and I try to open a Python file from outside the Django package. I use the OS library to get to the path that is outside the Django package, like this: file_path = OS.path.join(settings.FILES_DIR, 'execute_get_symbols.py') In file_path I got only the file path Now, I need to execute a function on this python file (execute_get_symbols.py). My questions are: It is possible? And if it is possible, so how. And if it's not possible, So... how can I import files that are outside the Django package and execute the function? Like from package.file_name import function -
Django I can't pull data from database
Admin can change the web title,keywords or description. But it's not working rn. When i entry website everything is fine i don't have any error but informations didn't come from database. This is my home/models.py from django.db import models class Setting(models.Model): title = models.CharField(max_length=150) keywords = models.CharField(max_length=255) description = models.CharField(max_length=255) company = models.CharField(max_length=50) address = models.CharField(blank=True, max_length=150) phone = models.CharField(blank=True, max_length=15) fax = models.CharField(blank=True, max_length=15) email = models.CharField(blank=True, max_length=50) smptpserver = models.CharField(blank=True, max_length=30) smptemail = models.CharField(blank=True, max_length=30) smptpassword = models.CharField(blank=True, max_length=150) smptport = models.CharField(blank=True, max_length=15) icon = models.ImageField(blank=True, upload_to='images/') facebook = models.CharField(blank=True, max_length=50) instagram = models.CharField(blank=True, max_length=50) twitter = models.CharField(blank=True, max_length=50) aboutus = models.CharField(max_length=50) contact = models.CharField(max_length=50) contact_map = models.CharField(max_length=50) references = models.CharField(max_length=50) status = models.CharField(max_length=10, choices=STATUS) create_at = models.DateTimeField(auto_now_add=True) uptade_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title This is my home/views.py from django.http import HttpResponse from django.shortcuts import render from home.models import Setting def index(request): setting=Setting.objects.all() context={'setting':setting} return render(request,'index.html',context) This is my home/temp/index.html {% block title %} {{ setting.title }} {% endblock %} {% block keywords %} {{ setting.keywords }} {% endblock %} {% block description %} {{ setting.description }} {% endblock %} -
Why does my registration form not work ? (Django Framework)
I am creating a website using Django. Somehow I cannot register as a user as I always get the following error message: UnboundLocalError at /register/ local variable 'context' referenced before assignment views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) pform = UserProfileForm(request.POST) if form.is_valid() and pform. is_valid(): user = form.save() profile = pform.save(commit=False) profile.user = user profile.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to login') return redirect('login') else: context = { 'form': UserRegisterForm, 'p_form': UserProfileForm } return render(request, 'users/register.html', context) register.html {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted">Already have an Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a></small> </div> </div> {% endblock content %} Does anyone have an idea why my context is false or won't be accepted ? -
How to save data from API to my MySQL database in Django REST project
I have a Django REST project. There is a model Product. I get some data from marketplace API about products stocks. And I need to save it to my datbase. I don't know, what kind of viewsets to choose. And how to make a create method. Thanks. My Product model ` class Product(models.Model): store = models.ForeignKey( Store, on_delete=models.PROTECT, blank=True, verbose_name="Store") offer_id = models.CharField(max_length=50, blank=True, default="", verbose_name="SKU") name = models.CharField(max_length=128, blank=True, default="", verbose_name="Name") present = models.PositiveIntegerField( default=0, verbose_name="Present") reserved = models.PositiveIntegerField( default=0, verbose_name="Reserved") ` My serializer class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' store = serializers.CharField() offer_id = serializers.CharField() name = serializers.CharField() present = serializers.IntegerField() reserved = serializers.IntegerField() The data I get from API is a list, for example: [ { "offer_id":"1-100-3-0", "present":5, "reserved":1 }, { "offer_id":"1-101-3-9", "present":0, "reserved":0 } ] -
Django MySQL error : django.db.utils.OperationalError: (1054, "Unknown column 'Euro.id' in 'field list'")
I coded a website based on PHP and I've recently started switching the solution to Django since I need the website to be able to run Python Scripts. Previously, all the datas were located on a MySQL database and were fetched through PHP / SQL Queries. I started following tutorials to connect the existing database to the Django App, and so I generated all the models with the following command: python manage.py inspectdb > models.py The models are correctly generated but the problem is that when I try to fetch data and display it on the HTML page I get the following error : django.db.utils.OperationalError: (1054, "Unknown column 'Euro.id' in 'field list'") Here's the way I summon the data : Views.py : from django.shortcuts import render from django.http import HttpResponse from .models import Euro from django.template import loader # Create your views here. def index(request): listeEuro = Euro.objects.first() context = { 'lasteuro': listeEuro, } return HttpResponse(request, context) The HTML : <div class="d-flex" id="UpdateEuro" style="cursor: pointer;"> <div class="mt-2"> <h6 class="">Euro</h6> <h2 class="mb-0 number-font"> {{lasteuro}} </h2> </div> <div class="ms-auto"> <div class="chart-wrapper mt-1"> <canvas id="euro" class="h-8 w-9 chart-dropshadow"></canvas> </div> </div> </div> Models.py : class Euro(models.Model): date = models.DateField(db_column='Date', blank=True, null=True) # Field name … -
Filter in get_context_data and get_query_set not working
I have a listview where I'm trying to filter out products by category. Some products have a subcategory. When a product has a subcategory I want the listview to display them by subcategory. Problem is: The listview works perfect for items with a subcategory, but does not work for items who do not have a subcategory. Where am I taking a wrong turn here? Models: class Category(models.Model): category_name = models.CharField(max_length=200) sub_category = models.CharField(max_length=200,blank=True,null=True) category_picture = ResizedImageField(upload_to='category/', null=True, blank=True) category_info = models.TextField(blank=True, null=True) category_video = models.CharField(max_length=250,blank=True, null=True) def __str__(self): if self.sub_category is None: return self.category_name else: return f" {self.sub_category}" class Meta: ordering = ['category_name'] class Bottle(models.Model): category_name = models.ForeignKey('Category', on_delete=models.SET_NULL,null=True,blank=True) brand = models.ForeignKey('Brand', on_delete=models.CASCADE) bottle_name = models.CharField(max_length=255) bottle_info = models.TextField() bottle_tasting_notes = models.TextField() bottle_barcode = models.IntegerField() bottle_image = ResizedImageField(upload_to='bottles/',null=True, blank=True) bottle_shop_link = models.CharField(max_length=250, null=True, blank=True) def __str__(self): return f"{self.brand}, {self.bottle_name}" class Meta: ordering = ['bottle_name'] View: class BottlesByCategoryView(ListView): model = Bottle context_object_name = 'bottles' #Filter bij subcategory in the category model. If no subcategory exists, load by category_name def get_queryset(self): if Bottle.objects.filter(category_name__sub_category=self.kwargs['category']) is None: return Bottle.objects.filter(category_name__category_name=self.kwargs['category']) else: return Bottle.objects.filter(category_name__sub_category=self.kwargs['category']) def get_context_data(self, **kwargs): context = super(BottlesByCategoryView, self).get_context_data(**kwargs) if Bottle.objects.filter(category_name__sub_category=self.kwargs['category']) is None: context['category_info'] = Category.objects.filter(category_name=self.kwargs['category']) else: context['category_info'] = Category.objects.filter(sub_category=self.kwargs['category']) return context URLS: path('BottlesByCategory/<str:category>/',BottlesByCategoryView.as_view(template_name='academy/bottlesByCat_list.html'),name='bottlesByCat_list'), … -
API that uses selenium for webscraping
I'm creating an API (Django/DRF with daphne) that accepts requests, scrapes website for data and returns it in response to user. Will this work properly for multiple users in the same time (in parallel)? Or it's impossible to scrape website for each request at the same time? -
update fields based on other table in django models using override method
I have two models, In activity model status is column name this column row has to update from 'Pending' to 'Done', when status column row update from 'Pending' to 'Done' in Item model. class Activity(models.Model): a_id = models.AutoField(primary=True, unique=True) status = models.CharField(max_length=225, blank=True,null=True, default="Pending") class Item(models.Model): item_id = models.AutoField(primary=True, uniue=True) activityid = models.ForeginKey(Activity, on_delete=models.CASCADE, related_name="activitynt") -
How to fetcha all data on the basis of search data
Family will book the tutor. Step-1: Family will search Tutor by Subject and which dates family want to tutor their kids by Teacher. Step--2: Need to show all tutor of that subject for those days which are not booked yet. class TutorProfile(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) which_grade = models.ForeignKey( Grade, on_delete=models.CASCADE, blank=True, null=True) tutoring_subject = models.ForeignKey( TutoringSubject, on_delete=models.CASCADE, blank=True, null=True) sat = models.BooleanField(default=False) sat_time = models.CharField( _("Saturday Time:"), max_length=255, null=True, blank=True) sun = models.BooleanField(default=False) sun_time = models.CharField( _("Sunday Time:"), max_length=255, null=True, blank=True) mon = models.BooleanField(default=False) mon_time = models.CharField( _("Monday Time:"), max_length=255, null=True, blank=True) tue = models.BooleanField(default=False) tue_time = models.CharField( _("Tuesday Time:"), max_length=255, null=True, blank=True) wed = models.BooleanField(default=False) wed_time = models.CharField( _("Wednesday Time:"), max_length=255, null=True, blank=True) thu = models.BooleanField(default=False) thu_time = models.CharField( _("Thursday Time:"), max_length=255, null=True, blank=True) fri = models.BooleanField(default=False) fri_time = models.CharField( _("Friday Time:"), max_length=255, null=True, blank=True) And the Booking Models is: class Booking(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) book_day = models.CharField( _("Book Day"), max_length=255, null=True, blank=True) book_time = models.CharField( _("Book Time"), max_length=255, null=True, blank=True) status = models.CharField( _("Status"), max_length=255, null=True, blank=True) Code in viewset.py: def get_queryset(self): subject_param = self.request.GET.get('subject') bookday = self.request.GET.get('book_day') grade = self.request.GET.get('grade') import ast li = list(bookday.split(",")) print("Book Info:", li) from datetime import datetime for … -
HOW TO SAVE AND CONTINUE IN DJANGO LIKE IN DJANGO-ADMIN
I have a Django form below, I want to save a form by using two buttons: "Save & Add" and "Save & Continue" like in Django Admin. <form method = 'POST' enctype = 'multipart/form-data'> {% csrf_token %} {form | crispy} <div class="form-group"> <button type="submit" name="save_add" class="btn btn-de-primary btn-sm text-light px-4 mt-3 mb-0">Save & Add</button> <button type="submit" name="save_continue" class="btn btn-de-danger btn-sm text-light px-4 mt-3 mx-4 mb-0">Save & Continue</button> <a href="{% url 'doctor:list_doctor' %}" class="btn btn-de-success btn-sm text-light px-4 mt-3 mb-0" type="button">Close</a> </div> </form> My code in views.py is as follows: def addDoctor(request): if request.method == 'POST': form = DoctorForm(request.POST, request.FILES) if form.is_valid(): form=form.save(commit=False) form.save() if request.POST.get('save_add'): messages.success(request,'Doctor is successfully added') return redirect('doctor:list_doctor') elif request.POST.get('save_continue'): return redirect('doctor:add_doctor') return redirect('doctor:list_doctor') else: form = DoctorForm() context = { 'form':form } return render(request,'doctor/add_doctor.html',context) -
UnboundLocalError: cannot access local variable 'u_form' where it is not associated with a value
@login_required def profile(request): if request.user.groups.filter(name='Student').exists(): try: profile = request.user.studentprofile except StudentProfile.DoesNotExist: profile = StudentProfile(user=request.user) if request.method == 'POST': u_form = UserUpdateForm(request.POST,instance=request.user) p_form = ProfileUpdateForm(request.POST, instance=profile) if p_form.is_valid(): p_form.save() messages.success(request, "Your information has been updated successfully.") return redirect('user-profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=profile) elif request.user.groups.filter(name='Employee').exists(): try: profile = request.user.employeeprofile except EmployeeProfile.DoesNotExist: profile = EmployeeProfile(user=request.user) if request.method == 'POST': p_form = EmployeeProfileUpdateForm(request.POST, instance=profile) if p_form.is_valid(): p_form.save() messages.success(request, "Your information has been updated successfully.") return redirect('user-profile') else: u_form = UserUpdateForm(instance=request.user) p_form = EmployeeProfileUpdateForm(instance=profile) context = { "u_form": u_form, "p_form": p_form, } return render(request, 'accounts/profile.html', context) I've been expecting for the django application to display the user profile but the error code is preventing that from actualizing -
OAuth and integration with the G suite
I have a DRF and Vue web application that uses OAuth for authentication via the drf-social-oauth2 package. Essentially, authentication goes like this: the user logs in with their Google account and gets a token from Google the frontend application issues a request to the convert-token token of my backend, which validates the Google token and issues an in-house token, which is also saved to my database from then on, the frontend application will include that in-house token in each subsequent request to my backend if that's the first time the user authenticates, a new account is created on my backend. This means that my backend, understandably, manages its own set of user accounts, which conceptually are twins of the Google accounts used to log-in. I'm now looking to integrate some Google applications into my webapp. To give a very simple example, I'd like to include a functionality that allows accessing Google slides and docs from the frontend of my app. Integration with those services is <iframe> based, so essentially I'd be embedding some iframes to access the resources on the G suite. Here's the issue: since, like I explained, requests to my backend are authenticated using an in-house token and … -
Django - CRUD functionality, Edit Profile Details
I am new to Django but I am creating a Realtor application, I would like the user to be able to update their details using CRUD functionality in the UI. But I can't get my request to work: Heres is my code (views.py): from django.shortcuts import render, redirect from django.contrib import messages, auth from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from contacts.models import Contact def register(request): if request.method == 'POST': # Get form values first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] # Check if passwords match if password == password2: # Check username if User.objects.filter(username=username).exists(): messages.error(request, 'That username is taken') return redirect('register') else: if User.objects.filter(email=email).exists(): messages.error(request, 'That email is being used') return redirect('register') else: # Looks good user = User.objects.create_user( username=username, password=password, email=email, first_name=first_name, last_name=last_name) # noqa # Login after register auth.login(request, user) messages.success(request, 'You are now logged in') return redirect('index') # user.save() # messages.success( # request, 'You are now registered and can log in') # return redirect('login') else: messages.error(request, 'Passwords do not match') return redirect('register') else: return render(request, 'accounts/register.html') def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user …