Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3.0 tutorial - mysite/URL not working
I have completed all seven steps of the Writing your first Django app tutorial for 3.0. Everything works great, except the base site URL for 'mysite' at http://127.0.0.1:8000/. At the beginning of the tutorial, it worked, but it stopped working as I progressed/at the end. http://127.0.0.1:8000/admin/ works fine. Can anyone tell me what I'm doing wrong? Based on how the tutorial is structured, i.e. "add this and that and this and that," etc., that I overwrote something. Here is the error I'm receiving in my browser: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Here is the error I'm receiving in Terminal: Not Found: / [20/Jun/2020 11:01:22] "GET / HTTP/1.1" 404 2027 Here is my polls/urls.py file: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] Here is my … -
Django Allowed Hosts
I want only my front.domain.com to access the django API so i updated my settings.py . When i deployed i can access the django API via curl and postman so i'm confused here is there anything i'm missing ! settings.py DEBUG = False # deployment if DEBUG: FRONT_OFFICE_URL = 'http://127.0.0.1:4200/' ALLOWED_HOSTS = ['*'] # development CORS_ORIGIN_ALLOW_ALL = True # development else: FRONT_OFFICE_URL = 'https://front.domaine.com' ALLOWED_HOSTS = [FRONT_OFFICE_URL ] # deployment CORS_ORIGIN_WHITELIST = [FRONT_OFFICE_URL] CSRF_TRUSTED_ORIGINS = [FRONT_OFFICE_URL ] INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] -
Django ModelForm not submitting
The views are rendering the correct values to the template and there are no errors when I try to submit the form. Instead when I try to submit the form nothing happens. Let me know if you guys need more pictures or information, and thanks for helping me out! -
Serve React with Django Server
I am following this tutorial in order to serve React through Django server, but I only get a blank page when I access http://localhost:8000/admin, and I get the following errors on Django local server console: [20/Jun/2020 17:05:08] "GET /admin HTTP/1.1" 200 2217 [20/Jun/2020 17:05:08] "GET /static/css/main.5f361e03.chunk.css HTTP/1.1" 404 1821 [20/Jun/2020 17:05:08] "GET /static/js/main.853c8ab9.chunk.js HTTP/1.1" 404 1815 [20/Jun/2020 17:05:08] "GET /static/js/2.6d20342a.chunk.js HTTP/1.1" 404 1806 [20/Jun/2020 17:05:08] "GET /static/js/2.6d20342a.chunk.js HTTP/1.1" 404 1806 [20/Jun/2020 17:05:08] "GET /static/js/main.853c8ab9.chunk.js HTTP/1.1" 404 1815 I made all, and only, the changes stated in the tutorial. Thanks for your help. -
The same validation for multiple views in django rest framework
I have created a number of API endpoints for accepting POST requests using DjangoRestFramework. For 5/6 of them, I need to have 1 key in the body present providing some data so for each view I have if (key not in request.data): return Response('please provide key', status=400) How can I remove this duplication across all views? -
Pulling Values From List Python
I am working in Django and I am saving the below variable as a list: manifestData = form.cleaned_data so if I print this it returns: [{'ProductCode': <Product: APPLES-1>, 'UnitQty': u'11', 'Price': u'11.00', 'Amount': u'121', 'DescriptionOfGoods': u'Washington Extra Fancy', 'Type': u'Cases', u'id': None, u'DELETE': False}, {'ProductCode': <Product: ORANGES-1>, 'UnitQty': u'1', 'Price': u'12.00', 'Amount': u'12', 'DescriptionOfGoods': u'SUNKIST ORANGES', 'Type': u'Cases', u'id': None, u'DELETE': False}] I need to pull the ProductCode values out of this and save them to variables. Really I need the values APPLES-1 and ORANGES-1 pulled from the list. What would my best approach be for this? Thanks! -
Access Denied Django : (1045, "Access denied for user 'darth_vader'@'151.33.241.48' (using password: YES)")
I am using django 3.0 and using MySQL database for my web application. My settings.py code is: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'thirdihrms', 'USERNAME': 'admin', 'PASSWORD': 'xxxxxxxx', 'HOST': 'database-1.xxxxxxxxx.us-east-1.rds.amazonaws.com', 'PORT': '3306', } } And instead of connecting to the admin@151.33.241.48 it's getting connected to the darth_vader username. The darth_vader name is my ubantu machine (Local development environment) home user name. I see "darth_vader@Rushikesh-HP:~$ " when i open my terminal. The error message: Traceback (most recent call last): File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 233, in get_new_connection return Database.connect(**conn_params) File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/MySQLdb/__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/MySQLdb/connections.py", line 179, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'darth_vader'@'157.33.241.48' (using password: YES)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv … -
Django Save Object "Receipts"
I'm building a Django web application, part of it involves an online ordering system for food. I want to make a "receipt" object to save transactions. My concern, however, is this - let's say I have an object Receipt that relates to Orders which relate to Items, if the items get edited or change over time, it will make the receipts look different down the line. Is there a way to save these at the moment of a transaction? I am implementing a "soft deletion" to my models to avoid deletion issues however I don't think this would protect against edits. -
Building wheel error mysqliclient pythonnet..FAIL
I'm trying to install requirement.txt file and it seems like there's some issue with build wheel of couple packages which I can't figure out. This is the error I'm getting Building wheels for collected packages: mysqlclient, ndg-httpsclient, newspaper, nltk, oauthlib, pycountry, pycryptodomex, PyDispatcher, pyjwkest, pyodbc, pyserial, python-instagram, python-Levenshtein, python-openid, pythonnet, PyYAML, randomcolor, redis, requests-file, simplejson, ssh-import-id, supervisor, Twisted, Unidecode, winpython, zope.interface, django-pure-pagination, stem Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/rehman/projects/wdpjsenv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-m500R2/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-m500R2/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-m7ljPY cwd: /tmp/pip-install-m500R2/mysqlclient/ Complete output (39 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-2.7.16=. -fstack-protector-strong -Wformat … -
Django: How to optimize and reduce repetitive code the django way?
I am new to development and to Django, still learning OOP but I wanted to learn better with some examples from the code that I created. I have created a function in my view file. The function is getting very long and probably I will have to make it longer. I think the if statement could be written as a function but not sure where to start. What would be a way to reduce the code making it easier to maintain. Here is the code: def processView(request, pk): process = ProcessInfo.objects.get(id=pk) #bottlenecks = get_object_or_404(ProcessBottlenecks, process_info_id=process.id) try: details = ProcessDetails.objects.get(process_info_id=process.id) except ProcessDetails.DoesNotExist: details = None try: score = ProcessScoring.objects.get(process_score_id=pk) except ProcessScoring.DoesNotExist: score = None try: assumptions = ProcessAssumptions.objects.get(process_rel_process=process.id) except ProcessAssumptions.DoesNotExist: assumptions = None color_bottleneck = None color_quality = None color_datacomplexity = None color_technology = None color_transformation = None color_driversforchange = None color_technology = None #B if score.tot_score_bottlenecks_scoring in range(0, 200): color_bottleneck = 'badge-primary' if score.tot_score_bottlenecks_scoring in range(100, 500): color_bottleneck = 'badge-danger' if score.tot_score_bottlenecks_scoring in range(500, 1000): color_bottleneck = 'badge-warning' if score.tot_score_bottlenecks_scoring >= 1000: color_bottleneck = 'badge-success' #P if score.tot_score_dataquality in range(0, 200): color_quality = 'badge-primary' elif score.tot_score_dataquality in range(200, 500): color_quality = 'badge-danger' elif score.tot_score_dataquality in range(500, 100): color_quality = 'badge-warning' … -
Django query with existing format
I have model like below class Books(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) name = models.CharField(null=True, blank=True) How to query that will return author1 - Book 1 - Book 2 - Book 3 author2 - Book4 - Book5 -
ModelFormMixin + DateDetailView
I have a DateDetailViewPage with a comment form. The GET requests works fine, but I have problems with POST. Below the view: class PostDateDetailView(ModelFormMixin, DateDetailView): template_name = 'blog/post_detail.html' queryset = Post.published.all() date_field = "publish" month_format='%m' form_class = CommentForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print(self) obj = self.get_object() post_tags_pks = obj.tags.all().values_list('pk', flat=True) related_posts = self.queryset.filter(tags__in=post_tags_pks).exclude(pk=obj.pk) related_posts = related_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:3] context["related_posts"] = related_posts comments = obj.comments.filter(active=True) context["comments"] = comments context['post_id'] = obj.pk context['form'] = self.form_class return context def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) The error I'm receiving is 'PostDateDetailView' object has no attribute 'object'. This error comes when get_context_data() is called and tries: if self.object: Honestly, I can't figure out the reason of this error. I mean, why get_context_data works for GET and not for POST. Thanks in advance!! -
Beginner questions about Wagtail (in comparison with Django)
I'm a beginner learning Wagtail, and a lot of things are un-clear to me, and unfortunately not found sufficient explanation in Wagtail documentation. Please help and give me some answers, and I feel I'm on the edge of giving up on Wagtail and switching back to Django. Here are a few noob questions I have, How to handle POST request? I've watched a few tutorials at LearnWagtail.com, it seems in Wagtail, development is all about creating models, no need to set urls.py or views.py. And we could create Routable pages to respond to custom url-patterns. Question: but how to respond to POST request if without defining a view? I don't see any example of Routable page handling POST request. Is the home app the only entry to a Wagtail website? From what I see, home app is a default one created by Wagtail when a project is created. And the home.HomePage is the default page when I open the website on 127.0.0.1:8000. Question: so I cannot remove this home app? How to set urls.py or should we set them? For example, a typicall urls.py settings are as follows. And my understanding is the wagtail_urls will point to home.HomePage by default. … -
How to create two different user authentication table in django for two different type of users?
#Models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) # User Model For registration --------------------------------------------------------------------------- class StudentUserManager(BaseUserManager): def create_user(self, name,email,gender, password,picture=None, ): """ Creates and saves a User with the given email and password. """ if not gender: raise ValueError('User must have a gender') if not email: raise ValueError('Users must have an email address') user = self.model( name = name, email=self.normalize_email(email), gender = gender, picture = picture ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, name, email, gender, password,picture=None,): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( name = name, email=self.normalize_email(email), gender = gender, picture = picture, password=password, ) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class StudentUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) GENDER_CHOICE = ( ('Male','Male'), ('Female','Female'), ('Other','Other') ) name = models.CharField(max_length=100, default='Open Blog Forum User') gender = models.CharField(max_length=10,null=True, blank=False, choices = GENDER_CHOICE) picture = models.ImageField(upload_to='Student Pictures', blank = True, null=True) creationTime = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = StudentUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','gender'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: … -
Invalid HOST Header from router IP
I keep getting an Invalid HOST Header error which I am trying to find the cause of. It reads as such: Report at /GponForm/diag_Form Invalid HTTP_HOST header: '192.168.0.1:443'. You may need to add '192.168.0.1' to ALLOWED_HOSTS I do not know what /GponForm/diag_Form is but from the looks of it, it may be a vulnerability attacked by malware. I also am wondering why the IP is from a router 192.168.0.1 as well as why it is coming through SLL :443 Should I consider putting a HoneyPot and blocking this IP address? Before I do, why does the IP look like a local router? The full Request URL in the report looks like this: Request URL: https://192.168.0.1:443/GponForm/diag_Form?style/ I am getting this error at least ~10x/day now so I would like to stop it. -
Submit button in a form is not working in django
In my django template when I render whole form at once, submit button works and forms get submitted or error shows up if there's any. this is actually deafult form in django. no styling or no customization has ben done: employee_add_form.html: {% extends 'base.html' %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'employee/css/master.css' %}"> {% load bootstrap4 %} <div class=""> <form class="form" action="" method="post" id="employee_add_form"> {% csrf_token %} {% bootstrap_form form %} <!-- {% bootstrap_css %}--> {% bootstrap_javascript jquery='full' %} {{ form.media }} <div class=""> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> {% endblock %} but when I render like this, when I call form's fields manually one by one and apply some customized design to form like this: {% extends 'base.html' %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'employee/css/master.css' %}"> {% load bootstrap4 %} <div class=""> <form class="form" action="{% url 'employee:employee-add' %}" method="POST" id="employee_add_form"> {% csrf_token %} <!-- {% bootstrap_css %}--> {% bootstrap_javascript jquery='full' %} {{ form.media }} {{ form.non_field_errors }} <div class="container"> <label for=""><b>Personal Info</b></label> <div class="border"> <div class="form-row"> <div class="col"> {{ form.first_name.errors }} <label for="">First Name</label> {{ form.first_name}} </div> <div class="col"> {{ form.last_name.errors }} <label for="">Last … -
Combining django templates with content editable for non-technical users
We use django to generate HTML pages using templates which include javascript. Our website only consists out of a limited number of pages (creating new pages isn't a common use case) and we have people editing the content without python (and html) knowledge. Is there a way to have a simple user interface where non-technical editors can (in the best case) use a WYSIWYG editor to change the content (mainly text) of a template and a developer can build the page with html, css and javascript around it? The problem we see with full CMS system like Wagtail and Django-CMS is that they don't give us the same flexibility to build the pages and don't offer the needed functionality to make our platform configurable (When setting up the system, a user can configure their specific instance of the system as many use cases have the same structure and only need specific configurations). -
form_invalid method not displaying fields in error
I have a CBV CreateView and a django form that behaves correctly when you entered data that is valid. However, when the form has fields in error (duplicate phone number or more than one primary contact phone), then is re-displayed by form_invalid method, but the fields that were previously populated are now displayed blank. The customUser field in the Phone model which is the foreign key to the user CustomUser(AbstractUser) model appears to be blank when I print the request.post data. This is my model: class Phone(models.Model): COUNTRIES = ( (55, _('Brazil')), (1, _('United States of America')), ) PHONETYPES = ( ('1', _('Mobile')), ('2', _('Home')), ('3', _('Work')), ('4', _('Other')), ) status = models.CharField(_("Record Status"), max_length=1, default='A') status_dt = models.DateTimeField(_("Status Date"), default=timezone.now) customUser = models.ForeignKey(CustomUser, verbose_name=_("User"), on_delete=models.CASCADE) phone_name = models.CharField(_("Phone name"), max_length=20, default="PH"+str(random.randint(1,99999))) country = models.IntegerField(_("Country Dialing Code"), choices=COUNTRIES) phone_number = models.CharField(_("Phone Number"), max_length=11) phone_type = models.CharField(_("Phone Type"), max_length=1, default="4", choices=PHONETYPES) verified = models.BooleanField(verbose_name=_('verified'), default=False) primary = models.BooleanField(verbose_name=_('primary'), default=False) at_user = models.CharField(_("Audit Trail (user)"), max_length=255, blank=True) at_ip = models.GenericIPAddressField(_("Audit Trail (IP)"), protocol='both', blank=True, null=True) at_dttm = models.DateTimeField(_("Audit Trail (Date-Time)"), default=timezone.now) at_action = models.CharField(_("Audit Trail (Function performed)"), max_length=255, blank=True) UniqueConstraint(fields=['customUser', 'country', 'phone_number'], name='user_unique_phone_number') class Meta: verbose_name = _("Phone Number") verbose_name_plural = _("Phone … -
update manytomany related field in django
i want to to update a field related to M2M whenever an instance been created i tried signals but it seems complicate to ManyToManyField i tried these ways but non of them worked in my case , i appreciate your helps def mobile_customer(sender,instance,created,*args,**kwargs): if created: for status in instance.imei.all(): Imei.objects.filter(pk=status.id).update(active=False) post_save.connect(mobile_customer,sender=SelectMobileCustomer) and also this in my CreateView class views.py Imei.objects.filter(selectmobile__item=self.object).update(active=False) even if i try to print Imei.objects.filter(selectmobile__item=self.object).update(active=False) the output will be 0 ! this is my model design class MobileCustomer(models.Model): customer = models.CharField(max_length=30) phone = models.CharField(max_length=13) mobile = models.ManyToManyField(MobileStorage,through='SelectMobile') class SelectMobile(models.Model): mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) item = models.ForeignKey(MobileCustomer,on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) imei = models.ManyToManyField(Imei) class MobileStorage(models.Model): mobile = models.ForeignKey(Mobile,on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Mobile(models.Model): mobile_name = models.CharField(max_length=40,unique=True) class Imei(models.Model): imei = models.CharField(max_length=15,verbose_name='IMEI',unique=True) mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) active = models.BooleanField(default=True) i appreciate your helps .. thanks -
Django - Rendering new form fields based on selected choices
Is it possible to render new form fields based on the selected form choices? Consider this model and form: class Task(models.Model): client = models.ForeignKey(models_extra.Client, on_delete = models.CASCADE) task = models.ForeignKey(models_extra.TaskType, on_delete = models.CASCADE) description = models.ForeignKey(models_extra.Description, on_delete = models.CASCADE) class TaskSelectForm(forms.ModelForm): class Meta(): model = Task fields = '__all__' How can i make it so the form renders new fields for every specific task? Assume that i have an extra model (i don't and i'm not sure that the solution is about this): class ExtraInfo(models.Model): task = models.ForeignKey(models.Task, on_delete = models.CASCADE) field = models.CharField(max_length = 100) In this new model i have 3 entries for task nr 1 -> (task1, 'Airport') (task1, 'Order nr') (task1, 'Subject') How can i make it for my template to render the new fields "Airport", "Order nr" and "Subject" when the task with id = 1 is selected? edit. I've already made this question today but i'm simplyfing it in order to get some ideas. -
Django - Class Function not returning page
I am trying to create code for my Django site which will take the user's input, perform a calculation, and then send the data back to the user in the form of a new page, however everytime I run the code, it does not create the new page nor does it post the results. Below is the function itself. def SparkCalc(request): new_item = sparkCalculator() new_item.tix = request.POST['tix'] new_item.tenrolls = request.POST['tenrolls'] new_item.crystals = request.POST['crystals'] new_item.save() total = new_item.getTotal() return render(request, 'SparkResults.html', {"title": "Spark Results"}, {"total": total}) and below is the Django page I am calling it from: <form action="/SparkCalc/" method="POST">{% csrf_token %} <label for ="tix">Please enter your single roll tickets</label> <input type="text" id="tix" name="tix"/> <label for ="tenrolls">Please enter your ten-roll tickets</label> <input type="text" id="tenrolls" name="tenrolls"/> <label for ="tix">Please enter your total crystal amount</label> <input type="text" id="crystals"name="crystals"/> <input type="submit" value="Get Results"/> </form> And finally below is the class I created: class sparkCalculator(models.Model): tix = models.PositiveIntegerField() tenrolls = models.PositiveIntegerField() crystals = models.PositiveIntegerField() def getTotal(self): return (int(self.tix)*300) + (int(self.tenrolls)* 3000) + int(self.crystals) The way I envision the code to work is that once the user enters their information into the form, Django then runs the SparcCalc function, collecting the information entered, performing the math … -
How can I link an object on save in django to an existing one if there is a matching value between them?
I'm using Django and DRF to to reconcile two lists of data (promises to pay, and payments). When uploading new payments, if the payment transaction ID shares the same ID as a promise to pay, I want to link them by saving the corresponding promise in the payment's foreign key field. I have two models: class Promise(models.Model): transaction_id = models.CharField(max_length=50) amount_promised = models.DecimalField(decimal_places=2, max_digits=8) created_on = models.DateTimeField(auto_now_add=True) class Payment(models.Model): promise = models.OneToOneField(Promise, on_delete=models.CASCADE, blank=True) transaction_id = models.CharField(max_length=50) amount_paid = models.DecimalField(decimal_places=2, max_digits=8) created_on = models.DateTimeField(auto_now_add=True) and two views: class PromiseViewSet(viewsets.ModelViewSet): permission_classes = (IsCreatorOrReadOnly,) queryset = Promise.objects.all() serializer_class = PromiseSerializer class PaymentViewSet(viewsets.ModelViewSet): permission_classes = (IsCreatorOrReadOnly,) queryset = Payment.objects.all() serializer_class = PaymentSerializer My understanding is this requires a custom save method, but I'm not certain if the magic should be happening in views or models. Either way, the logic should be something like: Loop through promises...if the new payment.transaction_id = a promise.transaction_id, break and link the two together by saving the promise.pk to the promise foreign key in the newly created payment object. And the solution would look something like this: warning, this is rough! def save(self, *args, **kwargs): #check if promise ID was manually entered, if not continue if self.promise is None: … -
How do I allow groups to access the admin page with an is_staff property?
I have 3 groups and I want two to be able to access the admin page with different permissions. I'm just building off the base user model. The closest I feel I've gotten is from a previous Stackoverflow post Django admin is_staff based on group from django.db import models from django.contrib.auth.models import User class User(User): @property def is_staff(self): if user.groups.filter(name="Level2").exists(): user.is_staff = True else: user.is_staff = False -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 0: invalid continuation byte
I've started making a Python project on my old computer and have decided to transfer all the files to the new one. Now, when I run python manage.py runserver it returns UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 0: invalid continuation byte June 20, 2020 - 12:05:37 Django version 3.0.7, using settings 'learning_log.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 139, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\servers\basehttp.py", line 206, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\servers\basehttp.py", line 67, in __init__ super().__init__(*args, **kwargs) File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\socketserver.py", line 452, in __init__ self.server_bind() File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\http\server.py", line 139, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\Гаджибек\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 676, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 0: invalid continuation byte``` -
How to get class name of an HTML tag from django backend
Teacher Student these span sets class= active using styles while selecting the span. How I can get the class name of the individual spans, or check any of the span is having a class="active"