Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store only the desired values in Django View
I'm a student learning Django for the first time. I want to save only the values I want in Django's View, but I don't know what to do. Below are Models.py and Views.py, forms.py. I want to save it by entering only one without entering second_value and third_value in value_name. Please help me a lot. def product_upload(request): current_category = None categories = Category.objects.all() products = Product.objects.all() photos = Photo.objects.all() designated_object = Designated.objects.all() options = Option.objects.all() slug = Product.slug if request.method == "POST": form = ProductForm(request.POST, request.FILES) if form.is_valid(): product = Product() product.name = form.cleaned_data['name'] product.benefit = form.cleaned_data['benefit'] product.detail = form.cleaned_data['detail'] product.target_price = form.cleaned_data['target_price'] product.start_date = form.cleaned_data['start_date'] product.due_date = form.cleaned_data['due_date'] product.category_code = form.cleaned_data['category_code'] product.image = request.FILES['photo'] product.username = request.user product.slug = slug product.kakao_link = form.cleaned_data['kakao_link'] product.save() for img in request.FILES.getlist('image'): photo = Photo() photo.product_code = product photo.photo = img photo.save() if request.method == "POST": form = OptionForm(request.POST) if form.is_valid(): option = Option() option.name = form.cleaned_data['option_name'] option.product_code = product option.save() if request.method == "POST": form = ValueForm(request.POST) if form.is_valid(): value = Value() value.name = form.cleaned_data['value_name'] value.option_code = option value.product_code = product value.extra_cost = form.cleaned_data['option_price'] value.save() if request.method == "POST": form = ValueForm(request.POST) if form.is_valid(): value = Value() value.name = form.cleaned_data['second_value'] value.option_code = … -
{"user":["This field is required."]} in Django REST Framework
Where does Django get the User from in self.request.user? When executing a GET request, Django sees the User, and when executing a POST request, he does not see it and throws such an error. User information is transmitted in the cookie from the frontend. views.py from rest_framework import generics from rest_framework.permissions import IsAuthenticated from rest_framework import pagination from rest_framework.response import Response from api.models.notes import Notes from api.serializers.notes import NotesSerializer class FilterNotes(generics.ListCreateAPIView): serializer_class = NotesSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): return Notes.objects \ .filter(user=self.request.user.id) \ .order_by('-time') -
Show products based on category slug in Django 3
I have created a category and subcategory in a project and it is showing as I wanted, but now having a little difficulty in getting the products to the category page. I have a parent category and sub-category but not in all cases will the parent category have a subcategory. #models.py #Category Model class Category(models.Model): name = models.CharField(max_length=20) slug = models.SlugField(max_length=25) parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=True, null=True) class Meta: verbose_name_plural = 'Categories' ordering = ('name',) def __str__(self): return self.name #Product Model class Product(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=110) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) #views.py def home(request): products = Product.objects.all().order_by('?') categories = Category.objects.all() featured_products = Product.objects.filter(is_featured=True) context = { 'products':products, 'category':categories, 'featured_products':featured_products } return render(request, "store/home.html", context) Below is my HTML code <div class="container"> <nav class="main-nav"> <ul class="menu sf-arrows"> <li class=""><a href="{% url 'home-page' %}">Home</a></li> <li class=""><a href="{% url 'about-page' %}">About</a></li> <li class=""><a href="{% url 'home-page' %}">Services</a></li> {% for category in category %} {% if category.parent == None %} {% if category.parent.children %} <li><a href="{{category.get_absolute_url }}" class="sf-with-ul">{{category.name}}</a> {% else %} <li><a href="{{category.get_absolute_url }}" class="">{{category.name}}</a> {% endif %} <ul> {% for subcategory in category.children.all %} <li><a href="{{sucategory.slug}}">{{subcategory.name}}</a></li> {% endfor %} </ul> </li> {% endif %} {% endfor %} <li … -
Django: Save method to save total of 3 columns in another model
I have 2 models as follow: class particulars(models.Model): reportref = models.ForeignKey(reportname,on_delete=models.CASCADE) year = models.CharField(max_length=250) sales = models.FloatField(blank=True,null=True,default=0) profit = models.FloatField(blank=True,null=True,default=0) def save(self, *args, **kwargs): self.profit = round((self.sales-self.depreciation),2) super(particulars, self).save(*args, **kwargs) def __str__(self): return str(self.year) class depreciation(models.Model): reportn = models.ForeignKey(reportname,on_delete=models.CASCADE) asset = models.CharField(max_length=250) cost = models.FloatField(blank=True,null=True,default=0) rate = models.FloatField(blank=True,null=True,default=10) depreciation_1 = models.FloatField(blank=True,null=True) wdv1 = models.FloatField(blank=True,null=True) depreciation_2 = models.FloatField(blank=True,null=True) wdv2 = models.FloatField(blank=True,null=True) depreciation_3 = models.FloatField(blank=True,null=True) wdv3 = models.FloatField(blank=True,null=True) depreciation_4 = models.FloatField(blank=True,null=True) wdv4 = models.FloatField(blank=True,null=True) depreciation_5 = models.FloatField(blank=True,null=True) wdv5 = models.FloatField(blank=True,null=True) def save(self, *args, **kwargs): self.depreciation_1 = round((self.cost*self.rate/100),2) self.wdv1 = round((self.cost-self.depreciation_1),2) self.depreciation_2 = round((self.wdv1*self.rate/100),2) self.wdv2 = round((self.wdv1-self.depreciation_2),2) self.depreciation_3 = round((self.wdv2*self.rate/100),2) self.wdv3 = round((self.wdv2-self.depreciation_3),2) self.depreciation_4 = round((self.wdv3*self.rate/100),2) self.wdv4 = round((self.wdv3-self.depreciation_4),2) self.depreciation_5 = round((self.wdv4*self.rate/100),2) self.wdv5 = round((self.wdv4-self.depreciation_5),2) super(depreciation, self).save(*args, **kwargs) def __str__(self): return str(self.asset) I have written save method to update depreciation for each year whenever a user put cost for assets. However I need to also update particulars model with depreciation for each year. What I am trying to get is total the depreciation of each asset for every year and put it in particulars table. Any way to do that? -
No "Authorization" header, how to access authorization header? Django
I need to check the Authorization HTTP Header of every incoming request. First i have implemented Middleware. Now on website in devtools (when i post something) i see authorizational header with token. class MyMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user_id = request.POST.get('created_by', False) try: api_token = CustomUser.objects.get(user=user_id).api_token except CustomUser.DoesNotExist: api_token = '' response = self.get_response(request) response['Authorization'] = "Bearer " + api_token return response and now im trying to access Authorization HTTP Header of every incoming request to validate it but there is no Authorization Header class EventApiView(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = Event.objects.all() serializer_class = EventSerializer @action(methods=['POST'], detail=False) def post(self, request): print(request.META['HTTP_AUTHORIZATION']) **#keyerror** print(request.META['Authorization']) **#keyerror** print(request.headers.items()) **#no authorization header** tutorial_serializer = EventSerializer(data=request.data) if tutorial_serializer.is_valid(): tutorial_serializer.save() return Response(tut`enter code here`orial_serializer.data, status=status.HTTP_201_CREATED) return Response(tutorial_serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django; update products but preserve purchase history
TLDR: How to edit products without changing the history of order/purchases wherein that product has been bought? I want to incorporate the option to do purchases in my website. I have a backend with django-drf and frontend react. In the frontend I want to be able to add, edit, and remove products. To create a consistent database I see two things being done on stack: copy all relevant fields from the product table over to the purchase table upon edit of a product create a new product instead of actually updating, and upon removal of a product flag it as deleted instead of actually deleting I am inclined to favor the second option, since it keeps the database easier to understand and maintain. However, it makes the update and removal logic harder. My toughts for implementation are roughly this: models.py from django.db import models class Product(models.Model) : name = models.CharField(max_length=120) price = models.DecimalField(max_digits=10, decimal_places=2) has_been_removed = models.BooleanField(default=False) ... class Purchase(models.Model) : product = models.ForeignKey(Product, related_name="purchases", on_delete=models.PROTECT) quantity = models.IntegerField(max_length=120) total = models.DecimalField(max_digits=10, decimal_places=2) ... serializer.py from django.db import models from .models import Product, Purchase class ProductSerializer(models.Serializer): ... def update(self, instance: Product, validated_data): has_associated_purchases = Purchases.objects.filter(product=instance).exists() if has_associated_purchases: new_product = Product(**validated_data) … -
How to handle a formset in function based view
I'm trying to implement a formset in function create based view to allow users to create their own course model, somehow when i try posting the data to the database only the course model data get sent to the database leaving the module data not persisted to the data base. why is function create view not persisting the data, Of my module to the model data base and how best can i do this. I know of the class create view solution but it actually doesn't help in my user case. and so i think using a function create view will be much favorable to my case. Here my function create view. def course_create(request): Formset = formset_factory(CreateCourse, extra=2) if request.method =="POST": formset_data = Formset(request.POST, request.FILES) sub = request.POST.get('subject') course = request.POST.get('title') overview = request.POST.get('overview') slug = request.POST.get('slug') pic = request.FILES['c_pic'] owner = Account.objects.get(username=request.user.username) sub,create = Subject.objects.get_or_create(title=sub) data = Course(title=course,owner=owner, pic=pic, subject=sub, slug = slug, overview=overview) data.save() if formset_data.is_valid(): data = formset_data.save(commit=False) data.course = data formset_data.save() return redirect('courses:main') Here is my Forms.py class CreateCourse(forms.ModelForm): class Meta: model = Module fields = ['title', 'description'] def save(self,commit=True): module = super(CreateCourse, self).save(commit=False) module.title = self.cleaned_data["title"] module.description = self.cleaned_data['description'] if commit: module.save() return module model.py … -
Django form with model choice filed
i have a problem with form in django. I was create a model form but he not save choicefield to database.Form save only a title(CharField).I was create a function that solving problem but i think its bad and can be write much better. Any help? class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) TOPIC_CAT=[ ('WEL', 'Spawlnictwo'), ('DIY', 'Majsterkowanie'), ('ELE', 'Elektryka'), ('IT', 'Informatyka'), ('CAT', 'Stolarstwo'), ] categories = models.CharField(max_length=3, choices=TOPIC_CAT) def __str__(self): return self.text FORM class NewTopic(forms.ModelForm): class Meta: model = Topic fields = ['text', 'categories',] labels = {'text':'Nazwa tematu', 'categories': 'Kategoria'} FUNCTION def new_topic(request): if request.method != 'POST': form = NewTopic() else: form = Search(data=request.POST) if form.is_valid(): new_topic = form.save(commit=False) cat = request.POST.get('categories') new_topic.categories = cat new_topic.save() return redirect('forum:topics_in_category', category=cat) context = {'form': form} return render(request, 'forum/new_topic.html', context) Second problem is a search form.I want the search field to be visible all the time like in stackoverflow website but i dont have idea how.Already did a button that open a new website with form -.- -
is it ok to create ManyToMany with no through Field?
so in Django models documentation when I have to add extra data to ManytoMany fields, the django documentation recommend I use 'through' like this example class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) in the admin panel this is good but when I try to use it on views.py to create API I get many problems that I can't get Membership fields info from Group model but when I created model like that it became possible: class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField('Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) not following docs makes me feel I'm doing it wrong since I'm a beginner I don't know if the way I did is good or not? like is it bad to create a model like that? if I should go back to using 'through' then is there a possible way to get Membership fields from the Group model? -
Why the translate tag doesn't work outside a block?
I have a base template... {% load static %} {% load i18n %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> {# Translators: The title of the website #} {% translate "FilFak" as the_title %} {# Translators: The description and subtitle of the website #} {% translate "Appointments, tasks and much more" as the_description %} <meta name="title" content="{{ the_title }}" /> <meta name="description" content="{{ the_description }}" /> <meta property="og:title" content="{{ the_title }}" /> <meta property="og:description" content="{{ the_description }}" /> <title>{% block title %}{{ the_title }}{% endblock title %}</title> <link href="{% static 'css/style.css' %}" rel="stylesheet" type="text/css" /> </head> <body> <header> <h1><a href="{% url 'index' %}">{{ the_title }}</a></h1> <p>{{ the_description }}</p> </header> <main> {% block content %} {% endblock content %} </main> <footer> {% include "courses/lang_form.html" %} </footer> </body> </html> And I have a few templates extending the base templates. Here's an example. {% extends "courses/base.html" %} {% load i18n %} {% translate "List of professors" as page_title %} {% block title %}{{ page_title }} | {{ block.super }}{% endblock title %} {% block content %} {% for professor in professor_list %} <article> <header> <h3 class="title"><a href="{% url 'professor_details' professor.slug %}">{% if professor.title %}{{ professor.title }} {% endif %}{{ professor.name }}</a></h3> </header> <p><span … -
Why Django ORM multiplies my results as many times as many users I have?
Im working on a project where I need to query some stuff but I'm not familiar with Django ORM. My query works fine but it multiplies the result as man time as my user related to a project and I can't figure it out how to limit it. In raw query I usually do it with inner join but this works not in this case. views.py def projects(request): jogosult = Projekt.objects.filter(jogosult_01_id=request.user) jog_projekt = Projekt.objects.filter(jogosult_01=request.user).order_by('-date') context = { 'jogosult': jogosult, 'jog_projekt': jog_projekt, } return render(request, 'stressz/projects.html', context) html {% for j in jogosult %} {% if request.user == j.jogosult_01 %} {% for jp in jog_projekt %} <a href="/mpa/project_details/report/{{ jp.id }}">{{ jp.projekt }}</a> {% endfor %} {% else %} You have no projets {% endif %} {% endfor %} models.py class Projekt(models.Model): def __str__(self): return str(self.projekt) projekt = models.TextField(max_length=150) company_name = models.ForeignKey('Company', on_delete=models.CASCADE, default=1) jogosult_01 = models.ForeignKey(User, on_delete=models.CASCADE, default=1) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) -
Connecting locally to online db mysql server with django
I have made a database on an online server http://remotemysql.com/ with the remote access on https://www.webphpmyadmin.com/ I am making my first web app in django and I wanted to connect to that server locally. Is it possible? I tried using these settings: but I have been getting this error: I have also tried using my ip adress instead of 'remotemysql.com' host, but again - I got other error: The localhost doesn't work too even with having apache and mysql running on xampp (it doesn't work both with these two running and stopped): The same with: I literally had already tried everything that I found on stackoverflow and any other forums, but nothing worked for me. That's why I decided to post a question myself. My requirements.txt: Do I have to have this database copied locally to use it in my app or is it really possible to connect it by settings.py? -
How to fix OSError: [WinError 2] The system cannot find the file specified
I tried installing Fastapi framework dependencies using the pip install Fastapi[all] command. The packages were downloaded but during installation, I got this error. Using legacy 'setup.py install' for python-multipart, since package 'wheel' is not installed. WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution - (c:\python39\lib\site-packages) Installing collected packages: sniffio, idna, colorama, typing-extensions, h11, click, anyio, websockets, watchgod, uvicorn, urllib3, starlette, six, pyyaml, python-dotenv, pydantic, MarkupSafe, httptools, dnspython, charset-normalizer, certifi, ujson, requests, python-multipart, orjson, jinja2, itsdangerous, fastapi, email-validator WARNING: Failed to write executable - trying to use .deleteme logic ERROR: Could not install packages due to an OSError: [WinError 2] The system cannot find the file specified: 'c:\\python39\\Scripts\\watchgod.exe' -> 'c:\\python39\\Scripts\\watchgod.exe.deleteme' WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution - (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution - (c:\python39\lib\site-packages) Python version: Python 3.10.0 pip version: pip 21.3 from c:\python39\lib\site-packages\pip (python 3.9) -
Django - Query 10 table objects before or after a date?
I was reading this blog on pagination, but I'm trying to do quick queries by create date time. So for example if I get a request and one of the parameters is a date time I want a quick way to get the next 10 posts created in order. The reason I can't use this blog post is because the table could be updated by the time the user tries to request older or newer posts as it gets updated quite frequently. So in a simple toy example: If I have a list of dates [1-01-2021, 1-05-2021, 1-06-2021] and I already sent 1-01-2021 to the user and the user sends me that date and expects the next single date it should return 1-05-2021 and not return dates it already has. How can I do this quickly and efficiently? I imagine it might be tricky, because I have to order my table first. I'd like to be to do this in 2 directions as in forward and backward in times. So if someone gives me a date to one endpoint will return the 10 posts that came after that and another endpoint if given a date it will return the 10 … -
Django Datetime function
Am aiming for the value 'grade' to be incremented by 1 on 25th every month. The below function doesn't seem to be working. Where could I be going wrong? Attached is the model and function. class Student(models.Model): student_name = models.CharField(max_length=100, null=True) extra_role = models.CharField(max_length=100, default='None', null=True) gender = models.CharField(max_length=20, choices = gender, default = "female") dob = models.DateField(null=True, blank=True) grade = models.IntegerField(choices=grade) parent_phone = PhoneField(blank=True, help_text='Contact phone number') # admNo = models.AutoField() @property def age(self): if(self.dob != None): age = date.today().year - self.dob.year return age @property def sgrade(self): if datetime.today().day == 25: grade = self.grade +1 return grade -
How to solve add key and value in local storage in the django website?
This is a Social network website. It's build in python django.I need to add the user login section the values stored in the local storage section. in this website have 2 login method one is end user and another is companies the main setting is need user is login that time the key and value is need to store the local storage this is need for cross site login for users for example facebook users have join in through instagram. please help me for the solution ? I need to fix the set cookies in the session also -
Create an API Gateway on an existing python project
To explain the context, I am currently developing a microservice application with 4 entities: Publishers [with a simulator]. A Queue system Receivers (which also do local processing) [in Python]. A front end that GETs data with a REST API on the receiver [in React]. My problem is the following: To set up a Gateway API between the receiver and the front end, I simply threaded the Receiver microservice to add a classic Flask execution. It seems to work, but I'm sure it's not the best solution... Initially I really thought of the Gateway API as a microservice in its own right, rather than an "add-on" to the Receiver -
model_to_dict: AttributeError: 'str' object has no attribute '_meta'
I have following error when I run the code. Can any of you please help to me solve the issue ? AttributeError: 'str' object has no attribute '_meta' Traceback (most recent call last): File "C:\Users\ipcramk\PycharmProjects\Quality_Check_UI\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\ipcramk\PycharmProjects\Quality_Check_UI\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\ipcramk\PycharmProjects\Quality_Check_UI\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\ipcramk\PycharmProjects\Quality_Check_UI\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\ipcramk\PycharmProjects\Quality_Check_UI\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\ipcramk\Desktop\Desktop files\pYTHON TRAINING\Django\Quality_Check_UI\QC_project\app1\views.py", line 328, in qc3_approval_view cn_data_form = qc3_approval_form( instance=request.GET['key'] ) File "C:\Users\ipcramk\PycharmProjects\Quality_Check_UI\lib\site-packages\django\forms\models.py", line 292, in __init__ object_data = model_to_dict(instance, opts.fields, opts.exclude) File "C:\Users\ipcramk\PycharmProjects\Quality_Check_UI\lib\site-packages\django\forms\models.py", line 82, in model_to_dict opts = instance._meta AttributeError: 'str' object has no attribute '_meta' [24/Oct/2021 12:02:40] "GET /cn_entry/approval_page?key=2 HTTP/1.1" 500 92849 Views.py def qc3_approval_view(request): cn_data_form = qc3_approval_form( instance=request.GET['key'] ) forms.py class qc3_approval_form(forms.ModelForm ): class Meta: model = cn_data_tables fields = ('status_qc3',) models.py class cn_data_tables(models.Model): sl_no = models.AutoField(primary_key=True) cn_number = models.CharField(max_length=10, null=False) status_qc3 = models.ForeignKey( 'status_list_table',related_name='status_qc3', on_delete=models.CASCADE, default=3 ) def __int__(self): return self.sl_no -
Json Response is not returning through success (Showing direct response after submit)
I am building a Blog App and I am trying to save instance through ajax and I am returning Json Response in view, But Json Response is not successfully returning instead it is showing response after form submit like {"action": "saved"}, I have tried by changing response but it is showing exactly the returnable response, It is supposed to show success message but it is not returning that. Form is submitting fine in Admin. views.py def posts(request): posts = Blog.objects.all() if request.method == "POST": form = BlogForm(data=request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.submit_by = request.user new_post.comment_of = comment new_post.save() else: form = BlogForm context = {'posts':posts,'form':form} return render(request, 'posts.html', context) def EditAllPosts(request, blog_id): comment = get_object_or_404(Blog, pk=blog_id) if request.method == "POST": form = BlogForm(data=request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.submit_by = request.user new_post.comment_of = comment new_post.save() return JsonResponse({'bool': True}) else: return JsonResponse({'bool': form.errors}) posts.html {% for blog in posts %} <form method="post" id="blog-form-" data-data="{{coms.pk}}" enctype="multipart/form-data" action="{% url 'EditAllPosts' blog.id %}"> {% csrf_token %} {{form}} <input type="submit" data-data="{{coms.pk}}" onclick="saveInstancOnClick({{forloop.counter}})"> </form> <script> $(document).ready(function(){ function saveInstancOnClick(id) { document.getElementById(`blog-form-${forloop.counter}`); var _questionid=$(this).data('data'); let thisElement = $(this); $.ajax({ url: thisElement.attr('action'), type:"post", data:{ csrfmiddlewaretoken:"{{csrf_token}}" }, dataType:'json', success: function(res) { if (res.bool == true) { alert("Worked") } } … -
Replacing a letter with "#" and reverse. In Python Django and HTML
I am new to python and doing a test program that replaces all the letters in a given text with signs. def encrypted(request): text = request.GET['text'] text = text.replace("a", "#.") text = text.replace("b", "##.") text = text.replace("c", "###.") text = text.replace("d", "####.") text = text.replace("e", "#####.") text = text.replace("f", "######.") etc... return render(request, 'encrypted.html', {'text': text}) I have achieved that but I have tried reversing it the same way and it does not work. def decrypted(request): ftext = request.GET['text'] ftext = ftext.replace("#.", "a") ftext = ftext.replace("##.", "b") ftext = ftext.replace("###.", "c") ftext = ftext.replace("####.", "d") ftext = ftext.replace("#####.", "e") etc... return render(request, 'decrypted.html') So the text does not appear at all on the page. <html lang="en"> <head> <meta charset="UTF-8"> <title>yCrypt</title> </head> <body> TEXT DECRYPTION: {{ftext}} </body> </html> I wonder why it shows no code issues whatsoever. Maybe there is a simplier way to make this possible? -
Django signals doesnt receive any signals (doesnt work)
Here is my code : models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.utils import timezone GENDER = ( ("MALE", "Male"), ("FEMALE", "Female"), ) class UserManager(BaseUserManager): def create_user(self, email, username, password=None, is_active=True, is_staff=False, is_superuser=False): # , **extra_fields if not email: raise ValueError('Users must have email address') if not username: raise ValueError('Users must have username') if not password: raise ValueError('Users must have password') # Normalize example: Test@gmail.com ---> test@gmail.com email = self.normalize_email(email) user = self.model(email=email, username=username, date_joined=timezone.now()) # , **extra_fields user.is_staff = is_staff user.is_superuser = is_superuser user.set_password(password) user.save() return user # Called when we run python manage.py createsuperuser def create_superuser(self, username, email, password=None): user = self.create_user(email, username, password, is_staff=True, is_superuser=True) return user # Abstract Base User will give three fields by default (id, password, last_login) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, unique=True, blank=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) objects = UserManager() # USERNAME_FIELD and password are required to login USERNAME_FIELD = 'email' # REQUIRED_FIELD is a list of the field names that will be prompted # for when creating a user via the createsuperuser management command REQUIRED_FIELDS = ['username'] def __str__(self): return self.email class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) … -
How to get the difference in seconds between two datetime fields in Django template?
Minutes is the smallest unit used in Django tags timesince and timeuntil, not sure how to get the difference in seconds between two datetime fields. For example, it is 11 seconds between 2021-10-24 15:11:22 and 2021-10-24 15:11:33. -
Django no such table
In the development environment of a new Django project I have 2 apps and I am was running into issues of "no column named" exceptions. I ended up deleting the sqlite db and retried python manage.py makemigrations and pyhon manage.py migrate now I run into a new exception of no table exits. I can verify from the sqlite model that the table do not exits, but I did not receive any errors after deleting the database and rerun python manage.py makemigrations and python manage.py migrate In models.py for my products app from django.db import models from django.db.models.fields import CharField from instructions.models import Instruction # Create your models here. class Product(models.Model): productName = models.CharField(max_length=200) productDescription = models.TextField(blank=True) productPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0) productSubQuantity = models.IntegerField(default=1, blank=False) productAvailable = models.BooleanField(default = True) productCreated_at = models.DateTimeField(auto_now_add = True) productUpdated_at = models.DateTimeField(auto_now = True) productSlug = models.SlugField(max_length = 255, unique = True, help_text = "Unique text for url created from product name") productMetaKeywords = models.CharField("Meta keywords for SEO", max_length = 255, help_text ="Comma delimited words for SEO") productMetaDescription = models.CharField("Meta description", max_length = 255, help_text="Content for meta tag description") instruction = models.ForeignKey(Instruction, on_delete = models.CASCADE, related_name = "instruction") class Meta: db_table = 'products' ordering … -
New Django, SQL user here: How do I reference my database objects in code in Django?
I know there are tons of resources online to figure this out, but I feel like the situation with my models is very weird, and I know the syntax can get very messy, so I'm just not sure what to do. So I am creating software for an ice cream company to track their inventory. My models look like this: class sizeCounts (models.Model): class Meta: verbose_name = "Size Count" verbose_name_plural = "Size Counts" #Just to label a collection of sizes with the corresponding flavor so it's not confusing! item_Flavor_Choices = [('CHOCOLATE','chocolate'),('VANILLA', 'vanilla'),('COOKIESNCREME', 'cookiesncreme'), ('STRAWBERRY', 'strawberry')] item_Flavor = models.CharField(max_length=100, choices = item_Flavor_Choices, default='chocolate') half_Pint_Count = models.IntegerField(default=30) one_Quart_Count = models.IntegerField(default=30) pint_Count = models.IntegerField(default=30) half_Gallon_Count = models.IntegerField(default=30) gallon_Count = models.IntegerField(default=30) def __str__(self): return 'Half Pint: %s, Quart: %s, Pint: %s, Half Gallon: %s, Gallon: %s' % (self.half_Pint_Count, self.one_Quart_Count, self.pint_Count, self.half_Gallon_Count, self.gallon_Count) class item (models.Model): class Meta: verbose_name = "Item" verbose_name_plural = "Items" item_Flavor_Choices = [('CHOCOLATE','chocolate'),('VANILLA', 'vanilla'),('COOKIESNCREME', 'cookiesncreme'), ('STRAWBERRY', 'strawberry')] item_Flavor = models.CharField(max_length=100, choices = item_Flavor_Choices) size_Counts = models.ForeignKey(sizeCounts, on_delete=models.CASCADE, default = None) def __str__(self): return self.item_Flavor As you can see, I have an item model and a sizeCounts model. An item has a flavor and a set amount of quantity for each size … -
I'm trying to use django channels but it keeps throwing error
im trying to implement django channels app in my django project.but whenever I put channels app in my django settings.py installed app it throws an error as bellow Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "E:\sunil_sachin\SSMOS_env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "E:\sunil_sachin\SSMOS_env\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "E:\sunil_sachin\SSMOS_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "E:\sunil_sachin\SSMOS_env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "E:\sunil_sachin\SSMOS_env\lib\site-packages\django\apps\config.py", line 124, in create mod = import_module(mod_path) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "E:\sunil_sachin\SSMOS_env\lib\site-packages\channels\apps.py", line 4, in <module> import daphne.server File "E:\sunil_sachin\SSMOS_env\lib\site-packages\daphne\server.py", line 5, in <module> from twisted.internet import asyncioreactor # isort:skip File "E:\sunil_sachin\SSMOS_env\lib\site-packages\twisted\internet\asyncioreactor.py", line 16, in <module> from twisted.logger import Logger File "E:\sunil_sachin\SSMOS_env\lib\site-packages\twisted\logger\__init__.py", line 105, in <module> from ._logger import Logger, _loggerFor File "E:\sunil_sachin\SSMOS_env\lib\site-packages\twisted\logger\_logger.py", line 269, in <module> _log = Logger() File "E:\sunil_sachin\SSMOS_env\lib\site-packages\twisted\logger\_logger.py", line 65, in __init__ from ._global import globalLogPublisher File "E:\sunil_sachin\SSMOS_env\lib\site-packages\twisted\logger\_global.py", line 17, in <module> from ._buffer import …