Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm getting ModuleNotFoundError: No module named '<anyproject>'
To generate some fake data i used "djnago_populator" as fakers.py and when I run code getting something related to "DJANGO_SETTINGS_MODULE". I searched in stackoverflow regarding this and saw there to use "set DJANGO_SETTINGS_MODULE=admin.settings" and didnt generated fakedata but i ran "set DJANGO_SETTINGS_MODULE=ecom.settings" where ecom is my project name. and so this generated fake data. and now i'm able to runserver command and able to visit localhost. but when I go admin site below error is getting Error at /admin/ Incorrect padding Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 2.1.7 Exception Type: Error Exception Value: Incorrect padding Exception Location: G:\Install\Python 3.8\lib\base64.py in b64decode, line 87 Python Executable: G:\Install\Python 3.8\python.exe Python Version: 3.8.2 Python Path: ['E:\\Workspace\\Atom_Wrksc\\django\\ecom', 'E:\\Workspace\\Atom_Wrksc\\django\\ecom', 'C:\\Program Files\\JetBrains\\PyCharm ' '2020.3.2\\plugins\\python\\helpers\\pycharm_display', 'G:\\Install\\Python 3.8\\python38.zip', 'G:\\Install\\Python 3.8\\DLLs', 'G:\\Install\\Python 3.8\\lib', 'G:\\Install\\Python 3.8', 'G:\\Install\\Python 3.8\\lib\\site-packages', 'G:\\Install\\Python 3.8\\lib\\site-packages\\django_misaka-0.2.1-py3.8.egg', 'G:\\Install\\Python 3.8\\lib\\site-packages\\pygments-2.7.3-py3.8.egg', 'G:\\Install\\Python ' '3.8\\lib\\site-packages\\houdini.py-0.1.0-py3.8-win32.egg', 'C:\\Program Files\\JetBrains\\PyCharm ' '2020.3.2\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Tue, 19 Jan 2021 10:53:17 +0000 Traceback Switch to copy-and-paste view G:\Install\Python 3.8\lib\site-packages\django\contrib\sessions\backends\base.py in _get_session return self._session_cache ... ▶ Local vars During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: G:\Install\Python 3.8\lib\site-packages\django\core\handlers\exception.py in inner i uninstalled django and installed again and tested. but samee error i'm getting. I also started a … -
how to add field to userchangeform?
I have extended the abstract user class but the fields I added is phone number but this field did not appear in user change form how would I add this field to user change form ? -
Django: Modify database object on click using a ListView
I have a ListView that I use to display a list of products. On the right of every product/row, I want a "archive" button that, when clicked-on, will change the "archived" field of the product in the database from True to False. I'd like to do this using only Django and I think this is possible but I have a hard time finding out how. I'm trying to do it using a form, but I don't know how I can send the pk of the current object (in the loop) back to the view to make the change. Here's my template (the relevant part): {% for product in product_list %} <tr> <th scope="row">{{ product.pk }}</th> <td> <a href="{% url 'accounts:products_edit' pk=product.pk %}"> {{ product.title }}</a > </td> <td class="d-flex justify-content-between"> <form action="" method="POST"> {% csrf_token %} <button type="submit"><i class="fas fa-trash" style="color: grey"></i></button> </form> </td> </tr> {% endfor %} Here's my view: class ProductsListView(ListView, LoginRequiredMixin): template_name = "accounts/products/products_list.html" model = Product def get_context_data(self, **kwargs): # ... return context def post(self, request, *args, **kwargs): # modify object from pk here return HttpResponseRedirect(self.request.path_info) I've seen several post with similar situations, but didn't find a solution that works completely for my case. Any help … -
Enumeration types in Django
I am trying to use enumeration types in Django but fell like I am not doing the right thing... I am building an ebay-like webapp where my Listings are saved in the database with a .category attribute. class Listing(models.Model): class Category(models.TextChoices): TOY = "TO", _("Toys") FASHION = "FA", _("Fashion") ELECTRONICS = "EL", _("Electronics") HOME = "HO", _("Home") OTHERS = "OT", _("Others") title = models.CharField(max_length=64) category = models.CharField( max_length=2, choices=Category.choices, default=Category.OTHERS, ) I referred to Django's documentation for the use of Enumeration types but there are some grey areas, as far as my understanding goes. When I render a template to display a Listing, how do I pass the string value associated with the .category of my Listing? I tried something like this: return render(request, "auctions/listing.html", { "listing": listing, "category": Listing.Category[listing.category].label, }) Or can I access it through the "listing" variable? What I would like is for the browser to display Home for a listing with listing.category = "HO". -
Django test database objects
I created custom database migration for creating new user in database like below: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("core", "0179_merge_20210104_1353"), ] db_user_name = 'database_new_user' db_password = 'database_new_user_password' create_db_user = f""" DO $$ BEGIN CREATE ROLE {db_user_name} WITH NOSUPERUSER NOCREATEDB NOCREATEROLE LOGIN PASSWORD '{db_password}'; EXCEPTION WHEN DUPLICATE_OBJECT THEN RAISE NOTICE 'not creating {db_user_name} -- it already exists'; END $$ """ delete_db_user = f""" DROP ROLE IF EXISTS {db_user_name}; """ grant_read_permissions = f""" DO $$ BEGIN GRANT USAGE ON SCHEMA public TO {db_user_name}; GRANT SELECT ON ALL TABLES IN SCHEMA public TO {db_user_name}; END $$ """ revoke_read_permissions = f""" REVOKE USAGE ON SCHEMA public FROM {db_user_name}; REVOKE SELECT on ALL TABLES IN SCHEMA PUBLIC FROM {db_user_name}; """ operations = [ migrations.RunSQL(create_db_user, delete_db_user), migrations.RunSQL(grant_read_permissions, revoke_read_permissions), ] This migration essentially creates new user in database and grant SELECT for all tables. Reverse options revoke permissions and drop user accordingly. Migration is deployed and working as expected. Problem is that when I try to revert (in local machine) this migration by typing: python manage.py migrate core 0179_merge_20210104_1353 Django says: django.db.utils.InternalError: role "database_new_user" cannot be dropped because some objects depend on it I inspected database and saw that django created test_database (when … -
NoReverseMatch error while adding slug in url path
i'm building a blog app in django. In the blog list page after preview of each button i've added Read More link to read the blog in details. I'm trying to add slug in the blog detail page but it gives the NoReverse error. I get this error: This is my urls.py of blog_app and i've included in main project url.py: app_name = 'blog_app' urlpatterns = [ path('', views.BlogList.as_view(), name='blog_list'), path('write/', views.CreateBlog.as_view(), name='create_blog'), path('details/<slug:slug>/', views.blog_details, name='blog_details'), ] This is the views.py: def blog_list(request): return render(request, 'blog_app/blog_list.html', context={}) class BlogList(ListView): context_object_name = 'blogs' model = Blog template_name ='blog_app/blog_list.html' class CreateBlog(LoginRequiredMixin, CreateView): model = Blog template_name = 'blog_app/create_blog.html' fields = ('blog_title', 'blog_content', 'blog_image') def form_valid(self, form): blog_object = form.save(commit=False) blog_object.author = self.request.user title = blog_object.blog_title blog_object.slug = title.replace(' ', '-') + '-' + str(uuid.uuid4()) blog_object.save() return HttpResponseRedirect(reverse('index')) def blog_details(request, slug): blog = Blog.objects.get(slug=slug) return render(request, 'blog_app/blog_details.html', context={'blog':blog}) This is models.py: class Blog(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author') blog_title = models.CharField(max_length=264, verbose_name='Assign a Title') slug = models.SlugField(max_length=264, unique=True) blog_content = models.TextField(verbose_name="What's on your Mind") blog_image =models.ImageField(upload_to='blog_images', verbose_name="Blog Image") published_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-published_date'] def __str__(self): return self.blog_title This is blog_details.html: {% extends 'base.html' %} {% block title … -
Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4 error in python django
You see I am getting this incredibly weird error related to the no of characters in a string I guess. I am a bit new to django and I have never see such an weird error. I checked a few threads and according to that this is about encoding and decoding something which I really do not know how to resolve. Here is my code: Request Method: GET Request URL: http://127.0.0.1:8000/profiles/myprofile/ Django Version: 2.1.5 Python Version: 3.9.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts', 'profiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\sessions\backends\base.py" in _get_session 190. return self._session_cache During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\PROJECTS\social\src\profiles\views.py" in my_profile_view 6. profile = Profile.objects.get(user=request.user) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py" in get 390. clone = self.filter(*args, **kwargs) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py" in filter 844. return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py" in _filter_or_exclude 862. clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py" in add_q 1263. clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py" … -
Django register user
Hi i want to connect normal user using UserCreationForm and my own Creation when i post it with button my postgre auth_user and auth_users_register nthing add to database when i click on button my code: forms.py class RegisterForm(ModelForm): class Meta: model = Register fields = ['date_of_birth', 'image_add'] widgets = { 'date_of_birth': DateInput(attrs={'type': 'date'}) } class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] models.py def validate_image(image_add): max_height = 250 max_width = 250 if 250 < max_width or 250 < max_height: raise ValidationError("Height or Width is larger than what is allowed") class Register(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE) date_of_birth = models.DateField( max_length=8, verbose_name="date of birth") image_add = models.ImageField( upload_to="avatars", verbose_name="avatar", validators=[validate_image]) views.py class RegisterPageView(View): def get(self, request): if request.user.is_authenticated: return redirect('/') user_form = CreateUserForm(request.POST) register_form = RegisterForm(request.POST) return render(request, 'register.html', {'user_form': user_form, 'register_form': register_form}) def post(self, request): if request.method == 'POST': user_form = CreateUserForm(request.POST) register_form = RegisterForm(request.POST) if user_form.is_valid() and register_form.is_valid(): user_form.save() register_form.save(commit=False) user = user_form.cleaned_data.get('username') messages.success( request, 'Your account has been registered' + user) return redirect('login') user_form = CreateUserForm() register_form = RegisterForm() context = {'user_form': user_form, 'register_form': register_form} return render(request, 'register.html', context) -
Variation/Fluctuation in SID for the same user in Apache open meetings 5.0.2
I am facing the issue in fetching the SID of user as it keeps on varying whenever there is GET request passed to the appplication. { "serviceResult": { "message": "bfddf0de-fdcc-4804-b355-a8d33ed57a44", "type": "SUCCESS" } } Below link uses REST to get the SID and create room hash, but the SID keeps on varying for the same user whenever the GET request is passed link : https://openmeetings.apache.org/RestAPISample.html Can anyone suggest how this variation can be rectified and how to proceed further to work with other API urls. link : http://evc-cit.info/openmeetings/webapps/openmeetings/docs/RoomService.html -
How to install Cmake on Django Azure webapp?
I'm trying to deploy a Django Webapp on Azure. One of the libraries I need, depends on Cmake, so im getting the error : CMake must be installed to build the following extensions: _dlib_pybind11 Now, in order to install Cmake on the service, I need to make some SH file, or manually insert some "startup" commands, is there a way to "pre-install" Cmake before the install of requirements.txt? -
How do i filter certain items in a model field by id of another model?
This is kind of a weird question class Post(models.Model): name = models.CharField(max_length=200) class PostKey(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) name = models.CharField(max_length=200) def __str__(self): return self.post.name + " | " + self.name I am trying to use the detail view such that it displays the details of the Post model as well as shows a list of PostKey (couldn't think of any other name) which has the same id as post.id. I have created a one to many relation with the Post model using ForeignKey. Here is my view: from django.shortcuts import render from django.views.generic import TemplateView, DetailView from .models import Post, PostKey class TestView(TemplateView): template_name = "test.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["posts"] = Post.objects.all() return context class PostDetailView(DetailView, Post): template_name = "test2.html" model = Post def get_context_data(self, **kwargs ): context = super().get_context_data( **kwargs) context['details'] = PostKey.objects.filter(id= Post.id) return context but when I run this code it shows me something like this: TypeError at /post/2 Field 'id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at 0x03F88478>. I have tried to add int(Post.id) but it still doesn't work. Here are is the template that is getting rendered for the above view. {% for detail in details %} {{detail.name}} {% endfor … -
django celery asynchronous file saves to storage
So I want to asynchronously conduct file saves to django file storage. I've tried to achieve this by overwriting the default File System Storage class. import hashlib import os import uuid import django.core.files.storage as storage from celery import shared_task from django.core.files import File class DefaultStorage(storage.FileSystemStorage): def __init__(self): super(DefaultStorage, self).__init__() @shared_task def _save(self, name, content): # need to encrypt file before saving return super(DefaultStorage, self)._save(name, content) @shared_task def _open(self, name, mode='rb'): # need to decrypt before opening return File(open(self.path(name), mode)) def get_available_name(self, name, max_length=None): # we return a hash of the file given, # in case we miss out on uniqueness, django calls # the get_alternative_name method dir_name, file_name = os.path.split(name) file_root, file_ext = os.path.splitext(file_name) file_root = hashlib.md5(file_root.encode()).hexdigest() name = os.path.join(dir_name, file_root + file_ext) return super(DefaultStorage, self).get_available_name(name, max_length) def get_alternative_name(self, file_root, file_ext): # we insert a random uuid hex string into the given # file name before returning the same back return '%s%s%s' % (file_root, uuid.uuid4().hex, file_ext) def save(self, name, content, max_length=None): # override existing system storage save method # to ensure that we call the shared task and # utilize the distributed task queue celery offers has_chunks = hasattr(content, 'chunks') name = content.name if not name else name content = … -
How to overwrite Django app to Pythonanywhere? 3
After the second time deploying the Django app to Pythonanywhere, (I re-edited and overwritten in VS code and did git push) I got the following error. The command is pa_autoconfigure_django.py https://github.com/[user_name]/[project_name].git --nuke Is that something exceeded? What should I delete? I don't know what wrong it is... Downloading llvmlite-0.33.0-cp36-cp36m-manylinux1_x86_64.whl (18.3 MB) |███████████████████████████▍ | 15.7 MB 14.7 MB/s eta 0:00:01ERROR: Could not install packages due to an EnvironmentError: [Errno 122] Disk quota exceeded Traceback (most recent call last): File "/home/hogehoge/.local/bin/pa_autoconfigure_django.py", line 47, in <module> main(arguments['<git-repo-url>'], arguments['--domain'], arguments['--python'], nuke=arguments.get('--nuke')) File "/home/hogehoge/.local/bin/pa_autoconfigure_django.py", line 31, in main project.create_virtualenv(nuke=nuke) File "/home/hogehoge/.local/lib/python3.6/site-packages/pythonanywhere/django_project.py", line 29, in create_virtualenv self.virtualenv.pip_install(packages) File "/home/hogehoge/.local/lib/python3.6/site-packages/pythonanywhere/virtualenvs.py", line 28, in pip_install subprocess.check_call(commands) File "/usr/lib/python3.6/subprocess.py", line 311, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['/home/hogehoge/.virtualenvs/hogehoge.pythonanywhere.com/bin/pip', 'install', '-r', '/home/hogehoge.pythonanywhere.com/requirements.txt']' returned non-zero ex it status 1. -
Django Sent Mail work in localhost but not in host server Cpanel
I make a e-commerce Website. When i run it on my localhost, Django sent mail can sent mail properly. But after hosting it, sent mail does not happend. It can not sent email. Settings.py #Email Settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'email' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL= 'Team <Team@support>' Views.py: send_mail( 'Purchase Order', # subject 'email_for_buy', # massage '', # from email ['email'], # to email fail_silently=True, ) Can someone help me, how can i able to sent email by django sent email from my cpanel host -
AES - changing a string to byte resulting in extra "/" how to avoid it
import unittest import base64 from py3rijndael import Rijndael import os import codecs #plain text a=input("Please Enter Plain text: ") plain_text = a.encode('utf-8') padded_text = plain_text.ljust(32, b'\x1b') #key key=input() key_bytes = codecs.encode(key, 'UTF-8') #key_bytes = key.encode('utf-8') #two change string to byte #base64_key_bytes = base64.b64encode(key_bytes) #base 64 encryption key_bytes = key_bytes[2:-1] print(key_bytes) #encryption rijndael_key = Rijndael(key_bytes, block_size=32) cipher = rijndael_key.encrypt(padded_text) print(cipher) I m changing a string (generated using os.urandom() and passed the form ) to byte to use as a key for aes algorithm but its resulting in adding one extra "/" to the actual required values please help me with this -
MySQLdb._exceptions.ProgrammingError: %d format: a number is required, not bytes [closed]
3: Please press 3 to process one posting. Please select action: 3 You have selected: 3 Starting ... UniquePostingID: 800 from here the error ocurrs: mysqldb 800 Traceback (most recent call last): File "D:\Projects\FBMarketPlace\env\lib\site-packages\MySQLdb\cursors.py", line 201, in execute query = query % args TypeError: %d format: a number is required, not bytes During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:/Projects/FBMarketPlace/main.py", line 35, in <module> main() File "D:/Projects/FBMarketPlace/main.py", line 26, in main post_one.post_one() File "D:\Projects\FBMarketPlace\post_one.py", line 39, in post_one cursor.execute(config.sql_one_posting, PostID) File "D:\Projects\FBMarketPlace\env\lib\site-packages\MySQLdb\cursors.py", line 203, in execute raise ProgrammingError(str(m)) MySQLdb._exceptions.ProgrammingError: %d format: a number is required, not bytes I am using this query but it's not working and in MySQL it is showing a syntax error: SELECT vwAllUniqueListings.*, tblPersons.fbEmailAddress, tblPersons.fbPassword, tblPersons.fbExactName FROM vwAllUniqueListings LEFT OUTER JOIN tblPersons ON vwAllUniqueListings.personUniqueID = tblPersons.personUniqueID WHERE **(vwAllUniqueListings.UniquePostingID =%d)** ORDER BY vwAllUniqueListings.UniquePostingID* This is occurring in a Django/MySQLdb application. -
SQL identifier parts must be strings
I am trying to create a database based on user input. Whenever I tried I have following error "SQL identifier parts must be strings". Please check and support to clear this issue. def dbcreation(request): if "GET" == request.method: dbname = request.GET.get('username') return render(request, 'dbcreation.html', {}) else: dbname = request.GET.get('username') con = psycopg2.connect(user='postgres', host='127.0.0.1',password='test@123') con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = con.cursor() cur.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(dbname))) # print("Your DB has been created!.. Your DB Name is :" + dbname + ";") return render(request, 'dbcreation.html', {'username': dbname}) <form role="form" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="username">Enter Workspace Name Here :</label> <input id="username" type="text" name="username"> <input type="submit" value="OK"> </form> -
Dajngo- Error Field 'id' expected a number but got string
There is a table like this: +---+----+-------+------+ | | id | color | type | +---+----+-------+------+ | 1 | 1 | Blue | 2 | +---+----+-------+------+ | 2 | 2 | Green | 4 | +---+----+-------+------+ | 3 | 3 | White | 5 | +---+----+-------+------+ | 4 | 4 | Red | 6 | +---+----+-------+------+ | 5 | 5 | Gray | 8 | +---+----+-------+------+ In template, there are two fields to do search in this table. One field for searching for color that is a string, and the other for type that is a number. In views.py I have this filter: results = models.MyModel.objects.filter(Q(color__iexact=search_query) | Q(type=search_query)) If I search for a number it shows some results, while searching for a string results in error as below: ValueError at /search/ Field 'id' expected a number but got 'White'. What should I do to correct it? -
Django-allauth templates missing from site-packages
I installed allauth. all up and running correctly etc but now i want to customise my forms I cannot find the allauth templates inside my site-packages. Wondering if there is a step I missed during installation to make sure these are available? -
Emails can't be sent to my gmail using Django
what i have in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'pi**@gmail.com' EMAIL_HOST_PASSWORD = '********' what i have on forms.py from django import forms class contactEmail(forms.Form): contact_name=forms.CharField(required=True) contact_email=forms.EmailField(required=True) subject=forms.CharField(required=True) contact_message=forms.CharField(widget=forms.Textarea,required=True) what i have on views.py from django.shortcuts import render from Myportfolio.forms import contactEmail from django.core.mail import send_mail from django.conf import settings def contact(request): if request.method=='GET': form=contactEmail() else: form=contactEmail(request.POST) if form.is_valid(): name=form.cleaned_data['contact_name'] subject = form.cleaned_data['contact_subject'] email=form.cleaned_data['contact_email'] message=form.cleaned_data['contact_message'] send_mail(name, subject, email, message, ['pinkymononyane@gmail.com', email]) return render(request, 'Myportfolio/contact-me.html', {'form': form}) what i have on contact-me.html <form method="post" class="breakable contactUsForm " data-thanks-msg="Thank you for contacting me, I have received your message and I will come back to you shortly" data-date-format="m/d/Y" data-click-action=""> {% csrf_token %} <div class="col-md-12"> <div class="row"> <div class="col-md-12"> <div class="form-group"> <input type="text" name="contact_email" placeholder="From Email address" class="form-control s123-force-ltr" data-rule-email="true" data-msg-email="Please enter a valid email." required data-msg-required="This field is required."> </div> </div> <div class="col-md-12"> <div class="form-group"> <input type="text" name="contact_subject" placeholder="Subject" class="form-control"> </div> </div> </div> <div class="form-group"> <input type="text" name="contact_name" placeholder="name" class="form-control" required data-msg-required="This field is required."> </div> <div class="form-group"> <textarea class="form-control" name="contact_message" placeholder="Message" style="min-height: 100px;" required data-msg-required="This field is required."> </textarea> </div> <button type="submit" class="btn btn-primary btn-block">Contact Me</button> </div> <input type="hidden" name="w" value=""> <input type="hidden" … -
Global variables not receiving data from computed variables hence data can't be displayed on html doc using django
***here is what I have in my models.py from django.db import models # Create your models here. global_msp = 0 global_mspSales = 0 global_ago = 0 global_agoSales = 0 class Stock(models.Model): global global_msp global global_ago msp = models.IntegerField(blank=True, null=True) msp2 = models.IntegerField(blank=True, null=True) ago = models.IntegerField(blank=True, null=True) total = models.IntegerField(blank=True, null=True) date_posted = models.DateTimeField(auto_now=True) def __str__(self): return 'Stock{}'.format(self.id) class Meta: verbose_name_plural = 'Opening Stock' def Total(self): x = self.msp y = self.msp2 ans = x + y return ans total = property(Total) global_msp = total global_ago = ago class Sales(models.Model): global global_mspSales global global_agoSales msp_sales = models.IntegerField(blank=True, null=True) # msp sales value put by user ago_sales = models.IntegerField(blank=True, null=True) # ago sales value put by user total_sales = models.IntegerField(blank=True, null=True) # to be automatically computed msp_price = models.IntegerField(blank=True, null=True) # msp price value put by user ago_price = models.IntegerField(blank=True, null=True) # ago price value put by user msp_mult_price = models.IntegerField(blank=True, null=True) # to be automatically computed ago_mult_price = models.IntegerField(blank=True, null=True) # to be automatically computed total_mult_price = models.IntegerField(blank=True, null=True) # to be automatically computed def __str__(self): return 'sales {}'.format(self.id) class Meta: verbose_name_plural = 'Sales Unit & Cash' global_mspSales = msp_sales global_agoSales = ago_sales def salesTotal(self): x = self.msp_sales + self.ago_sales … -
Django JsonResponse doesnt work when using a helper function
Question summary: How can I use helper functions(not the view itself) to send JsonResponse? Issue summary: I am trying to send a JsonResponse containing dynamically updated data to a ChoiceField and I have achieved partial success but I lack understanding of something foundamental in the process obviously. The idea is when the date in the corresponding field changes, to fire up a function that gets the available hours from the DB for the selected day and updates the hours field for a date. The available hours are fetched by another helper function that belongs to the Form itself(code below). I have achieved partial success where everything works when the JsonResponse is sent directly by the View, however since I have to do this in 2 places at least, I would like to keep the code DRY. Therefore I wanted to implement a helper function that is called whenever the request.is_ajax() and sends the response to the endpoint. Below is the default code that works. View: def booking(request): if request.method == "POST": form = BookingForm(request.POST) if form.is_valid(): ////Creates a booking and redirects to home return redirect('home') else: form = BookingForm() if request.is_ajax(): date = request.GET.get('date') new_form = form(data={"timestamp": date}) # hours … -
How to create an immutable copy of the django model in python?
I want to create an immutable copy of the model instance, such that the user be able to access the details of the model, including its attributes, but not the save and the delete methods. The use case is that there are two repos accessing the django model, where one is supposed to have a writable access to the model, while another should only have a readable access to it. I have been researching ways of doing this. One way, I could think is the readable repo gets the model instance with a wrapper, which is a class containing the model instance as a private variable. class ModelA(models.Model): field1=models.CharField(max_length=11) class ModelWrapper: def __init__(self,instance): self.__instance=instance def __getattr__(self,name): self.__instance.__getattr__(name) The obvious problem with this approach is that the user can access the instance from the wrapper instance: # model_wrapper is the wrapper created around the instance. Then # model_wrapper._ModelWrapper__instance refers to the ModelA instance. Thus instance = model_wrapper._ModelWrapper__instance instance.field2="changed" instance.save() Thus, he would be able to update the value. Is there a way to restrict this behaviour? -
django redirect after post with post parameters after update
I was looking for help but couldn't find any suitable solution. I would like to ask about redirect after POST. Situation looks as below step by step: Simple search form with POST with parameter called 'find' within form. Search form appears on every site and if i call search on site with devices i'm checking referrer and i'm doing query for device model fields and results go to devices.html template. Same situation is when I search within localization site, checking for referrer and querying for model fields of localization model and returning query result in localization.html template. When I try to update device i'm opening new edit device template with url '/edit/device/dev_id' when every field of this model is shown so i can update some fields manually. After commiting changes on edit site device 'post' goes to url 'update/device/dev_id' and changes to device are saved properly. The problem is how can I redirect after updating device to step number one where are the results of search view for devices? If i redirect after update ('update/device/dev_id') device to 'request.META.get('HTTP_REFERER')' i'm getting 'edit/device/dev_id' url ? Worth to mention is that method POST for search form sends text search input to action="/search" and … -
Question and answer object matching in quiz
I have a question answer quiz. I have 2 pages. On the first page the user fills in the question and writes the answer, on the second page these questions come out and then have to have the Answer model input to check if the question was answered correctly, but when I return the questions to html and output the answer fields do not match without manually selecting. Here is such a result . I want the instance to automatically match but I do not want to pass the id in the view. I want all the questions to come out on one page. I could not figure out if I should use the model formset or anything else. How to automatically match the Answer input query models.py from django.db import models class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions") answer=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts …