Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Viewflow - start process with Django model post_save signal
Is there a way to start a Viewflow process with Django model post_save signal. I managed to do this: //start viewflow process start = ( flow.StartSignal(post_save, create_dest_flow) .Next(this.approve) ) //create flow function def create_dest_flow(**kwargs): print("Test") pass The "Test" string is printed for every save on any model. If I add activation to the create flow function parameteres I get an error: missing 1 required positional argument: 'activation'. How to start the flow only on specific model post_save signal? -
I get this error when i run python manage.py
So i am working with django. after setting up my urls in both applications, i get this error "file "C:\Users\Eric\Anaconda3\envs\myDjangoEnv\lib\site packages\django\urls\resolvers.py", line 542, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'alerts.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import". when i run python manage.py migrate.However, when i comment out include in my alerts.urls file it works fineenter image description here how can i fix this? i have attached my urls.py files this is my accouts.urls file from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ path('login/',auth_views.LoginView.as_view(template_name='accounts/login.html'), name ='login'), path('logout/', auth_views.LogoutView.as_view(), name ='logout'), path('signup/', views.SignUp.as_view(), name ='signup'), ] this is my main project url file from django.contrib import admin from django.urls import include,path from django.urls import path,include from . import views urlpatterns = [ path('', views.HomePage.as_view(), name="home"), path('admin/', admin.site.urls), path('test/', views.TestPage.as_view(), name="test"), path('thanks/', views.ThanksPage.as_view(), name="thanks"), path('accounts/', include("accounts.urls", namespace="accounts")), path('accounts/', include("django.contrib.auth.urls")), -
Is there any way to change username field label in user authentication login page?
Right now login page looked like this I want to change label of username field to Team Name Note: I'm using builtin LoginView -
View function is not working properly after including bootstrap
I am writing an HTML page that takes input from user via html form and "POST" method and submits it to a link. the link is attatched to a view which accesses a data base entry based on the info passed by the user. But, when i include bootstrap code for navbar header in that HTML page it is not able to access the database. my view function is def favorite(request,album_id): album = get_object_or_404(Album,id = album_id) try: selecte d_song = album.song_set.get(id = request.POST['song']) except: return render(request,'music/detail.html',{'album':album,'error_message':'No song selected!!'}) else: selected_song.isFavorite = True selected_song.save() return render(request,'music/detail.html',{'album':album}) the HTML page is - {% extends 'music/base.html' %} {% block body %} {% if error_message %} <p><strong>{{error_message}}</strong></p> {% endif %} <img src = "{{album.album_logo}}"> <h1>The album is {{album}} </h1> <h2>Artist - {{album.artist}}</h2> <h3>The songs in this album are: </h3> <form action = "{%url 'music:favorite' album.id %}" method = "post"> {% csrf_token %} {% for song in album.song_set.all %} <input type = "radio" id = "song{{forloop.counter}}" name = "song" value = "{{song.id}}"> <label for = "song{{forloop.counter}}"> {{song.song_title}} {% if song.isFavorite == True %} ' fav ' {% endif %} </label><br> {% endfor %} <input type = 'submit' value = "Favorite"> </form> </body> </html> while the … -
How do I login with with the user credentials in Django?
I'm working on a simple login and logout app in Django. I wrote two views one for login and another for register. Register view is working as expected. But login view is causing issues. I'm using form.is_valid() in login view. That is where the issue is arising. If I print the form in else block, it is saying A user with that username already exists. This is happening even before trying to authenticate the user. Some one help me with this. from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.http.response import HttpResponse from django.shortcuts import render from notes.forms import UserForm def login(request): if request.method == 'GET': return render(request, 'login.html') elif request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user: login(request, user) return HttpResponse("Logged in") else: return HttpResponse("Wrong creds") else: print(form) return HttpResponse("else of is_valid()") def register(request): if request.method == 'GET': return render(request, 'register.html') elif request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] existing = User.objects.filter(username=username) if existing: return HttpResponse('Username is already taken') else: User.objects.create(username=username, password = password, email=email) return HttpResponse("User created with "+ username +" username") else: return HttpResponse("Hi") -
Reverse for 'user' with arguments '('',)' not found. 1 pattern(s) tried: ['rubies/users/(?P<user_id>[0-9]+)/$']
NoReverseMatch at /project/users/1/stories/1/ Reverse for 'user' with arguments '('',)' not found. 1 pattern(s) tried: ['project/users/(?P[0-9]+)/$'] Does anyone have any idea why I face this error when I press "python manage.py runserver"? It used to work just fine and now it just doesn't. I've seen that the problem might be with user_id or user.id, but I can't really see it! Here is my code: project/views.py def story(request, user_id, story_id): if story_id is not None: story = get_object_or_404(Story, pk=story_id) else: story = Story() story.user_id = user_id if request.method == 'POST': story.title = request.POST['title'] story.story = request.POST['story'] story.date = timezone.now() story.save() return HttpResponseRedirect(reverse('rubies:story', args=(user_id,))) else: context = { 'user_id': user_id, 'story_id': story_id, 'title': story.title, 'story': story.story, 'likes': story.likes, 'comments': story.comments } return render(request, 'rubies/story.html', context) project/urls.py urlpatterns = [ path('', views.index, name='index'), path('register/<int:user_id>/', views.register, name='register'), path('login/<int:user_id>/', views.login, name='login'), path('users/<int:user_id>/', views.user, name='user'), path('users/<int:user_id>/stories/<int:story_id>/', views.story, name='story'), ] project/templates/project/story.html {% extends "rubies/base.html" %} {% block content %} {% if story_id %} <div class="post-preview"> <h2 class="post-title"> {{ story.title }}</h2> <p class="post-subtitle"> {{ story.story }} </p> <p class="post-meta">Posted by <a href="{% url 'rubies:user' story.author.id %}">{{ story.author.username }}</a> on {{ story.date }} <i class="fas fa-thumbs-up"> {{ story.likes }}</i> <i class="fas fa-comment"> {{ story.comments }}</i> </p> </div> <div class="post-preview"> <h2> … -
How to overwite django password_reset_confirm page?
I am a new Django developer. I am trying to overwrite django password_reset_confirm.html page with the below HTML file(change_pwd.html). <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="{% static "icon/tab_logo.png"%}"> <!-- Bootstrap --> <link href="{% static "web/vendors/bootstrap/dist/css/bootstrap.min.css" %}" rel="stylesheet"> <!-- Custom Theme Style --> <link href="{% static "web/src/css/login.css" %}" rel="stylesheet"> <!-- jQuery --> <script src="{% static "web/vendors/jquery/dist/jquery.min.js" %}"></script> </head> <body > <div class="vertical-center"> <div class="container"> <div class="row"> <div class=" col-md-4 col-md-offset-4"> <div id="loginbox" > <h1 class="text-center title">Change Password</h1> </br></br> <form id="passwordform" role="form" method="post" action="."> {% csrf_token %} <div style="margin-bottom: 25px" > <input type="password" class="pwd" name="new_password1" placeholder="password" autocomplete="off"> </div> <div style="margin-bottom: 25px" > <input type="password" class="pwd" name="new_password2" placeholder="repeat password" autocomplete="off"> </div> <div style="margin-top:10px" > <!-- Button --> <input id="btn-change-pwd" class="btn btn-primary btn_extend " type="submit" value="Submit"> </div> </form> </div> </div> </div> </div> </div> </body> </html> I have also overwritten the project's Urls.py as below: path(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', password_reset_confirm, {'template_name' : 'change_pwd.html'}, name='password_reset_confirm'), When I reset password, the page is redirected to admin/templates/registration/password_reset_confirm.html page and then displays below message: The password reset link was invalid, possibly because it has already been used. Please request a new password reset. Based … -
Django template if choice field
im currently trying to figure out how i can check if a status does apply to a users request or not. models.py class CategoryRequests(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) status = StatusField() STATUS = Choices('Waiting', 'Rejected', 'Accepted') views.py def view_profile_categoy_requests_accepted(request, pk=None): if pk: user = get_user_model.objects.get(pk=pk) else: user = request.user args = {'user': user} return render(request, 'myproject/category_request_accepted.html', args) But at the template this seems to be wrong. template.html {% if user.categoryrequests.status == 'Waiting' %} Thanks in advance -
Javascript Python Communication
I am currently working on a web app project in a django frame. This app let users take a picture through webcam(code written in javasript inside a html file), and I hope to transmit this image to a .py python file, is there a way I can make it? -
Channels server development cannot migrate
I'm following the tutorial to create a CHAT to learn using Channels. In this way I'm following this tutorial : https://channels.readthedocs.io/en/latest/tutorial/part_2.html I have done everything. When I apply the command: python manage.py migrate I get : Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: No migrations to apply. Whereas what is expected : Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying sessions.0001_initial... OK And when I run my Channels server developement (ASGI), I go on the url http://127.0.0.1:8000/chat/lobby/ and I still get on my browser's Javascript console the message error : WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/lobby/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET I don't know why it is not working. In my settings.py file of the project : INSTALLED_APPS = [ 'channels', 'chat', 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Last thing : I have not been able to install Docker because I'm on Windows 10 HOME. Could it be the … -
Why can't I use Jinja syntax in Javascript for a django site?
So for those of us who use Python and Django framework to develop a website, there is this awesome tool known as jinja which can be used as a template engine. For example: Instead of hard-coding an import like this: <script src="assets/js/onebutton.js"></script> We can do this: <script src="{% static 'assets/js/onebutton.js' %}"></script> In this case, it automatically searches for a folder named static and goes inside to look for the needed code. But why isn't it possible to use jinja template in Javascript. For example: homepage.html <script src='whatever.js'></script> <p>Another example</p> <button id="clickme"> click me </button> whatever.js $(function() { $('#clickme').click(function(){ $.ajax({ headers : {'X-CSRFToken': getCookie('csrftoken')}, type: "POST", url: '{% url "func" %}', //<--Problem arise here datatype:"json", data: {}, success: function(data){ var new_template = '<h1> %firstmsg% </h1>'; var new_frontend = new_template.replace('%firstmsg%',data.message); console.log(new_frontend); document.getElementById('wor').innerHTML+=new_frontend; } }); } } Django would recognize the url in the AJAX request as /'{% url "func" %}' instead of /func The only way to solve this is to move the entire code from whatever.js into the homepage.html under <script></script> brackets. Perhaps we need to import something for Jinja templating to work? -
What Happens When Django-Rest-Framework Receives a Request?
I'm trying to understand how DRF works, specifically the GenericViewSet view. What is the sequence of actions upon request retrieval? Which component receives the request? To where the request is passed? When does validation happen? Context: All of my field-choices enums are lowercased, so I was trying to lowercase all values that arrive (from uncontrolled 3rd parties). Django's model validation fails before any of the exposed GenericViewSet methods are called. How can I process request data before model validation? Can anyone shed some light on the topic? -
django aws error while creating in elastic benstack
errors: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 635, in _build_master ws.require(__requires__) File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 943, in require needed = self.resolve(parse_requirements(requirements)) File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 834, in resolve raise VersionConflict(dist, req).with_context(dependent_req) pkg_resources.ContextualVersionConflict: (urllib3 1.24.1 (/home/soubhagya/.local/lib/python3.5/site-packages), Requirement.parse('urllib3<1.23,>=1.21.1'), {'awsebcli'}) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/bin/eb", line 5, in <module> from pkg_resources import load_entry_point File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2927, in <module> @_call_aside File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2913, in _call_aside f(*args, **kwargs) File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2940, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 637, in _build_master return cls._build_from_requirements(__requires__) File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 650, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 834, in resolve raise VersionConflict(dist, req).with_context(dependent_req) pkg_resources.ContextualVersionConflict: (requests 2.9.1 (/usr/lib/python3/dist-packages), Requirement.parse('requests!=2.18.0,>=2.14.2'), {'docker'}) i am trying with below command: eb init -p python-3.6 eb-django below is my project tree. Here i am trying to deploy django in aws-elasticbeanstalk but, it is showing above error. -
Django on a single server. Web and Dev environments with web/dev databases
In a couple of months, I'm receiving a single (physical) Ubuntu LTS server for the purpose of a corporate Intranet only web tools site. I've been trying to figure out a framework to go with. My preference at this point would be to go with Django. I've used RoR, CF and PHP heavily in the past. My Django concern right now is how to have both a separate '/web/' and '/dev/' environment, when I'm only getting a single server. Of course this would include also needing separate 'web' and 'dev' databases (either separated by db name or having two different db instances running on the single server). Option 1: I know I could only setup a 'web' (production) environment on Ubuntu and then use my corporate Windows laptop to develop Django tools. I've read this works fine except that a lot of 3rd party Django packages don't work on Windows. My other concern would be making code changes and then pushing to the Ubuntu server where I might introduce problems that didn't show up on the local Windows development environment. Option 2: Somehow setup a separate Django 'web' and 'dev' environment on the same server. I've seen a lot of … -
Django + Multiprocessing argument passing failure
I've got a function which spins off a separate Process and passes some arguments to it. When I call this function testing locally, everything is fine. When I call this function from a Django view, the variables passed don't make any sense. Specifically, when I am passing a string, what comes through on the other side, no matter what string I put in, is __path__. Simplified example: views.py: handler = Handler() @csrf_exempt def my_view_func(request) str1 = request.POST['str1'] # passed value is e.g. 'my string' return HttpResponse(handler.do_work(str1)) handler.py from multiprocessing import Process class Handler: def do_work(str1): # str1 is still 'my string' p = Process(target=self.do_work_help, args=(str1)) p.start() # str1's value is again in this context def do_work_help(str1): print str1 # value will be '__path__' From what I've read I should probably be using Celery for this, but I'd prefer not to refactor everything just yet, so if anyone has any idea what's going on here I'd greatly appreciate a short-term fix. -
Client side encryption Django
I just finished an app and, for safety reasons, I would like the content of some fields of the db to be readable only by the user. This involves client side encryption and I think that I found a decent pure js implementation. Typically, I would go for an AES 256 CBC using parts of the user's password hash (client side computation) as key an vi (stored as cookies) to feed the encrypt and decrypt functions. Here comes the thing. The decryption is pretty straightforward. Spontaneously, I would call the function directly in the templates using the objects passed in context as inputs for my function. It would look like: <div class=whatever_the_class> decrypt_function({{ patient.first_name }}, key, vi) decrypt_function({{ patient.last_name }}, key, vi) </div> However, I am not sure how to deal with encryption in forms. I think that I need to bypass somehow the way my forms work (in this example form_add) to take the output of my encrypt function as data but I really do not know how/where to do it. In the widget section of my form? In the template? Any thoughts? Any clean way to do it? (I am also interested in similar questions/posts/projects to get a … -
Pagination are not working with filtering Django
I had a Listview that worked perfectly with pagination it looked like: class BranchListView(ListView): model = Branch paginate_by = 10 Now I need to change it to Filterview and used django_filters, I'm trying to create pagination in a FilterView this way class BranchListView(FilterView): model = Branch paginate_by = 10 filter_class = BranchFilter template_name = 'erp_system/branch_list.html' filterset_fields = ['id', 'name'] And this how I use pagination part in the template {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="?page={{ page_obj.previous_page_number }}"><button class="btn-success">الصفحة السابقة</button> </a> {% endif %} <span class="page-current"> صفحة رقم {{ page_obj.number }} من {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}"><button class="btn-success">الصفحة التالية</button> </a> {% endif %} </span> </div> {% endif %} Now the filtering is working perfectly. But there is no pagination at all. -
how to delete django relation and rebuild model
ive made a mistake with my django and messed up my model I want to delete it & then recreate it - how do I do that? I get this when I try to migrate - i just want to drop it relation "netshock_todo" already exists Thanks in advance -
Get json data from url and insert data into the model with verification
I am using python package requests for getting json data from remote url. Json data should be entered to my model with verification. If object id exists update data in the model else create. I can not make a check. How can i put a check? This is for getting data from remote url. Data in the remote url will be updated every hour so I have to write a function that needs to take data from the server and insert my model. Also function must to check. I've tried fooloop json data from server and insert it to my model, but I think this is not the best way. import requests from requests.auth import HTTPBasicAuth from main.models import Acceptor def sync_data(): response = requests.get('https://94.158.53.183:9443/apipp/acceptors', auth=HTTPBasicAuth('user', 'password'), verify=False).json()['acceptor_list'] for r in response: Acceptor.objects.update_or_create( login=r.login, password=r.password, sync_tm=r.sync_tm ) sync_data() class Acceptor(DeleteModel, BaseModel): login = models.CharField(max_length=255) password = models.CharField(max_length=255) sync_tm = models.IntegerField() I expected the data to appear in my database, in the Acceptors table, but there is no data from the server in the database -
Django - Disabled field in CreateView empty after ValidationError
My model Sprint has two DateFields "start" and "end". I defined a clean-method "start < end". Now, I have disabled my ModelForm field 'project' with this solution. Link. And I provide an initial value for it. class Sprint(models.Model): project = ForeignKey start = DateField end = DateField def clean(self): if start > end: raise ValidationError() class SprintCreate(LoginRequiredMixin, CreateView): model = Sprint form_class = SprintCreateForm def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['pk'] = self.kwargs['pk'] kwargs['initial'] = {'project': Project.objects.get(id=self.kwargs['pk'])} return kwargs class SprintCreateForm(forms.ModelForm): class Meta: model = Sprint fields = ['project', 'start', 'end'] def __init__(self, *args, **kwargs): pk = kwargs.pop('pk') project = Project.objects.filter(id=pk) super().__init__(*args, **kwargs) self.fields['project'].queryset = project self.fields['project'].widget.attrs['disabled'] = True def clean_project(self): instance = getattr(self, 'instance', None) if instance and instance.pk: return instance.project else: return self.cleaned_data['project'] I expect that field 'project' is still filled with the correct instance upon reload and validationerror. -
Django structure base on different type of projects
I couldn't find the best answer for this question that what is the Django solution about different kind of project, for example, what is the difference between Django solution for enterprise [rojects vs medium scale projects -
Pandas to_sql in django
I am trying to use Django's db connection variable to insert a pandas dataframe to Postgres database. The code I use is df.to_sql('forecast',connection,if_exists='append',index=False) And I get the following error Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': relation "sqlite_master" does not exist LINE 1: SELECT name FROM sqlite_master WHERE type='table' AND name=?... I think this happens because the Django connection object is not an sqlalchemy object and therefor Pandas assumes I am using sqlite. Is there any way to use .to_sql other than make another connection to the database? -
Using HTML, how to print objects from inside Postgresql?
In the application I started using Django and postgresql, whenever I upload a file, it'll be recorded into database. I've confirmed this is working by checking the database using pyadmin. However, now I need to print out the file onto a html document. The code I have below belongs to a SQLite database. Most of the names remained the same except for the obj part which I assumed is not supposed to be there for postgresql. Mainly, I'm looking the the Postgresql equivalent of the 'obj' in the code below. {% extends 'base.html' %} {% block content %} <p>Uploaded files:</p> <ul> {% for obj in documents %} <li> <a href="{{ obj.document.url }}">{{ obj.document.name }}</a> <small>(Uploaded at: {{ obj.uploaded_at }})</small> </li> {% endfor %} </ul> {% endblock %} The image URL shows the way my database is setup. https://i.stack.imgur.com/ao8TV.png If it's possible, I would prefer not to involve using PHP as I'm still fairly new to this. -
I get an integrity error when deleting a user in django admin
So I am creating a social medial app with Django and I have made a lot of model connections with users and profiles and now I am confused. When Ii try to delete a user, I get an error. IntegrityError at /admin/auth/user/ FOREIGN KEY constraint failed I am not so sure but I think the error has to do with something about the followingin the `model below. I tried creating a new user that is not following anyone and tried deleting it too, it worked! But the ones already follwing each other won't get deleted and raise the error above class Profile(models.Model): # creating a one to oe rel with a user model user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='default.jpg', upload_to='profile_pics') dob = models.DateField(blank=True, null=True) bio = models.TextField(max_length=400, blank=True) following = models.ManyToManyField('self', related_name='follows', symmetrical=False) joined_at = models.DateField(auto_now_add=True) Here is my post model class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, blank=True, related_name='post_likes') image = models.ImageField(null=False, blank=False, upload_to='post_images') -
Django admin select box options from model
I have language category, tags and questions models. When adding question I want to select category and multiple tags in multiselect dropdown/checkbox from the admin panel Here is my question model: from django.db import models from datetime import datetime from languages.models import Language from categories.models import Category from tags.models import Tag class Question(models.Model): language = models.ForeignKey(Language, on_delete=models.DO_NOTHING) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) tags = models.CharField(max_length=200, blank=True) def __str__(self): return self.title How can I achieve this in Django admin panel?