Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Append in Loop using Selenium
def show(request): driver = webdriver.Chrome('/Users/colegulledge/desktop/chromedriver') driver.get('https://www.horrycounty.org/bookings') sleep(random() + 2) date_form = driver.find_element_by_id('txtBookingDate') ##we are going to loop through the start date-end date in this input box def daterange(start_date, end_date): for n in range(int((end_date - start_date).days)): yield start_date + timedelta(n) start_date = date(2020, 1, 1) end_date = date(2020, 1, 3) def change_date_format(dt): return re.sub(r'(\d{4})/(\d{1,2})/(\d{1,2})', '\\2-\\3-\\1', dt) ##to change the format to month-day-year for single_date in daterange(start_date, end_date): days = (single_date.strftime(format("%Y/%m/%d"))) days = (change_date_format(days)) date_form.send_keys(days) sleep(2) ##Changing the date format and using send keys we put in in the inputbox for el in days: search = driver.find_element_by_css_selector("span.btn-primary") driver.execute_script("arguments[0].click();", search) sleep(2) inmate_info = driver.find_elements_by_class_name("cellLarge") rs = [] for p in range(len(inmate_info)): rs.append(inmate_info[p].text.strip()) date_form.clear() print(rs) ##the website keeps the previous date in the input box, so we must ##clear the input box and repeat the loop return HttpResponse(rs) So whenever I do this, rs is only returning the last day of records.. I believe my function is not appending to the list, instead it is replacing it. This may be obvious, but I am an inexperienced and working on my first major project. Any ideas/suggestions? Thanks -
Ajax data manipulation when transmitting to Django CBV
I'm using django-autocomplete-light with the select2 "select multiple" widget for a M2M form. I have it set up to enable "Create New" when the input is not found. However, my model has additional required fields beyond the initial input of the "select multiple" widget. I am trying to create a way to prompt the user for the additional fields when trying to create, and then sending that data through ajax to my django view. Right now, if I pre-supply the other required fields within my view, the user can create a new object with the name that they've entered (and clicked "Create New") for, and the other fields will be determined in my view. This shows me that the code is working, but ideally I'd like to prompt the user for the additional data. I have created a prompt, however I cannot the correct syntax for transmitting the data. As an example, pretend I have a model with required fields "Name" and "Location". On the Select2 widget, the user types a "Name" which doesn't exist as an object, and clicks "Create New". Now, I'd like the script to prompt them for the location, then transmit that in as a get_or_create … -
Django Stripe Payment Responds with Invalid Parameter after clicking Submit Payment button
I am working on an e-commerce project that requires stripe payment gateway. It is my first time to work on an application that requires stripe payment. I am a junior programmer. I am working on my localhost machine, I have tried to debug the code but i have failed to see where the problem is. @Hacker86 got the solution but has not shared it can anyone help me with the problem. This is the link of the same problem Stack I tried to solve the problem with the solution in the replies to above the question but all was in veil. So please can anyone help immediately reply me. Below is my relevant Code base.py import os from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__)))) SECRET_KEY = config('SECRET_KEY') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_framework', 'drf_yasg', 'crispy_forms', 'django_countries', 'core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'perfectfits.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = … -
django-tables2: Change column header link
I have created a table using django-tables2, and it displays correctly with verbose names displaying in the column headers. Each of the column headers is a link to sort the column, but as far as I can tell there is no way to change the link href: <th class="orderable"> <a href="?sort=column_name">Verbose Name</a> </th> I have found ways to edit the attributes of the <th> tag, but I can't find a way to edit the href parameter on the <a> tag wrapping the column header text. I have multiple tables I'd like to display, and I'd like to use different paths for updating each different table. Is there a way to update the Table or Column class to customize the URL used when clicking on the column header text? -
Redirect non ajax requests to DRF endpoint
I want to prohibit direct access to the endpoints. If I was using Django's CBV I'd simply add if not request.is_ajax(): return redirect... to the view. Now how would I achieve the same with DRF, specifically with viewsets and generic mixins? Should I overwrite get methods? If so, are there more elegant ways? -
After creating login and registration page HTML and CSS how to take user input and save to data base?
I'm currently making a website and have created both the HTML and CSS for both the registration and login Pages - I'm wanting to use Django to save the information, I'm just a bit confused on how to take the user input (using my html inputs) and then transferring them to the Django data base. I'm very new to web development as you can tell - I'm just trying to take it one step at a time. /* This is the style sheet for the Registration Page only */ body { background-color: rgba(255,0,0,0.65); } h2 { color: white; font-family: optima; font-size: 300%; font-weight: 500; font-variant: small-caps; line-height: 200px; height: 200px; z-index: 0; margin-top: -50px; } h3 { color: white; font-family: Helvetica; font-size: 250%; font-weight: 400; font-variant: small-caps; margin-top: 50px; } #rectangle{ top: 20px; display: inline-block; width:450px; height:550px; background:rgba(43, 43, 43, 1); transform: translate(-50%,-50%); border-radius: 15px; position: absolute; z-index:-5; top: 550px; } img { opacity: 0.8; display: block; margin-left: auto; margin-right: auto; background-repeat: no-repeat; } div { text-align: center; padding: 0; } label{ color:white; font-family:Helvetica ; display: block; text-align: center; padding-bottom: 10px; } select{ font-family:Helvetica ; background-color: lightgrey; text-align: center; margin: 0 auto; display: block; padding: 50; } span { color:white; … -
certbot and apache domain name trouble
I have deployed a django web application on a linux server using ubuntu 20.10 and apache2. My site was working well before I added certbot. However, after I ran the certbot commands for apache2 and ubuntu 20.04 (because 20.10 was not listed) my site only works for for first time users who put www.my_domain_name.com. When they just put my_domain_name.com in it serves them the default apache ubuntu page which is clearly not what I want. My idea was to use rewrite conditions and rules to send them to the www. version if they try to access it without that but everytime I do that an error occurs. The only rewrite rule I have is below and Server_Name is set to www.my_domain_name.com at the top of the .conf file. Can you help me write a rewrite rule to always send them to the https version and to the www. version or give me advice on how to get the non www. version to serve up the proper page with https? Also it is worth noting that when I try to open the non www. version in my browser it works fine, but when a first time user trys it it does … -
Can't load link postgreSQL to Django
I've created a new Django project in my virtual environment and installed psycopg2. I changed my settings.py file to the following: DB_NAME = "neighborhood" DB_USER = "django" DB_PASSWORD = "password" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, 'HOST': 'localhost', 'PORT': '5432', } } But when I run python manage.py migrate in my virtual enviorment, I get the following error: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: DLL load failed while importing _psycopg: The specified module could not be found. I'm using python v3.9 and postgreSQL v13. I checked other posts on Stack Overflow but none answered my problem. Thanks. -
django-filter according to the logged user
I am using the django_filters to filtering the information. However, it is showing the data of all regitered user of my system. I need show only the data of logged user. Follow the files: filters.py import django_filters from apps.requisitos.models import Requisito class RequisitoFilter(django_filters.FilterSet): class Meta: model = Requisito fields = ['nomeRequisito', 'projeto'] views.py class RequisitoList(ListView): paginate_by = 10 model = Requisito def get_queryset(self): usuarioLogado = self.request.user return Requisito.objects.filter(user=usuarioLogado) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = RequisitoFilter(self.request.GET, queryset=self.queryset) return context the loop for of html page {% for requisito in filter.qs %} thank you very much -
Saving database changes with django channels
I wish to make simple programme in django channels - I open Websocket and then listen for users clicking a button or pressing any key down. If such event occurs JS sends message to Channels where it gets access to db where there is a model of a counter, increment it depends it was click or key, and then send it back to group on layers. Unfortunately, error occurs. Why it calls contex error if I already used database_sync_to_async My consumers.py : from channels.generic.websocket import AsyncWebsocketConsumer import json from channels.db import database_sync_to_async from .models import Licznik class MyConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = 'main_room' self.counter = await database_sync_to_async(self.get_counter)() await (self.channel_layer.group_add)( self.room_group_name, self.channel_name ) await self.accept() def get_counter(self): return Licznik.objects.all()[0] async def receive(self, text_data): if text_data == "klik": self.counter.klik +=1 elif text_data == "klak": self.counter.key += 1 await database_sync_to_async(self.counter.save()) #error here klik = self.counter.klik klak = self.counter.key await (self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'klik': klik, 'klak': klak } ) async def chat_message(self, event): message_klik = event['klik'] message_klak = event['klak'] await self.send(text_data=json.dumps({ 'klik': message_klik, 'klak': message_klak })) async def disconnect(self, close_code): await (self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) await self.close() Error: Exception inside application: You cannot call this from an async context - use … -
python manage.py dumpdata Access is denied
I got the error message - (ECOMME~1) C:\Users\HP\Django Projects\EcommerceProject>python manage.py dumpdata products --format json --indent 4 > products/fixtures Access is denied. I assumed it was because I had changed my databases because the default databases are not sufficient if you want mapping functionality. I read the post Django loaddata returns a permission denied for relation and asked GRANT ALL PRIVILEGES ON DATABASE Blog&Cart for user postgres. -
My very simple Django Form not passing value to another View
I'm new to Django with a background in Database design. I spent most of my IT career developing prototypes in MS Access so this Web stuff is new to me. Now I'm trying to develop prototype reports in Django for a reporting wing of a SAAS offering. I've got a rough report developed, and if I hard-code the values to pass into some raw queries, it renders a report. Now I'm trying to make a simple form to enter a value into and pass it into the view that renders the report. (Pardon me if I'm using the correct lingo.) Here's the form for the data entry: product_batch.py from django import forms class PrdBtchSelect(forms.Form): prd_btch_nbr = forms.CharField(max_length=20) Here is the data entry HTML: prd_btch_select.html {% extends "base.html" %} {% block title %}Product Batch Select{% endblock %} {% block content %} <form action={% url 'prd_btch_dtl' form.prd_btch_nbr %} method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock %} Here are the views for the data entry form and for rendering the report: view\product_batch.py from django.shortcuts import render from reports.views import sql from reports.models import Accounts from reports.forms import PrdBtchSelect # import datetime def prd_btch_dtl(request, prd_btch_nbr): """View function for … -
Where do I keep ORM in a distributed app?
I am designing a scalable web app. I have APIs (Django Rest Framework) in one container instance, Web App (Django) in another, Database (Postgreql) in another and finally CDN in another (Azurite). I wanted to decouple API since mobile apps will use the same - eventually. Question: Where do I keep ORM in this scenario? If I keep it part of Web apps, then how do the APIs recognize and use the objects? Or, if I keep them part of the API services, how do the front end (web apps) understand the objects? -
Reloading the data automatically in django
im new to this Here in this program when i clicking the refresh button the entire page is being reloaded and then only the data is being updated so i was thinking you could automatically update the data after some time or when clicking the refresh button get the data without loading the page entirely again The link is here for the github issue https://github.com/ALDRIN121/Covid-19_live_tarcker/issues/1 And thanks in advance -
2 pages in URL in python
my question is why i cannot get property.html when the server is run let me explain you how th project go one : the 1st page which is content list of cities one of them choosen then th next page i get it's property_name the 3rd page should give me all it's properties (name,area) i hope u understand me models.py: from django.db import models class location(models.Model): location_name = models.CharField(max_length=500) location_type = models.CharField(max_length=500) def __str__(self): return self.location_name class property(models.Model): location = models.ForeignKey(location, on_delete=models.CASCADE) property_name = models.CharField(max_length=500) property_area = models.CharField(max_length=500) def __str__(self): return self.property_name views.py: from django.shortcuts import render from django.views import generic from .models import location,property class indexview(generic.ListView): template_name = "homsapp/index.html" def get_queryset(self): return location.objects.all() class locationview(generic.DetailView): model = location template_name = "homsapp/location.html" class propertyview(generic.DetailView): model = property template_name = "homsapp/property.html" urls.py: from django.contrib import admin from django.urls import path,include, re_path from homsapp import views app_name = 'homsapp' urlpatterns = [ #path('admin/', admin.site.urls), path(r'', views.indexview.as_view(), name=('index')), re_path(r'(?P<pk>[0-9]+)/$',views.locationview.as_view(),name=('property')), re_path(r'([0-9]+)/(?P<pk>[0-9]+)/$',views.propertyview.as_view(),name=('propertyview')), ] index.html: {% for locat in object_list %} <a href="/homsapp/{{locat.id}}">{{locat.location_name}}</a><br> {% endfor %} location.html: {% for i in location.property_set.all %} <a href="/homsapp/{{locat.id}}/{{i.id}}">{{i.property_name}}</a> {% endfor %} property.html: {{property.property_name}}<br> {{ property.property_area}} -
Using django without models
Is it possible to use Django but without models? Instead of models I want to use raw sql queries with help of mysql cursor. I want to implement Car Rental site to rent a car. There will be three tables: Cars, Users, Orders. Anyone can sign up on the webpage, sign in and make orders. The only limitation is that a have to do this using raw sql queries so I think that I have to avoid using models. Is this even possible? I'm new to Django and this might be dump question but need to know cause this is my academic project. -
Failing django migrate from ProcessedImageField to FilerImageField
I currently have a model for reusable images: class Image(models.Model): class Meta: verbose_name = _('Image') verbose_name_plural = _('Images') name = models.CharField( max_length=200, unique=False, blank=False, null=False, verbose_name=_('Image name') ) full_size = ProcessedImageField( upload_to='images/', processors=[ResizeToFit(height=450, upscale=False)], format='JPEG', options={'quality': 90}, ) thumbnail = ImageSpecField( source='full_size', processors=[Thumbnail(width=200, height=115, crop=True, upscale=False)], format='JPEG', options={'quality': 60} ) def __str__(self): return self.name Now I'm trying to move over to the FilerImageField from django-filer. I have added the field with a different name, here's the relevant code section: image = models.ForeignKey( Image, on_delete=models.SET_NULL, verbose_name=_('Unit image'), null=True, blank=True ) img = FilerImageField( null=True, blank=True, related_name="unit_img", verbose_name=_('Unit image'), on_delete=models.DO_NOTHING, ) I have the following migration: # Generated by Django 3.1.2 on 2020-11-02 20:09 from django.db import migrations from filer.models import Image def migrate_unit_images(apps, schema_editor): Units = apps.get_model('tageler', 'Unit') for unit in Units.objects.all(): if unit.image: img, created = Image.objects.get_or_create( file=unit.image.full_size.file, defaults={ 'name': unit.name, 'description': unit.image.name, } ) unit.img = img unit.save() class Migration(migrations.Migration): dependencies = [ ('tageler', '0008_filer_create'), ] operations = [ migrations.RunPython(migrate_unit_images), ] My problem is that I get the following error: ValueError: Cannot assign "<Image: This is a test image>": "Unit.img" must be a "Image" instance. I thought that I just created or gotten the Image. What am I missing … -
Can I nest similar model relationships under a custom type in Graphene Django?
Assuming I have a Django model with a number of relationships that are related, is it possible to nest them through a non-model type for querying purposes? A specific example: Assume I have a model Organization with relationships that include X_projects, X_accounts, etc which are also Django models. It is pretty easy to allow queries like: query fetchOrganization($id: Int!) { organization(id: $id) { id, ... other fields ... X_accounts { ... } X_projects { ... } } } but I would prefer to support queries like: query fetchOrganization($id: Int!) { organization(id: $id) { id, ... other fields ... X { accounts { ... } projects { ... } } } } Given that X doesn't actually make sense to be a Django model / relation on the backend, is there a way to achieve this? -
getting error when manage.py makemigrations with mongodb
enter image description hereenter image description here enter image description hereur.com/fPD9B.png -
Django group and sum QuerySet for template
Hoping someone can help! Apologies if the question isn't well written, this is my first post. I am trying to pass a queryset through to a template - I get an error if I do not pass the id through (ID1 in example output below) but I do not want to do that as it interferes with a group by: ID1 Staff No. Week Start Hours Staff ID 1 12345 2020-10-24 15 1 2 12345 2020-10-17 7.5 1 4 12345 2020-10-17 10.0 1 Basically, I want the output to grouped to display only TWO rows (2020-10-17 should be one row with 17.5 hours in total). My model is: from django.db import models from django.contrib.auth.models import User class Contractor(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) staff_number = models.CharField(max_length=9, null=True) contractor_name = models.CharField(max_length=100, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) objects = models.Manager() def __str__(self): return f"{self.staff_number}: {self.contractor_name}" class WeekList(models.Model): week_number = models.SmallIntegerField(null=True) week_start = models.DateField(null=True) objects = models.Manager() def __str__(self): return f"{self.week_number}: ({self.week_start})" class Timesheet(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.PROTECT) contractor = models.ForeignKey(to='timesheet.Contractor', null=True, on_delete=models.PROTECT) week_list = models.ForeignKey(to='timesheet.WeekList', null=True, on_delete=models.PROTECT) job_number = models.CharField(max_length=16, null=True) sat_hours = models.FloatField(default=0, null=True, blank=True) sun_hours = models.FloatField(default=0, null=True, blank=True) mon_hours = models.FloatField(default=0, null=True, blank=True) tue_hours = models.FloatField(default=0, null=True, blank=True) … -
Timestamp keeps updating in admin
class Transaction(models.Model): id_str = models.CharField(verbose_name="Transaction ID", max_length=200) created = models.DateTimeField(verbose_name="Date of creation", auto_now_add=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.set_transaction_id() def set_transaction_id(self): dt = datetime.datetime.now() self.id_str = str(dt.year) + str(dt.month) + str(dt.day).zfill(2) + \ str(dt.hour) + str(dt.minute).zfill(2) + str(dt.second).zfill(2) I want to use the the timestamp of point where the model instance is created to assign id_str. I can't use model field created because __init__ runs first. But in the above code, after creating the model instance and id_str assigned, when I refresh the admin page, id_str also gets refreshed to an updated timestamp. Why does datetime.now() refreshes itself in admin? -
How to get data from another table by using foreign key and JOIN in django and display it in angular using restapi
I want to get course title and course code using the foreign key courseID and JOIN.Then using django restapi I want to show the courseOffered table to display the course title and course code instead of courseID class Course(models.Model): courseID = models.AutoField(default = None, max_length=20, primary_key = True, verbose_name='course ID') courseCode = models.CharField(max_length=8, verbose_name='course Code', unique = True) crs_title = models.CharField(max_length=50, verbose_name='title') crs_shortName = models.CharField(max_length=9, verbose_name='short Name', unique = True) CATEGORY_CHOICES = ( ('major', 'major'), ('core', 'core'), ('science & mathematics', 'science & mathematics'), ('general education', 'general education'), ('optional', 'optional'), ) crs_category = models.CharField(max_length=25, choices=CATEGORY_CHOICES, verbose_name='category') programCode = models.ForeignKey('Program',on_delete=models.CASCADE, verbose_name='program', db_column="programCode") class Meta: db_table = '"tbl_course"' verbose_name_plural = "Course" def __str__(self): return '%s %s' % (self.courseCode, self.crs_shortName) `class CourseOffered(models.Model): courseOfferedID = models.AutoField(default = None, max_length=20, primary_key = True, verbose_name='courseOffer ID') TERM_CHOICES = ( ('Spring', 'Spring'), ('Summer', 'Summer'), ('Autumn', 'Autumn'), ) ofr_term = models.CharField(max_length=6, choices=TERM_CHOICES, verbose_name='term') ofr_year = models.IntegerField(verbose_name='year') programCode = models.ForeignKey('Program',default='115', on_delete=models.CASCADE,verbose_name='program',db_column="programCode") batchCode = models.ForeignKey('Batch',blank = True, null = True, on_delete=models.CASCADE, to_field='batchCode', related_name='batch_Code', verbose_name='batch Code', db_column="batchCode") courseID = models.ForeignKey('Course',default=None,on_delete=models.CASCADE, to_field='courseCode', verbose_name='course', db_column="courseID") facultyID = models.ForeignKey('Faculty',default=None,on_delete=models.CASCADE, verbose_name='faculty', db_column="facultyID") fac_shortName = models.ForeignKey('Faculty',default=None, on_delete=models.CASCADE, related_name='Faculty_Short_Name', to_field='fac_shortName', verbose_name='Faculty Short Name', db_column="fac_shortName") class Meta: db_table = 'tbl_courseOffered' verbose_name_plural = "CourseOffered" def __str__(self): return '%s' % (self.courseOfferedID) -
Error in parsing django variable in javascript
I have a django app. I am using the below code to use access a django variable in javascript. var pd_info = {{pd_inf|safe}}; This is giving Uncaught SyntaxError: missing ] after element list note: [ opened at line 327, column 15 The variable works perfectly fine in django template. How to resolve this? -
How do you turn a new-style middleware class into a decorator for generic DRF views?
I have middleware that I need for certain views. I don't want the middleware to run globally, so I would like to decorate some generic DRF views with it instead. I'm guessing that this should be simple to do, but I haven't had much luck. I was trying to use the decorator_from_middleware decorator with the middleware, but that appears to only work with old-style middleware. Below is a simplified example of what I am trying to do. class LoggerMiddleware: """ Middleware that logs Request and Response context """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) # capture the data I need here return response This decorator fails with the middleware, but I do not know what to replace it with. @decorator_from_middleware(LoggerMiddleware) class TestView(CreateAPIView): def post(self, request): return Response({'detail': 'attempting this'}) -
How to get response parameters in Django?
I want to implement login with twitter without using any library for my django app. I am sending the user to login page using a request function in views by passing the tokens which is successfully going to the twitter login page. Twitter redirects user to a url which I have configured as login/twitter/callback How do I access the parameters sent by twitter on this url using a view ?