Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Keep getting ModuleNotFoundError: No module named 'mainsite.settings' when pushing scheduler to heroku
I'm trying to set up a scheduler on heroku - I read on the django docs that I need to treat django as a stand alone app My clock.py, which triggers the background job looks like this: import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainsite.settings.dev') django.setup() from django.conf import settings from apscheduler.schedulers.blocking import BlockingScheduler from rq import Queue from worker import conn from accounts.tasks import print_message q = Queue(connection=conn) sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=3) def timed_job(): print('This job is run every three minutes.') q.enqueue(print_message, 'http://heroku.com') sched.start() I keep getting an error saying ModuleNotFoundError: No module named 'mainsite.settings' even though my folder structure doesn't even have a mainsite.settings. It's stored in mainsite.settings.prod for the heroku server and in mainsite.settings.dev on my local machine, as seen here: My wsgi.py looks like this: os.environ.setdefault('DJANGO_SETTINGS_MODULE', os.getenv('DJANGO_SETTINGS_MODULE')) The worker.py file, if anyone wonders, looks like this: import os import redis from rq import Worker, Queue, Connection listen = ['high', 'default', 'low'] redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379') conn = redis.from_url(redis_url) if __name__ == '__main__': with Connection(conn): worker = Worker(map(Queue, listen)) worker.work() What am I doing wrong? -
Django NoReverseMatch at / is it conflicting path names and or order?
hello i am trying to add an edit page to my django url patterns and the page give me an error once i click on one of the links on my page the system crashes and i am presented with a no reverse match error from the system. If i do swap the the edit path with the entry path it does work then but that is not the way i want it to work. I would like the user be presented with entry page first and then be able to click on the edit button to edit the page. below are my views and some html pages. new to django and looked into the documentation but didn't find anything. thank you for the help below is also the error: error - Reverse for 'edit' with arguments '('# Django\r\n\r\nDjango is a web framework written using Python that allows for the design of web applications that generate HTML dynamically.\r\n',)' not found. 1 pattern(s) tried: ['(?P[^/]+)$'] urls.py: from django.urls import path from . import views app_name = "enc" urlpatterns = [ path("", views.index, name="index"), path("new_page", views.new_page,name="check_page"), path("",views.get_search,name="search"), path("<str:title>",views.entry, name="page"), path("<str:title>",views.edit, name ="edit"), ] views.py from django.shortcuts import render from django.http import HttpResponse, … -
How to create a horizontal box-card carousel using for loop with django
Iam new to django and learning.I did make my html card-box code horizontally carousel but has lot of card-box, I'am trying from last one week to modify and simplify card-box code using django forloop, searched all over net but couldn't get any desire solution. help me with example templets plz. -
Is it possible to override model save behavior in cases where Django admin throws an error on save?
The situation is this: I have two models, Text and Edition, in a many-to-many relationship. That relationship is tracked by an intermediate "through" model, EditionTextThrough, which keeps track of the position of each text within each edition. This position is represented by an integer, and must be unique with the edition ID. So the table looks like this: +----+----------+----------------------------------+---------+ | id | position | edition_id | text_id | +----+----------+----------------------------------+---------+ | 1 | 1 | 5208c5563d4148c89813a4f7105b0b4c | 1 | | 2 | 2 | 5208c5563d4148c89813a4f7105b0b4c | 2 | | 4 | 3 | 5208c5563d4148c89813a4f7105b0b4c | 4 | | 5 | 4 | 5208c5563d4148c89813a4f7105b0b4c | 4 | | 6 | 5 | 5208c5563d4148c89813a4f7105b0b4c | 4 | | 7 | 6 | 5208c5563d4148c89813a4f7105b0b4c | 1 | +----+----------+----------------------------------+---------+ This sample only shows one edition, but you get the idea. What's important here is that I want to keep the position numbering consecutive; the numbers don't matter on their own except to keep track of a sequence. I've been able to get them to stay consecutive when an instance is deleted, along with most of the other behavior I want. However, the sticking point is when it comes to rearranging them, swapping positions, etc. Say … -
How do I maintain a button state across pages
In my project I'm using normal HTML for front-end and Django for back-end. There I have a login system. I have two questions on that: When the user logs-in how do I detect it in HTML and change the Login button to show Log out. How do I maintain this changes across pages. So, that when I navigate to a different page after login it keeps showing the logout button. Don't suggest me react. I have come a long way from where I can change my technology stack for this project. -
time data '0:02:00' does not match format '%H %M %S'
I want to save a string as time format to store it in the database for a django project, Here's my utils.py file: import datetime import re import math from django.utils.html import strip_tags def count_words(text_string): word_string = strip_tags(text_string) matching_words = re.findall(r'\w+', word_string) count = len(matching_words) return count def get_read_time(text_string): count = count_words(text_string) read_time_min = math.ceil(count/200.0) #Assuming 200 words per min Reading read_time = str(datetime.timedelta(minutes=read_time_min)) return read_time Here's the required portion of the models.py file: class Post(models.Model): read_time = models.TimeField(null=True, blank=True) Here's the required portion of the views.py file: class PostDetailView(DetailView): model = Post def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) texts = self.object.content # print(texts) read_time=get_read_time(texts) # print(read_time) Post.objects.create(read_time=datetime.strptime(read_time, "%H:%M:%S")) return context The Output format of the string is 0:02:00 this I want to save it in the database as datetime field. But I am encountering this error:- Exception Type: ValueError at /post/this-blog-contains-an-image-with-it/ Exception Value: 's' is a bad directive in format '%H:%MM:%ss' -
Django Custom Authentication with user model
Im trying to add SAML2 authentication to my Django Project. I'm now at the point where I get the SAML response with user and I can parse the response. I'm in the returned URL of SAML2 request that is a specific view of my SAML2 module. In the view I have this code: if 'samlUserdata' in request.session: if len(request.session['samlUserdata']) > 0: attributes = request.session['samlUserdata'].items() user = saml_authenticate(attributes) saml_authentication is a simple method that take the attributes of SAML Response, take username and search it on DB and return the user model. Now its not clear what I have to do to effectively log in my software. Im especting to redirect to the HomePage of my software where, instead of Login Page, I automatically login. Searching on google, I found out the custom authentication. So I've create a new backend authentication and added to settings. Somehting like this: def authenticate(self, request, username): try: logger.debug("Authenticating user '%s'" % (username)) user = User.objects.get(username=username) if not user.is_active: syslog.syslog("User '%s' not active" % (username)) return None logger.debug("User '%s': authenticated" % (username)) return user except User.DoesNotExist as e: logger.debug("User '%s' not found" % (username)) return None But I don't know how to use properly. I have … -
Retrieve user e-mailaddress given confirmation key (email verification) from Django all-auth with rest-auth
The application is using Django backend and ReactJS frontend. I created user accounts using the standard rest-auth package in Django, calling the endpoints from the ReactJS frontend forms. Sign up and login works fine, but when it comes to e-mail confirmation, I haven't been able to find where confirmation keys are stored and how this is accessed. I've overridden get_email_confirmation_url from DefaultAccountAdapter to change the URL confirmation link that is being sent out from [backend]/rest-auth/registration/account-confirm-email/[KEY] to [frontend]/registration/confirm-email/[KEY]. I'm able to read out [KEY] at the frontend. However, how do I retrieve the e-mailaddress and name of the user that's trying to confirm their address? In the standard Django template this is possible (email_confirm.html): {% extends "account/base.html" %} {% load i18n %} {% load account %} {% block head_title %}{% trans "Confirm E-mail Address" %}{% endblock %} {% block content %} <h1>{% trans "Confirm E-mail Address" %}</h1> {% if confirmation %} {% user_display confirmation.email_address.user as user_display %} <p>{% blocktrans with confirmation.email_address.email as email %}Please confirm that <a href="mailto:{{ email }}">{{ email }}</a> is an e-mail address for user {{ user_display }}.{% endblocktrans %}</p> <form method="post" action="{% url 'account_confirm_email' confirmation.key %}"> {% csrf_token %} <button type="submit">{% trans 'Confirm' %}</button> </form> {% else … -
How to initialize db.sqlite3 database in pythonanywhere?
I'm neewbie in pythonanywhere. I've just deploy my django project and all seems to be OK except I need initialize ma database first and I don't know how to do this. I can I get a python shell? thanks for help -
Is it possible to use FastAPI with Django backend?
Well, it seems like nobody is talking about this. I'm a django developer and recently stumbled onto FastAPI framework, which seems to be promising among the community. Then I decided to give it a shot. But usually when you talk about building RESTful APIs with django you usually use Django Rest Framework(DRF). My question is: is anybody aware if it is possible to substitute DRF by FastAPI using django perks, like its ORM, and still have access to all FastAPI's async features? Up until now I only found one article on this. And the guy makes a poor integration, losing most of the exciting features of FastAPI. You can find it here In the FastAPI docs, they do mention that it is possible to redirect certain request to a WSGI application here. I hope this post starts a healthy discussion about the manner. -
How to load json api data to html template in angular?
Can anyone help me with a simple question(I guess). I'm trying to display a json file in a table through Django into an Angular front end app. I can view the data by console logging it, however I can't seem to get the data into the webpage. I know how to display the table in HTML. The specific problem is that the object which is fetched from the API does not appear in the HTML. component.ts import { AfterViewInit, ChangeDetectionStrategy, Component, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; import ApexChart from 'apexcharts' import { ApexOptions } from 'ng-apexcharts'; import { FinanceService } from 'app/modules/admin/dashboards/finance/finance.service'; @Component({ selector: 'app-finance', templateUrl: './finance.component.html', styleUrls: ['./finance.component.scss'], encapsulation : ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush }) export class FinanceComponent implements OnInit { _stockData: any; _portData: any; _effData: any; _calData: any; _labels: any; _table: any; constructor( private _financeService: FinanceService, ){ } ngOnInit(): void { this._financeService.getFinanceData() .subscribe((res: any) => { console.log(res); this._stockData = res.stocks; this._portData = res.port; this._effData = res.eff; this._calData = res.cal; this._labels = res.labels; this._table = res.table; console.log(res.table); this._prepareChartData(); }, (response) => { // Re-enable the form }); } template.html <div> <p>{{_table.Percentage}}</p> </div> json (as presented by the django API) { "stocks":[], "eff":[], "port":[], "cal":[], "labels":[], "table":{ "Percentage":{ "AD.AS":16.1, … -
Is there a way to construct pages with components
I am familiar with the concept of extends and include with django templates. However, I am trying to build up pages with components (which relates more to the "include" approach). Unfortunately, some elements on a page should be added in the header of the page (e.g. stylesheets) and some should be added at the end of the page (e.g. scripts). Is there a way to declare blocks (e.g. {% block extraheaders %}<link...>{% endblock %}) in the included files so they are placed in the correct region of the page? -
Multiple Database Instance for Django Project
I have created an django application where i am using ngnix server. My project is deployable for customer. One of client is saying that they won't allow us to their customer data in our database due to data privacy. So basically they want us to make a system where data will be store data on their database instance. Basically we want store their data on their system. I did some research and found django allow Multiple Database. But i am using ngnix also, please suggest me a good solution for such type of problem where it will be generic, let say in future other customer also come so i can provide them. My Questions - Using Django Multiple Approach using db_label will be a good approach? Is there other ways to achieve such problems? Is there a way using ngnix server redirecting, where ngnix will redirect data to particular database? Basically my django code will be on my instance. But they will provide us database credentials where we can access it. For login system my database will be using for checking credentials. But except user models, all other models will be on client system. Please provide me a best solutions. -
Nginx, Django Static files, Docker, Oh My
First, everything works great in my development system. On my deployment server I'm running Nginx in a docker and gunicorn serving my django app in a second docker. I've configured Nginx to serve up the static files. If I don't copy the contents of my static_cdn folder (of static files) to the Nginx docker, I see this error in the console window, GET http://<my_ip>:1337/static/pb_django/home.css net::ERR_ABORTED 404 (Not Found) and my web page text is left aligned. If I do copy the static files folder into the Nginx docker, I don't get the error message and my text is centered (as instructed by my css). However, if I then change my css, it seems to have no effect on the displayed page. Thoughts or suggestions? Here's my code: Nginx Dockerfile where static_cdn contains my static files FROM nginx:alpine RUN rm -f /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d/default.conf COPY static_cdn /static nginx.conf upstream pb_django { server web:8000 fail_timeout=0; } server { root /; listen 80; location / { proxy_pass http://pb_django/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_read_timeout 10m; proxy_connect_timeout 10m; client_max_body_size 700m; } location /static/ { } } -
To print products ,categories ,subcategories from django database in table form by retrieving it from databse
views.py enter code here from django.shortcuts import render enter code here#from django.template.defaulttags import registerenter code here enter code here#from django.http import RequestContext enter code herefrom django.http import HttpResponseRedirect enter code herefrom django.db import models enter code herefrom django.conf import settings enter code herefrom .models import Category,WebSubCategory,ProductMan,Inherit1 enter code here# Create your views here. enter code heredef home(request): enter code here #context = RequestContext(request) enter code here#category_list = Category.objects.order_by('-name')[:5] enter code here# subcategory_list = WebSubCategory.objects.order_by('-category')[:5] enter code here# product_list = ProductMan.objects.order_by('-subcategory')[:5] enter code here# inherit = Inherit1() enter code here# category_list.save() enter code here#subcategory_list.save() enter code here# product_list.save() enter code herecategory_list = Category.objects.all() enter code heresubcategory_list = WebSubCategory.objects.all() enter code hereproduct_list = ProductMan.objects.all() enter code hereinherited = Inherit1.objects.all() enter code here context_dict = {'webcat': category_list, 'websubcat':subcategory_list,'Product': enter code hereproduct_list,'Inherited' : inherited} enter code here print(context_dict) enter code hereprint(category_list) enter code hereprint(subcategory_list) enter code hereprint(product_list) enter code here# print(inherited) enter code here return render(request,'registration.html', {'dict' :context_dict} ) enter code heremodels.py enter code here from django.conf import settings enter code herefrom django.db import models enter code hereclass Category(models.Model): enter code here name = models.CharField(max_length=50, unique=True,null=True) enter code hereid = models.AutoField(primary_key=True,unique=True ,null =False) enter code here#slug = models.SlugField(verbose_name='Slug') enter code hereclass Meta: enter code … -
Create functional GIN index for FTS in Django with solely Django-orm
I want to create a GIN index for full-text search in Djnago. Is it possible to express something like this in Django ORM? Index on function(expression): CREATE INDEX index_name ON table_name USING GIN (to_tsvector(config_name, field_name)); without custom migrations with RUNSQL and staf... Thank you. P.S. SearchVectorField is not an option as i dont want to deal with triggers. -
How to group_by() column(RID) in Django
How to gourp_by() column based on RID. My Actual output Whatever values are displayed in the Months Names like [Jan, Feb,...., Des], all the values come from the one table column. I want to display all values in one particular column like the below image. Expected output -
django JsonResponce gives json with slaches as a string
I use django for sending some data in json but i get json string with slashes This code class LevelsSerialiser(Serializer): def end_object(self, obj): # self._current has the field data indent = self.options.get("indent") if not self.first: self.stream.write(",") if not indent: self.stream.write(" ") if indent: self.stream.write("\n") data = {} data['id'] = self._value_from_field(obj, obj._meta.pk) data.update(self._current) json.dump(data, self.stream, **self.json_kwargs) self._current = None class LevelsView(MainView): def get(self, request, *args, **kwargs): serializer = vocabulary.customserializers.LevelsSerialiser(); return JsonResponse(serializer.serialize(vocabulary.models.Level.objects.all()), safe=False) gives me this json with slashes as string "[{\"id\": 1, \"name\": \"Upper Intermediate\", \"code\": \"B1\"}]" But i need something like this, [ { "id": 1, "name": "Upper Intermediate", "code": "B2" } ] what i am doing wrong? -
how to pre run rest APIs and store into Redis Cache with Django
I have a dashboard where customers can request forms which runs a REST API. But when they request the form it takes a while (around two minutes) to come back if it's the first time running the request. However, if I create a program/dashboard that pre runs these API calls which preloads the forms into our Redis Cache it would speed up the customer request to around (5 seconds) because we clear our Redis Cache once a week. -
Wrong Rendering in Html?
I am using my website to send emails and the email is an html page... when i view the html page in the browser it looks as follows when i send the email it looks as follows I'll share my html file now.. .product_title { font-size: 20px; text-transform: uppercase; letter-spacing: .2em; padding-top: 15px; padding-bottom: 10px; } .text-center { text-align: center; margin: 0 auto; } .table-bordered th, .table-bordered td { border: 1px solid #dee2e6 !important; } .table { border-collapse: collapse !important; } .text-left { text-align: left !important; } .text-right { text-align: right !important; } .r { float:right; } .text-center { text-align: center !important; } .d { display: inline; } <div class="container"> <span style="float: left;"> <h1 style="color:#003366;">Wiss</h1> <br></span> <span style="float: right;"><h1 style="color:#003366;">Order Customer</h1> <br></span> <br> <table class="table"> <tr> <td class="text-left" colspan="2"> <b>Street: </b>Nii Martey Tsuru St <br> <b>Address: </b>Spintex Road <br> <b>City: </b>Accra <br> <b>Phone: </b>Phone Num <br> <b>Email: </b> Email <br> </td> <td class="text-left r" colspan="2"> <b>Customer: </b> {{ order.customer }} <br> <b>Address: </b>{{ adr.address }} <br> <b>City: </b>{{ adr.city }} <br> <b>zipcode: </b>{{ adr.zipcode }} <br> <b>Phone: </b>{{ order.customer.phone}} <br> <b>Email: </b>{{ order.customer.email}} <br> </td> </tr> </table> <div class="text-center"> <br> <h1 class="product_title"> Order Details </h1> <br> <table class="table table-bordered"> <tr> … -
Django Rest Framework simple Endpoint to receive json without Serializer and Model
I'm pretty new to django and trying to create a simple Post-Endpoint for receive the raw Json from body and response with an own json string. My structure looks like following : I have already seen some snippets here in SO so I know its possible. But I miss the steps how to do and where to do. I would like to do : Add new controller in pfc App that listen for request Define the Endpoint Wire up an routing for this controller Everything i could found is always to do with serializers and models. But I need only the Bodys JSON. -
How to get results of only the primary key and not all results in django-rest-framework?
In my django app, i need to check if a user exists using a phone number. The login is done using phone number and OTP. I can check if the user exists by a get request to "/api/profiles/<primary key here>/". However if I request "/api/profiles/" i get a list of all the users in the database. I need my app to return nothing if requesting "/api/profiles/" and user details if requesting "/api/profiles/<primary key here>/" How do I do this? -
Pre-populate Django form with CreateView using reverse relationship
I've searched the forums and various other places and can't really find what I'm looking for. I have five models: Hydrant, Meter, AssetType, WorkOrderActivity and Workorder. # models.py class Hydrant(models.Model): uniqueId = GISModel.CharField(max_length=100) geom = GISModel.PointField() def__str__(self): return self.uniqueId class Meter(models.Model): uniqueId = GISModel.CharField(max_length=100) geom = GISModel.PointField() def__str__(self): return self.uniqueId class AssetType(models.Model): typeChoices = ( ('Hydrant', 'Hydrant'), ('Meter', 'Meter'), etc... ) name = models.CharField('Asset Type',max_length=30,choices=typeChoices) def __str__(self): return self.name class WorkOrderActivity(models.Model): assetType = models.ForeignKey( 'AssetType', related_name='workorderactivities', on_delete=models.SET_NULL, blank=True, null=True ) activityChoices = ( ('Paint Hydrant', 'Paint Hydrant'), ('Flush Hydrant', 'Flush Hydrant'), ('Read Meter', 'Read Meter'), etc... ) activityType = models.CharField('Activity Type', choices=activityChoices ,max_length=50) def __str__(self): return self.activityType class Workorder(models.Model): assetType = models.ForeignKey(AssetType, related_name='typeOfAsset', on_delete=models.SET_NULL) woActivity = models.ForeignKey(WorkOrderActivity, on_delete=models.SET_NULL) hydrant = models.ForeignKey(Hydrant, related_name='workorders', on_delete=models.SET_NULL) meter = models.ForeignKey(Meter, related_name='workorders', on_delete=models.SET_NULL) description = models.TextField('Description', max_length=250, blank=True, null=True) def __str__(self): return self.description What I'm trying to do is from a leaflet map where I see all of my assets (Hydrants and Meters), click on an asset to see the popup information where I have a button to 'Create Workorder'. In my normal 'create_workorder' view, where the user would not be creating the workorder from the map, all of my dropdowns are chained, meaning based … -
Decode uft8 in html (template) [closed]
I have a problem I get a queryset of Items by: ingredients = Zutaten.objects.filter(rezept=rezept_id) And inside my context: "ingredients_queryset" : ingredients, And I use it in HTML like this: {% for i in ingredients_queryset %} <li>{{i.zutat}}</li> {% endfor %} But now I have the problem that inside of the queryset strings are which are encoded with utf8 and now I need to decode them. I'm not sure how I can do it. So I hope you can help me. Thank you! -
How to show javascript alert via Django
I want to show alert after the user successfully logs in and call some other javascript function.