Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to call a python(.py) script from a link on the DJango webpage?
All, I have just started learning python and django and I was wondering if there's a way to call a python script (Test.py) from a link on the django page. So far I have created a django project (TestDjango) and I have these files in that folder: __init__.py settings.py urls.py views.py Test.py This is what I have in my views.py script so far: from django.http import HttpResponse def index(request): return HttpResponse('''<h1>Test</h1> <p> <!-- <a href = "https://www.python.org/"> Python </a> </br> --> </p> ''' and in my urls.py I am calling it this way: from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name ='index'), ] When I run this on the server I get a simple page with title - "Test" and a clickable "Python" link which takes me to the python website. However, what I am looking for is a way to add a link on that django page which would call my "Test.py" script when you click on, say "Test". I have done some visualizations in that script with some mocked up data that I'd like to see on my webpage. It might be something very simple, but, β¦ -
Error in python django when trying to save a user manualle
I am experimenting some error when i try to create a new user manually in django This is my code: from django.contrib.auth.models import User newuser = User() newuser.username = request.data['username'] newuser.first_name=request.data['first_name'] newuser.last_name=request.data['last_name'] newuser.email = request.data['email'] newuser.is_active=True newuser.set_password(request.data['password']) newuser.full_clean() newuser.save() The code is able to insert correctly the user, i see the changes in my database, however the code breaks after saving the user with this File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 413, in create obj.save(force_insert=True, using=self.db) TypeError: save() got an unexpected keyword argument 'force_insert' I really can not figure out what the problem is -
Django article format: why the articles I posted are showed in a mess?
I tried use django/admin to post my article. But when I checked the articles I posted, I found they were in a mess. the articles contain html labels and other unkonwn characters. I don't why this happens. So could anyone help me check what's the problem? -
i'm having a problem with requests library Django
all. trying to access a foo.com using python requests library from the django application. i'm using same versions of all dependencies locally and in production. django application is hosted on elastic beanstalk. locally requests to foo.com returns status code 200 . while production request to the same page is always 403 . also , production requests to bar.com returns 200 . there is nothing in the aws EB logs. where should i look for clues for this issue? python3. requests 2.20.1. -
CHECKBOXES instead radio buttons at DJANGO ADMIN?
If you are looking for a way to put radio buttons in Django using MODELS you only need do something like this (e.g): in models.py class MonitoringPointsClass( models.Model ): monitoring_has_power = models.BooleanField( null = True, max_length = 1, default = None, choices = YES_NO, name = 'monitoring_has_power', blank = True, verbose_name = _( 'Electrified' ), ) ... in admin.py class MonitoringPoints_InLine_MODELadmin( admin.ModelAdmin ): model = MonitoringPointsClass radio_fields = { 'monitoring_has_power' : admin.HORIZONTAL, ... } checkboxes_fields = { 'it's do not exists I guess, why?!'... } But I can't find anyway to do this using checkboxes instead radio buttons -
Get error message from imported/external validator to print django
I am trying to build a simple user registration page. I want it to include a captcha for validation purposes. I am using django-simple-captcha for this purpose. (If there's a better library, tell me...) So far everything is working great, EXCEPT that when a captcha is incorrect the user is not notified--they are simply returned to the registration screen. How can I get a specific ValidationError message printed when the captcha is invalid? (I'm also using django-crispy-forms, if that makes any difference) template: {% extends "base.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">Registration</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' %}">Log in</a></small> </div> </div> {% endblock content %} form model: class UserRegisterForm(UserCreationForm): email = forms.EmailField(validators=[validate_email]) captcha = CaptchaField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] # including 'captcha here didn't seem to make a difference and the view: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): *do unrelated things* return redirect('login') else: form = UserRegisterForm() return render(request, 'register-template-url', {'form': form}) -
Django Model Admin - Traffic Light Alert
I have a series of models all the same as this one: class Documents(models.Model): id = models.AutoField(primary_key=True) paper = models.ForeignKey( 'Paper', models.DO_NOTHING, blank=True, verbose_name='Paper') date = models.DateField('Date') expired_date = models.DateField('Expired Date') alert_warning_gg = models.SmallIntegerField( 'Alert Warning gg', blank=True, null=True) enable = models.BooleanField('Enable') def __str__(self): return str(self.id) or '' class Meta: managed = False db_table = 'Documents' The paper field is composed of a foreignkey that connects to another model having a field called a traffic_light. I need a function to notify me with a traffic light (red,yellow,green) when the date field expire inside the model is expiring(yellow), expired (red) and not expired(green), putting it in comparison with today's date for the traffic light red and green; and that use the alert_warnig_gg field (here you enter the number of days before the yellow light is marked). I would like the result of the function to be marked in the traffic_light field of the model Paper. For now i have tested this function on a single model, so that it gives me the result in a column of the ModelAdmin. def custom_column(self, obj): if obj.expired_date < datetime.datetime.now(): retval = ('red.jpg') else retval = ('green.jpg') return "<img src='%s' alt='%s' />" % retval custom_column.short_description β¦ -
Redirect to exact category with django mptt
For my category view I have following code. def getOffers(self, request,hierarchy = None): category_slug = hierarchy.split('/') parent = None root = Category.objects.all() for slug in category_slug[:-1]: parent = root.get_object_or_404(parent=parent, slug = slug) try: instance = Category.objects.get(parent=parent,slug=category_slug[-1]) except: instance = get_object_or_404(OfferClass, slug = category_slug[-1]) return render(request, "offers/offer_detail.html", {'instance':instance}) else: return render(request, 'offers/offer_list.html', {'instance':instance}) Also in urls.py path('category/<hierarchy>/', views.OfferClass.getOffers,name='category_terr'), And the main problem starts probably in template and in urls. My template looks like this <a href="{% url 'category/Terraristic' %}"> .... On my main page I would like to have a few cards with links to categories but what is correct syntax for templates and for urls ? After this I would like to filter also via subcategories for previously choosen categories. Thanks for all responses ! -
My User Profile Update form is not appearing in my template
My User profile update form is not appearing in my template. I can only see 'Update' button and legend name. But I don't see the form. Any ideas? Here is my forms.py class UserUpdateForm(UserChangeForm): username = forms.CharField() email = forms.EmailField() class Meta: model = User fields = ['username', 'email' ] Here is my views.py @login_required def profile(request): u_form = UserUpdateForm context = { 'u_form': u_form, } return render(request, 'users/user_detail.html', context) Here is my template called user_detail.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Profile Info</legend> {{ u_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> </form> -
Django 2.1.7, IntegrityError, FOREIGN KEY constraint failed
I have a problem with ForeignKey. Or rather, when creating the ForeignKey for the Custom User Model, an error appears: #CustomUserModel class Usr(AbstractBaseUser): username = models.CharField(max_length=30, validators=[ RegexValidator( regex=USERNAME_REGEX, message='Username must be alphanumeric or numbers', code='invalid_username' ) ], unique=True) objects = UsrManager() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) def has_perm(self, perm, obj=None): # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): # Simplest possible answer: Yes, always return True USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] #Model with ForeignKey class Posts(models.Model): title = models.CharField(max_length=50, unique=True) text = models.CharField(max_length=300) author = models.OneToOneField(get_user_model() ... default=1, swappable=True, related_query_name='post', db_constraint=True, related_name='posts', on_delete=models.CASCADE) I apologize in advance for possible flaws in the code and grammatical errors. Thank you in advance! -
How to setup Two-step verification in Django?
I was making a website for my college and i have user account functionality in it by Djnago.AllAuth, but i am very confused about using 2_Step Verification, So user gets an email when registering himself. Help me out please. Thank you. web. link - tinyurl.com/kratikjain -
running flow through code Django-Viewflow
I want to run my process entirely by code. I've managed to start a process but a I can't run the next part of the process. I tried using the "flow.Function" and calling my desired function but i't says 'Function {} should be called with task instance', 'execute'" and the documentation on this subject is'nt very clear. flows.py @flow.flow_start_func def create_flow(activation, campos_proceso, **kwargs): activation.process.asignador = campos_proceso['asignador'] activation.process.ejecutor = campos_proceso['ejecutor'] activation.process.tipo_de_flujo = campos_proceso['tipo_de_flujo'] activation.process.estado_del_entregable = campos_proceso[ 'estado_del_entregable'] activation.process.save() activation.prepare() activation.done() return activation @flow.flow_func def exec_flow(activation, process_fields, **kwargs): activation.process.revisor = process_fields['revisor'] activation.process.save() activation.prepare() activation.done() return activation @frontend.register class Delivery_flow(Flow): process_class = DeliveryProcess start = flow.StartFunction(create_flow).Next(this.execute) execute = flow.Function(exec_flow).Next(this.end) end = flow.End() views.py def Execute(request): #campos_ejecucion, request): campos_ejecucion = { 'ejecutor':request.user, 'revisor':request.user, 'observaciones_ejecutor':'Este es un puente magico', 'url_ejecucion':'https://www.youtube.com/watch?v=G-yNGb0Q91Y', } campos_proceso = { 'revisor':campos_ejecucion['revisor'] } flows.Delivery_flow.execute.run() Entregable.objects.crear_entregable() return render(request, "Flujo/landing.html") -
Dropdown menu in safari not showing dropdown-items
My dropdown menu works on Chrome(Desktop & Mobile) and Firefox(Desktop & Mobile) but seems to not work on Safari (Desktop) as well as Chrome (Tablet). Here's what it looks like working on Chrome And here's how it looks on Safari HTML: <button type="button" id="platform" class="btn btn-orange dropdown-toggle mr-2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Select Platform </button> <div class="dropdown-menu" id="plat-form-options"> {% for platform in game.platform.all %} <option class="dropdown-item" value="{{ platform.id }}" onclick="platFormSelect('{% url 'title-updates-ajax' slug=game.slug platform_id=platform.id %}', '{{ platform }}')">{{ platform }}</option> {% endfor %} </div> Javascript: $(document).ready(function () { if ($("#plat-form-options option").length > 0) { $("#plat-form-options option")[0].click(); } }); function platFormSelect(url, platform) { $('#platform').text(platform); $.get(url, function (response) { $('#updates_data').html(response); }) .done(function () { }) .fail(function () { }); } -
Experiencing issues Changing form traits for users
Im experiencing an issue being able to change user profile data traits for users once I set them with the initial form in forms.py to override the generic django settings. class EditProfileForm(UserChangeForm): class Meta: model = User fields=('username','first_name','last_name','email','street','city','state','zipcode','country',) It fails when I try this, but works if I remove street, city, state, zipcode, and country, even though the registration form allows it to fill in all of this information. The original form allows me to set all of this information with the registration form in forms.py without issue, and ive confirmed its working without flaw. However, it wont let me edit the setting once I set it. Any insight would be absolutely appreciated. I believe it may be because the superuser doesnt have these fields, and if so, if I could set a default='' if thats possible? Im not aware of being able to do that though for previously existing users, and Ive also tried erasing all users and attempting it with no users, but that didnt work either. -
postgresql auth django (password authentication failed for user "BlogAdmin2")
I followed the tutorial posted by Digital Ocean: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04#create-and-configure-a-new-django-project (How to set up django with postgres nginx and gunicorn on ubuntu) I created a git hub private repo with the website and when I created the postgresql database with the folowing commands: CREATE DATABASE PiaBlog; CREATE USER BlogAdmin WITH PASSWORD 'Andrei1234'; ALTER ROLE BlogAdmin SET client_encoding TO 'utf8'; ALTER ROLE BlogAdmin SET default_transaction_isolation TO 'read committed'; ALTER ROLE BlogAdmin SET timezone TO 'UTC'; GRANT ALL PRIVILEGES ON DATABASE PiaBlog TO BlogAdmin; \q and here is my django database config: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'PiaBlog', 'USER': 'BlogAdmin2', 'PASSWORD': 'Andrei1234,', 'HOST': 'localhost', 'PORT': '', } } When I run python manage.py migrate I get : django.db.utils.OperationalError: FATAL: password authentication failed for user "BlogAdmin2" FATAL: password authentication failed for user "BlogAdmin2" Does somebody know why do I get this problem I spent an hour searching for a typing error and I never found it. -
How to use Django models outside of Django?
Following this guide, I am able to use models outside of Django with the following file structure by calling python main.py. βββ data β βββ __init__.py β βββ migrations β β βββ __init__.py β βββ models.py βββ main.py βββ manage.py βββ settings.py where main.py looks like this: import os, django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') django.setup() from data.models import Foo, Bar #... print(Foo.objects.all()) #this works fine What I want to do is turn this into a "package" called db that looks like this: βββ data β βββ __init__.py β βββ migrations β β βββ __init__.py β βββ models.py βββ __init__.py βββ manage.py βββ settings.py And in the __init__.py of the db package, I want to do this: import os, django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') django.setup() from data.models import Foo, Bar # ... from django.db import connection __all__ = [ 'connection', 'Foo', 'Bar', #... ] So I can call the db package from test.py (which is in the same directory as db) like this: import db print(db.Foo.objects.all()) #this throws an error "no module named data" or like this: from db import Foo print(Foo.objects.all()) # this throws an error "no module named settings" Is there a way I can use Django's models without having to call: os.environ.setdefault('DJANGO_SETTINGS_MODULE', β¦ -
Pass a rendered view to another app's view in Django
I'm trying display the outputs of 2 apps on a same web page, but am encountering issues when trying to use the solution proposed here. I have a "main_app" handling the content of most of the page, and would like to add the output of a "sub_app" (i.e. a rendered <div> element) on the same page. Here's how I collect the output of sub_app in a main_app view: from sub_app.views import sub_app_view # def main_app_view(request): my_sub_app_html = user_tests(request) #supposed to get rendered HTML content from sub_app context = { 'sub_app_html ': my_sub_app_html, } return render(request, 'main_app.html', context) Then the view in sub_app: def sub_app_view(request): context = { 'sub_app_context': "foo", } return render(request, 'sub_app/sub_app.html', context) main_app.html contains: <p> {{ sub_app_html }} </p> and sub_app.html: <div id="mydiv"> {{ sub_app_context }} </div> But instead of correctly displaying the rendered HTML from sub_app_view, what is shown in main_app.html in the browser is: <HttpResponse status_code=200, "text/html; charset=utf-8">. Is there a solution to this, or a better way to achieve linking between apps? -
Call a model method from the views
I am new at django and I am creating a React/Django app and want to tell a model method to run with a post request from my react frontend. from django.urls import path from . import views urlpatterns = [ path('toggle/', views.Toggle) ] class Entry(models.Model): ... def toggle_paused(self): some code from django.shortcuts import render from rest_framework import viewsets from .models import Entry class Toggle(viewsets.ModelViewSet): Entry.toggle_paused() Is there a way to call a method from the view or maybe a better way to do what I am trying to accomplish? -
Angular Material theme/styles not showing up in Django
So I've written a Django REST Framework API, and am now working on the Angular front end, I serve the angular app through Django using and calling the appropriate js. I've specified Angular's build output to be to the same directory as my Django static files directory. The theming and CSS works when I connect directly to the Angular service (localhost:4200) but not when it is being served through Django (localhost:8000) I've imported the relevant modules in my material.module.ts and applied a global theme in styles.css. Any direction? I don't see any errors anywhere that I can try to diagnose, so I really have no idea what's going on. -
Gunicorn Django Setup Issues
I am attempting to setup a DigitalOcean Droplet to hold a Django application, and I am following this overview: https://simpleisbetterthancomplex.com/tutorial/2016/10/14/how-to-deploy-to-digital-ocean.html However, I am getting gunicorn errors following along with the script provided and I cannot seem to work it out to work, although I feel like I have a good idea what the file system structure is. Can someone help? Here is my directory structure: exactestate@ExactEstateDroplet:~$ cd ../ exactestate@ExactEstateDroplet:/home$ cd ../ exactestate@ExactEstateDroplet:/$ ls bin dev home initrd.img.old lib64 media opt root sbin srv tmp var vmlinuz.old boot etc initrd.img lib lost+found mnt proc run snap sys usr vmlinuz exactestate@ExactEstateDroplet:/$ ^C exactestate@ExactEstateDroplet:/$ cd home exactestate@ExactEstateDroplet:/home$ ls exactestate exactestate@ExactEstateDroplet:/home$ cd exactestate exactestate@ExactEstateDroplet:~$ ls ExactEstate bin include lib local logs run share exactestate@ExactEstateDroplet:~$ cd bin exactestate@ExactEstateDroplet:~/bin$ ls activate activate.fish easy_install gunicorn_start pip2 python python2 wheel activate.csh activate_this.py easy_install-2.7 pip pip2.7 python-config python2.7 exactestate@ExactEstateDroplet:~/bin$ cd ../ exactestate@ExactEstateDroplet:~$ cd ExactEstate exactestate@ExactEstateDroplet:~/ExactEstate$ ls ExactEstate app.yaml forms interface_login interface_management interface_resident interface_security objects requirements.txt utils README.md cron.yaml interface_admin interface_maintenance interface_onsite interface_root manage.py objects_client templates exactestate@ExactEstateDroplet:~/ExactEstate$ ExactEstate is my Django Project Directory Here is my gunicorn_start file #!/bin/bash NAME="ExactEstate" DIR=/home/exactestate/ExactEstate USER=exactestate GROUP=exactestate WORKERS=3 BIND=unix:/home/exactestate/run/gunicorn.sock DJANGO_SETTINGS_MODULE=ExactEstate.settings DJANGO_WSGI_MODULE=ExactEstate.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ β¦ -
Django : How to access a localhost database hosted by a user?
I want to develop a website (with is own database) where all the users will host a tiny database on their computer (SQlite or mySQl). I need to find a way for the users to access their local database and work with it on the website. I read the docs concerning the multi-database (https://docs.djangoproject.com/en/dev/topics/db/multi-db/) we can in the settings tell to django which database it needs to connect to. For example : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } How to tell django to connect to the database hosted by the user ? I assume that 127.0.0.1 will refer ton localhost of the django server. Am i right ? -
Retrofit 2 Android : "message ":"incorrect type, Expected pk value, received str"
I am trying to call an api on server using POST method. However, I am receiving 400 Bad Request, with above message in error body. I tried to call the api using the RestClient, and still got the same error. I am using Retrofit 2 on Android. I don't know what is the problem. Here is my code. public class NetworkRepo { private static NetworkRepo networkRepo = null; private ApiServer apiServer; private NetworkRepo(){ Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constants.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); apiServer = retrofit.create(ApiServer.class); } public static synchronized NetworkRepo getNetworkRepo(){ if(networkRepo == null){ networkRepo = new NetworkRepo(); } return networkRepo; } public void getRegister(DoctorsPayload doctorsPayload, Callback<RegisterationResponse> callback){ Call<RegisterationResponse> call = apiServer.getRegister(doctorsPayload); call.enqueue(callback); } } -
ValueError: dictionary update sequence element #0 has length 28; 2 is required
I am getting this error in one of my django views. What does it mean? How can I solve this? Below is the view where I am getting the error, def duedate(request): data = Task.objects.all() total_count = data.count() pending_count = 0 for dat in data: if dat.done == False: pending_count += 1 today = datetime.date.today() context = {'data':data, 'today':today, 'count':total_count, 'pending':pending_count} return render(request, 'todoapp/index.html', context) -
Django Forms or own html forms?
Is it a good practice to write own forms in django templates isntead of creating built-in django forms? Like this: <div class="container"> <div class="row justify-content-center mt-5"> <div class="col-4"> <form method="post" > {% csrf_token %} <div class="form-group"> <label for="username">UserName</label><br> <input type="text" id="username" placeholder="username" name="{{ form.username.name }}" class="form-control"> </div> <div class="form-group"> <label for="password1">Password</label><br> <input type="password" id="password1" placeholder="password" name="{{ form.password1.name }}" class="form-control"> </div> <div class="form-group"> <label for="password2">Password</label><br> <input type="password" id="password2" placeholder="password" name="{{ form.password2.name }}" class="form-control"> <span id="help"></span> </div> <input type="submit" class="btn btn-primary form-control" value="Send"> </form> </div> </div> </div> -
Developing a queryset using a "through" foreign key
I'm looking to build a queryset of UserCarts that have UserCartItems that are related to a particular UserService: For example, if a UserService is "Painting", I'd like to get a queryset of all UserCarts that had a UserCartItem with "Painting" as a Foreign Key. Models.py class UserService(models.Model): title = models.ForeignKey(IndustryService, on_delete=models.CASCADE) class UserCartItem(models.Model): cart = models.ForeignKey("UserCart", on_delete=models.CASCADE, default=None) title = models.ForeignKey(UserService, on_delete=models.CASCADE, default=None) class UserCart(models.Model): items = models.ManyToManyField(UserService, through=UserCartItem) views.py userservice = UserService.objects.get(id=2) usercarts = UserCart.objects.filter(items__title=userservice) This doesn't seem to be working. I get the following error: Cannot query "X": Must be "IndustryService" instance. Thanks for your help!