Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why does the UserChangeForm model does create an object instead of update it in this case? [django]
I'm using UserChangeForm to update user Form now when I try to send by the request post the function does works but doesn't change the user object but instead, it saves the object like create method does. so, at this moment how can, I change the form object? views.py # Edit Your account @login_required def edit_profile(request, user_slug=None): template_name = 'account/edit_profile.html' if request.method == "POST": request_user = request.user.userprofile user_profile = UserProfile.objects.get(slug=user_slug) form = EditForm(request.POST) if form.is_valid(): form.instance.slug = user_slug form.save() return redirect('account:view_profile', form.instance.slug) return render(request, template_name, {'form': form}) else: form = EditForm() user_profile = UserProfile.objects.get(slug=user_slug) return render(request, template_name, {'form': form}) urls.py urlpatterns = [ path('view-profile/<slug:user_slug>/', views.view_profile, name='view_profile'), # /account/edit-profile/ path('edit-profile/<slug:user_slug>/', views.edit_profile, name='edit_profile'), ] edit_form.html {% extends 'base.html' %} {% block title %} Edit Profile {% endblock %} {% block body %} <div class="edit-form"> <div class="container"> <div class="my-form"> <form method="post"> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="exampleInputEmail1">{{ field.label_tag }}</label> <p>{{ field }}</p> </div> {% endfor %} <button type="submit" class="btn btn-primary btn-lg">Change Password</button> </form> </div> </div> </div> {% include 'base_footer.html' %} {% endblock %} forms.py # Edit your data except password class EditForm(UserChangeForm): password = None class Meta: model = User fields = ('first_name', 'last_name', 'email') def … -
How to model persons, their addresses and possibly undelivered messages?
I have a database of persons with e-mail addresses like this: from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class E-Mail-Address(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) address = models.CharField(max_length=256) Now when I send them an e-mail I create an object to record it based on this model: class Sent-E-Mail(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) subject = models.CharField(max_length=120) body = models.TextField() message_id = models.CharField(max_length=10, unique=True) address_used = models.CharField(max_length=256) Note the message_id field. It is a unique identifier for every message, that is used for VERP. So if the e-mail bounces I get that message_id back and can handle it, but this could take several days. In the meantime the Person might update their e-mail-address. How could I change these models to ensure all of the following properties? I know which message had which message_id, so I can identify and resend the bounced message via other means. It is possible to handle situations in which the person updated their e-mail-address between sending the message and receiving the bounce, without marking the new address as invalid. I can tell apart the newly added address and the one actually used to send the last message. I think I have 1. and 3. … -
Django: polls tutorial ImportError
I am learning django using the app tutorial from their page. I ran into a problem with importing views. from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] I think you should know that I'm doing this tutorial on Windows using PyCharm. I am importing the module from the same directory. The error: Traceback (most recent call last): File "C:/Users/sarah/Desktop/django2/myproject/my_site/polls/urls.py", line 2, in <module> from . import views ImportError: attempted relative import with no known parent package Thanks. -
Why does my ModelForm validation returns False instead of True using Django-simple-captcha
I am trying to implement Django-simple-captcha to somehow prevent my blog from receiving spam comments. Thus, I defined a form and want to implement some validation on the backend to check for human or not... Somehow If I fill out my form and solve the Captcha and try to commit the comment, it always returns false. I guess the bug is in my view. Looking forward to be pointed into the right direction. Thank you. forms.py # Blog Post Comment Form class CommentForm(forms.ModelForm): captcha = CaptchaField() class Meta: model = Comment fields = ('name', 'text', 'captcha') views.py @require_http_methods(['POST']) def post_comment(request): form = CommentForm(request.POST) if form.is_valid(): print('True') gif = request.POST['gif_src'] name = request.POST['name'] text = request.POST['text'] post_id = request.POST['post_id'] # Create new DB entry comment = Comment.objects.create( post_id=post_id, name=name, text=text, gif=gif ) # Query all comments including the new one post = get_object_or_404(Post, id=post_id) return render(request, 'post.html', {'post': post}) else: form = CommentForm() print('False') return render(request, 'post.html', {'form': form}) html <div id="comment-form-ctn"> <h1>Add comment</h1> <form method="POST" class="post-form" id="comment-form-ctn">{% csrf_token %} <div id="form-name-ctn"> <div>Name/Nickname</div> <div id="form-name">{{ form.name }}</div> </div> <div id="form-text">{{ form.text }}</div> <div id="form-captcha">{{ form.captcha }}</div> <div id="buttons-ctn"> <button type="submit" class="comment-button">Comment!</button> </div> </form> </div> -
How to filter post objects in django according to a particular user model field?
I'm currently creating a Social platform with Django. Right now, I'm developing homepage and want to show posts matching a userfield. This is my Post model: class Discussion(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Account, on_delete=models.CASCADE) post = models.TextField() date = models.DateTimeField(default=timezone.now) This is user account model: class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) classid = models.CharField(max_length=10) This is view: @login_required(login_url='login') def home(request): if request.method == 'GET': discussions = Discussion.objects.get(post=Account.classid).order_by('-date') form = PostDiscussionForm() return render(request, 'app/home.html', {'discussions':discussions,'form':form}) else: form = PostDiscussionForm(request.POST) newdisscussion = form.save(commit=False) newdisscussion.author = request.user newdisscussion.save() return redirect('home') I want to show only logged users matching their classid (from user account model) -
CSRF verification failed, 'CSRF token missing or incorrect'
This has been asked many times before and I have read all of those answers, but none of them worked for me so I'd like to try again. When I try to submit a Django form with username and password, I get this error message: 'CSRF token missing or incorrect'. The CSRF token is not missing. Here is where I included it in my form in my .html template: In index.html: <form name="loginform" action="/notes/index/" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit"/> {% for field, errors in form.errors.items %} {{ errors }} {% endfor %} </form> In views.py: class LoginForm(forms.Form): username = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput()) def index(request): if request.method == 'POST': print("Received POST") form = LoginForm(request.POST) if form.is_valid(): print("FORM is Valid") else: print("FORM is NOT VALID") template = loader.get_template('index.html') context = { 'username': 'Benny', 'form': LoginForm(), } return HttpResponse(template.render(context)) I tried adding @ensure_csrf_protect and @csrf_protect, but none of these worked. I also have csrf middleware in settings. I am trying to avoid using @csrf_exempt as this app will go into production down the line. -
Django attaching to COM Application (SAP GUI Scripting)
I have a python script that attaches to the SAP GUI instance by using the pywin32 library. Is it possible to have that pywin32 library running through Django on a remote server but attaching to an application on the client side? Here is an example of my test script that works fine on the client side: #----------------------------------------------------------------------- # Transaction = SESSION_MANAGER # Title = SAP Easy Access # Dynpro = SAPLSMTR_NAVIGATION.100 # Session = 1 #----------------------------------------------------------------------- #-Begin----------------------------------------------------------------- #-Includes-------------------------------------------------------------- import sys, win32com.client #-Sub Main-------------------------------------------------------------- def Main(): try: SapGuiAuto = win32com.client.GetObject("SAPGUI") if not type(SapGuiAuto) == win32com.client.CDispatch: return application = SapGuiAuto.GetScriptingEngine if not type(application) == win32com.client.CDispatch: SapGuiAuto = None return connection = application.Children(0) if not type(connection) == win32com.client.CDispatch: application = None SapGuiAuto = None return if connection.DisabledByServer == True: application = None SapGuiAuto = None return session = connection.Children(0) if not type(session) == win32com.client.CDispatch: connection = None application = None SapGuiAuto = None return if session.Info.IsLowSpeedConnection == True: connection = None application = None SapGuiAuto = None return #>Insert your SAP GUI Scripting code here< session.findById("wnd[0]").maximize() session.findById("wnd[0]/tbar[0]/okcd").text = "mb51" session.findById("wnd[0]").sendVKey(0) except: print(sys.exc_info()[0]) finally: session = None connection = None application = None SapGuiAuto = None #-Main------------------------------------------------------------------ Main() #-End------------------------------------------------------------------- -
ansible --version not working throwing following Exception
Traceback (most recent call last): File "/usr/bin/ansible", line 60, in import ansible.constants as C File "/usr/lib/python3.7/site-packages/ansible/constants.py", line 12, in from jinja2 import Template File "/usr/lib/python3.7/site-packages/jinja2/init.py", line 33, in from jinja2.environment import Environment, Template File "/usr/lib/python3.7/site-packages/jinja2/environment.py", line 15, in from jinja2 import nodes File "/usr/lib/python3.7/site-packages/jinja2/nodes.py", line 19, in from jinja2.utils import Markup File "/usr/lib/python3.7/site-packages/jinja2/utils.py", line 647, in from markupsafe import Markup, escape, soft_unicode ModuleNotFoundError: No module named 'markupsafe' -
how to display foreign key value to template django
hello guys so i have a bit of problem here, i want to display my foreign key value to my form but it seems its not doing showing anything at all so i tried to print it from the backend like this: task = task_admin_form.objects.all() for tasks in task.values(): print(tasks.username.username) but its not working can anyone help me with this? thanks my model class task_admin_form(models.Model): username = models.ForeignKey(Account, on_delete=models.CASCADE) subject = models.CharField(max_length=100) task_tenggat = models.DateField(auto_now=False, auto_now_add=False) task = models.TextField(max_length=200) def __str__(self): return self.username views.py task = task_admin_form.objects.all() return render(request,"form.html",{"task":task}) form.html(the username is a field in my other model) <div class="block"> <label>TO: </label> <select name="username"> {% for form in form_task %} <option value={{form.username.username}} >{{form.username.username}}</option> {% endfor %} </select> </div> -
Django HttpResponse in JsonResponse
In my django project in order to avoid another request I would like to return a JsonResponse with a HttpResponse in there like this: JsonResponse({"known": True, "space": render(request, 'space.html')}, status=200) Django process returns the normal internal error Object of type HttpResponse is not JSON serializable I tried all the web solutions (serializer, etc.) and can not find a way to return a json format (necessary for my javascript) with dictionary entries with one of them being an entire html page that I can use with then with $("body").html(response["space"]). Am I missing something? Thanks for your time. -
How to use multiple Django FBVs in capturing and saving data through Ajax+jQuery
In my Django app, I am using two function views, FV1 and FV2. FV1 is being used to capture data from the database and populate form/formsets. In FV2, I am trying to send serialized data from the page (with the aforesaid data) using Ajax, validate the data in FV2 and save it and finally, receive a confirmation from FV2 as Ajax callback in the page. In the console I can see the serialized data. That validation happens is proven by the fact that if one of the required values is not keyed in, error message captured in the relevant else: segment is passed to the console. However, if all the data is correctly entered and form is submitted, data is not being saved in the respective models. There is no error message either. Given the above scenario, what should be the approach in achieving the goal. It goes without saying that I am missing something big. A guidance to solving the problem will be much appreciated. -
Import error 'six' while initializing haystack in django settings.py INSTALLED APPS
I was trying to add haystack to the list of installed apps in django, but during initialization I got an import error saying: from haystack.utils import loading from django.utils import six ImportError: cannot import name 'six' from 'django.utils' (C:\Users\Sanjeev K M\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils_init_.py) Please help me solve this problem. Thanks in advance. -
Bad Request (400) even when I have configured the CNAME
I have a basic hacker plan with pythonanywhere and have my domain registered in Namecheap. I am trying to link my domain name with my django app and I get Bad Request (400) upon configuring the CNAME record which is the setup pythonanywhere suggests. Am I missing somthing? The following are the steps I have done: In my "web" tab I have edited the app name as www.gmsolutions.in Have added a CNAME record in NameCheap control panel under my registered domain. Type: CNAME-Record Host: www Value: webapp-xxxxx.pythonanywhere.com (where xxxxx is my app number given by pa) TTL: automatic I am not sure that whether I can make the app number visible or not, that's why shaded it. I had only the CNAME record setup. Is there anything else I should do it? I found no DNS setup errors in my "web" as well. Note: In my allowed hosts, I have added gmsolutions.in. Any hints would be helpful. -
Search by end nested relation django rest framework
I recently picked up an existing project in nodejs, this one is full of all kinds of problems. I decided to reconvert it for more ease with django rest framework, I try to keep the same json structure so as not to interfere with react. For the most part I don't have any problems except for some search with sequelize it searches by the last model to make the inverse relations example : Occurence.findAll({ include: [ { model: TimeSlot, as: 'TimeSlot', include: [ { model: Agenda, as: 'Agenda' } ] }, { model: Monitor, as: 'Monitor', include: [ { model: User, attributes: { exclude: ['password'] } } ], where: { id: req.params.id } } ] }) with django rest framework I didn't find an "efficient" solution to start my search from the end to the beginning and/or replace the structure with to_representation() to display the relations between them. For the total representation I was able to do this but for the search from the last one like the code given with "sequelize" (nodejs code) I don't really see how to do it. class TimeslotsGetOptimizeSerializer(TimeslotsGetSerializer): agenda = serializers.SerializerMethodField(read_only=True) timeslots_occurences = serializers.SerializerMethodField(read_only=True) def get_agenda(self, obj): if obj: agenda = Agendas.objects.filter(timeslotagendas__timeslot_id=obj.id) if agenda: … -
Pipenv virtual environment pulling me into different directories
I have installed pipenv on my machine to run virtual environments. My problem is that when i run pipenv, it keeps pulling me back to a different folder. For example, I build a project in my pycharmprojects folder. I navigate to that project from my terminal. cd pycharmprojects then cd myproject. Then when I run a virtual enrolment in that folder pipenv shell, I get pulled back to /Users/myname/PycharmProjects. This is where my pipfile, piffle.lock and Procfile seem to live as well. I am getting a error when trying to deploy to heroku and I am wondering if it is something to do with this issue based on my virtual environment. The error im getting with deploying to heroku is: ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/my-heroku-app-123.git' -
Create public profiles for users in django
I created a profile view for users and I want everyone to be able to see it without having to log in But when I click on the profile while not having logged in, it automatically logs into the account of the user I clicked on! How can I fix it? This is the view def public_profile(request, username): user = User.objects.get(username=username) return render(request, 'users/public_profile.html', {"user": user}) This is the url path('<str:username>/profile/', public_profile, name='public-profile'), -
How to get image from Django Summernote in react
I am making a blog web app using django and react. I added django-summernote for the blog content. The image is being uploaded to my media directory. But when I checked my api, the image tag in has src like this: src=\"/media/django-summernote/2020-06-22/626173a6-4711-40b6-867a-d46f5d484534.jpg\" But I would like to have it as: src="localhost:8000/media/django-summernote/2020-06-22/626173a6-4711-40b6-867a-d46f5d484534.jpg" Because the image is not rendered in my react app. Please suggest changes in my django part or react part to make use of it -
Is it a good idea to use a virtual box VM Linux server to test hobby web projects on different platforms
I am currently learning django and was also Learning Linux using the Oracle's Virtual Box , I wanted to ask is it a good idea to use a VM as Linux server to test my hobby projects on different platforms (laptops, mobiles). -
How to make two gunicorn configs work simultaniously? (Nginx - Gunicorn - Django)
This question might look duplicating, but I can't sort my issue out using the previous answers, sorry. I have a site that is based on Nginx - Gunicorn - Django. Its nginx config is server { listen 80; server_name example.com; ... location / { include proxy_params; proxy_pass http://unix:/home/ks/example-venv/example/example.sock; } } Gunicorn config at /etc/init/gunicorn.conf: description "Gunicorn application server handling example" start on runlevel [2345] stop on runlevel [!2345] respawn setuid ks setgid www-data chdir /home/ks/example-venv/example exec /home/ks/example-venv/bin/gunicorn --workers 3 --bind unix:/home/ks/example-venv/example/example.sock example.wsgi:application Everything works fine. Now, I created the second site at test.example.com (the project is in the separate virtual env). It has its own nginx config in sites-enabled: server { listen 80; server_name test.example.com; ... location / { include proxy_params; proxy_pass http://unix:/home/ks/example-test-venv/example_test/example_test.sock; } } And its Gunicorn config is description "Gunicorn application server handling example_test" start on runlevel [2345] stop on runlevel [!2345] respawn setuid ks setgid www-data chdir /home/ks/example-test-venv/example_test exec /home/ks/example-test-venv/bin/gunicorn --workers 3 --bind unix:/home/ks/example-test-venv/example_test/example_test.sock example_test.wsgi:application test.example.com works if in /etc/init/gunicorn.conf there are isntructions only for example_test. If there are instructions for both example and example_test, I get the error 502 Bad Gateway at test.example.com (while example.com is OK). What could I do to make both Gunicorn configs … -
Django problem overriding all auth Signup forms
Thanks in advance, i'm learning Django and can't figure how to override all auth forms. Quick explanation first, I have a custom user model class PersoUser(AbstractBaseUser): email = models.EmailField( verbose_name="Email Adress", max_length=200, unique=True) username = models.CharField( verbose_name="username", max_length=200, unique=True) first_name = models.CharField(verbose_name="firstname", max_length=200) last_name = models.CharField(verbose_name="lastname", max_length=200) date_of_birth = models.DateField(verbose_name="birthday") is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = PersoUserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["date_of_birth", "username"] .... and I would want to add date_of_birth field to my signup page , so I followed the official doc to override the specif form used by the all auth SignupView https://django-allauth.readthedocs.io/en/latest/forms.html#signup-allauth-account-forms-signupform which leads to ( in Book_store/forms.py ) from allauth.account.forms import SignupForm from users.models import PersoUser class PersoUserRegisterForm(SignupForm): class Meta: model = PersoUser fields = ["username", "email", "first_name", "last_name", "date_of_birth", "password1", "password2"] def save(self, request): # Ensure you call the parent class's save. # .save() returns a User object. user = super(PersoUserRegisterForm, self).save(request) # Add your own processing here. # You must return the original result. return user in my settings/base.py ACCOUNT_FORMS = {'signup': 'Book_store.forms.PersoUserRegisterForm'} My account/signup.html template just refers to {{form.as_p}} and it doesn't display the extra fields specified in PersouserRegisterForm just the default ones I don't really see what I'm missing,Thanks … -
How to host.deploy my django project to firebase
I made this little django project, it shows weather of next three days of given city, its just a single page project, it looks like this i want to deploy/host it on firebase my project link here But i have no idea how to do it, please help. -
Returning a DateTimeField results in OperationError
from django.db import models # Create your models here. class TheDate(models.Model): """A topic the user is learning about""" theDate = models.DateTimeField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """returns a string representation of the model""" return self.theDate Even trying to access the values store or trying to save a new field results in the following traceback: OperationalError at /admin/meal_plans/thedate/ no such table: meal_plans_thedate Request Method: GET Request URL: http://localhost:8000/admin/meal_plans/thedate/ Django Version: 2.2 Exception Type: OperationalError Exception Value: no such table: meal_plans_thedate Exception Location: C:\Users$$$\Desktop\meal_planner\ll_env\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383 Python Executable: C:\Users$$$\Desktop\meal_planner\ll_env\Scripts\python.exe Python Version: 3.8.3 Python Path: ['C:\Users\$$$\Desktop\meal_planner', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1008.0_x64__qbz5n2kfra8p0\python38.zip', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1008.0_x64__qbz5n2kfra8p0\DLLs', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1008.0_x64__qbz5n2kfra8p0\lib', 'C:\Users\$$$\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0', 'C:\Users\$$$\Desktop\meal_planner\ll_env', 'C:\Users\$$$\Desktop\meal_planner\ll_env\lib\site-packages'] Server time: Sun, 28 Jun 2020 13:18:06 +0000 -
Creating comment system in django using class based views
I am trying to create a comment system using class based views but it shows error like comment box is not showing and previous comment is not showing. If anyone can provide articles or examples related to it it will be big help to me. -
Online league player, team, roster, league models
I'm creating league system for online games. My biggest problem is with modeling roster. Every player can be in multiple teams simultaneously. For now i have something like this class Player(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) age = models.IntegerField() rank = models.CharField(max_length=20, choices=RANK_CHOICES); class Team(models.Model): name = models.CharField(max_length=200, null=True) creator = models.ForeignKey(Player, on_delete=models.CASCADE, related_name="creator") team_creation_date = models.DateTimeField(auto_now_add=True, null=True) players = models.ManyToManyField(Player, through="PlayerTeam", related_name="players") class TeamPlayer(models.Model): player = models.ForeignKey(Player,on_delete=models.CASCADE) team = models.ForeignKey(Team,on_delete=models.CASCADE) class League(models.Model): name = models.CharField(max_length=200, null=True) creator = models.ForeignKey(Player, on_delete=models.CASCADE, related_name="league_creator") number_of_teams = models.IntegerField() #number of teams for league to start league_start = models.DateField(null=True) league_end = models.DateField(null=True) class LeagueRoster(models.Model): league = models.ForeignKey(League, on_delete=models.CASCADE, related_name="league") players = models.ManyToManyField(TeamPlayer, related_name="roster_players") When captain/creator of the team is signing team for the league he should choose 5 players from team to create a LeagueRoster. I was thinking about creating roster field in Team model to hold current roster and change it in team panel instead of choosing players before each league. But both those ideas seem like workarounds for me. -
DJANGO - Models.Forms - Usuarios
I'm trying to save and retrive the data owned by the user. I mean, in one Sqlite3 DB I store the tables for all users but each one has their one data store in it, how can I give each one their own data. this are my models, view and form MODEL.PY class Cuentas (models.Model): rubro_cta = models.ForeignKey(TipoC, on_delete=models.CASCADE, verbose_name = u'Tipo') sub_rubro_cta = models.ForeignKey(Sub_rubro, on_delete=models.CASCADE, verbose_name = u'Sub Rubro') titulo_cuenta = models.CharField(max_length=50) detalle_cuenta = models.CharField(max_length=60) importe_cuenta = models.FloatField() def save(self, *args, **kwargs): self.importe_cuenta = round(self.importe_cuenta, 2) super(Cuentas, self).save(*args, **kwargs) def __str__(self): return self.detalle_cuenta FORMS.PY class CuentasForm (forms.ModelForm): class Meta: model = Cuentas fields = ['rubro_cta', 'sub_rubro_cta', 'detalle_cuenta', 'importe_cuenta'] labels = { 'rubro_cta': _('Cuenta'), 'sub_rubro_cta': _('Tipo'), 'detalle_cuenta': _('Detalle'), 'importe_cuenta': _('Importe'), } VIEWS.PY @login_required def carga (request): if request.method == 'POST': form = CuentasForm(request.POST) if form.is_valid: form.save() return redirect('balance') else: form = CuentasForm() return render (request, "ProyetoWebApp/carga.html",{"form": form})