Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to annotate the age of a person based on their date of birth - Django
I am trying to annotate a simple Person object with both the users date of birth and their age to keep the data normalised. I am wishing to later perform some filtering with this annotation so a model property will not work. I have found this blog article (last example) which seems to state what I'm wanting to do is possible, however whenever I actually execute this age is always None I am unsure what is going wrong here, logically it looks sound to me.. models.py class Person(AbstractUser): email = models.EmailField(unique=True) date_of_birth = models.DateTimeField(default=date.today()) views.py class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer permission_classes = [permissions.IsAdminUser] def get_queryset(self): queryset = self.queryset.annotate( age = ExpressionWrapper( ExtractDay( ExpressionWrapper( Value(datetime.now()) - F("date_of_birth"), output_field=DateField(), ) ) / 365.25, output_field=IntegerField(), ) ) return queryset -
Deploy Django Project on Hostgator shared hosting
I am currently delving into the world of Django and have aspirations to bring my small project to fruition by deploying it. I have secured a cloud hosting plan with Hostgator for one year, which is a shared hosting option. Although my budget is currently limiting me from utilizing more advanced hosting solutions such as AWS or DigitalOcean. I reached out to Hostgator's customer support team for guidance, but was informed that while they could assist me with deploying the app on the server, they would not be able to provide further support. As a novice, I am still on the hunt for resources that can guide me through the deployment process in a comprehensive manner. I would be immensely grateful for a roadmap that can guide me through this process and any recommendations for online resources that are tailored for beginners such as myself, who are eager to learn. Thanks -
Dynamic url rendered by Django as an api response, but not by frontend
I'm using Django + Angular, and I have a dynamic url which works for first time when load my product page. I specified as a dynamic url in Django too, so the url look like this "product/home/:productName/:productId". Everything definitely works but as a response when I reload my page, it gets plain API response from Django and the host is changed to the backend one. Why it's happening? I was searching around didn't found anything. url.py path('product/home/<str:handle>/<int:id>', ProductGet) view.py @csrf_exempt def ProductGet(request, handle, id): product = Product.objects.get(id=id) serializer = ProductSerializer(product, many=False) return JsonResponse(serializer.data, safe=False) So, this code works for first time, but then when I reload seems it changes host to Django and I'm getting as a response, my API response. -
Error when using comment form on website: (1048, "Column 'comment_post_id' cannot be null")
I'm trying to implement a comment section below each blog on my site. I've got the form rendering but when I try to post a comment I get the following error: (1048, "Column 'comment_post_id' cannot be null") I cannot see what I'm doing wrong, I've also followed a tutorial step by step, although it is 2 years old. here's my code: sorry if I missed any, please ask if you require more. models.py: class BlogPost(models.Model): blog_title = models.CharField(max_length=100, null=False, blank=False, default="") blog_article = RichTextUploadingField(null=True, blank=True, default="ici") blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") blog_date = models.DateField(auto_now_add=True) blog_published = models.BooleanField(default=False) blog_featured = models.BooleanField(default=False) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.blog_title) super().save(*args, **kwargs) def __str__(self): return self.blog_title class blogComment(models.Model, ): comment_post = models.ForeignKey(BlogPost, related_name="comments", on_delete=models.CASCADE) comment_name = models.CharField(max_length=100) comment_text = models.TextField(max_length=1000) comment_date = models.DateTimeField(auto_now_add=True) comment_status = models.BooleanField(default=True) class Meta: ordering = ("comment_date",) def __str__(self): return '%s -- Name: %s'%(self.comment_post.blog_title, self.comment_name) views.py: def viewBlog(request, slug): try: blog = BlogPost.objects.get(slug=slug) except BlogPost.DoesNotExist: print("ViewBlog with this slug does not exist") blog = None comments = blog.comments.filter(comment_status=True) user_comment = None if request.method == 'POST': comment_form = commentForm(request.POST) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.blog = blog user_comment.save() return HttpResponseRedirect('/' + blog.slug) else: comment_form … -
Django - BaseSerializer.is_valid() takes 1 positional argument but 2 were given
This project was working before, but then Heroku took away free tier so I have been trying to deploy somewhere else, but now all of a sudden I cannot even create a user locally even though I could before... Now when I create a user I get the error mentioned in the title. serializers folder common.py file from xml.dom import ValidationErr from rest_framework import serializers from django.contrib.auth import get_user_model, password_validation from django.contrib.auth.hashers import make_password User = get_user_model() class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) confirm_password = serializers.CharField(write_only=True) def validate(self, data): password = data.pop('password') confirm_password = data.pop('confirm_password') if password != confirm_password: raise ValidationErr({ 'confirm_password': 'Does not match the password'}) password_validation.validate_password(password) data['password'] = make_password(password) return data class Meta: model = User fields = ('id', 'username', 'email', 'password', 'confirm_password') views.py file from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.exceptions import PermissionDenied from django.contrib.auth import get_user_model import jwt User = get_user_model() from datetime import datetime, timedelta from jwt_auth.serializers.common import UserSerializer from django.conf import settings class RegisterView(APIView): def post (self, request): create_user = UserSerializer(data=request.data) try: create_user.is_valid(True) create_user.save() return Response(create_user.data, status=status.HTTP_201_CREATED) except Exception as e: print(str(e)) return Response(e.__dict__ if e.__dict__ else str(e), status=status.HTTP_422_UNPROCESSABLE_ENTITY) class LoginView(APIView): def post(self, request): password = request.data.get('password') username … -
UnicodeEncodeError: 'charmap' codec can't encode character DJANGO
I am getting this error: UnicodeEncodeError: 'charmap' codec can't encode character '\u064f' in position 3583: character maps to <undefined> while running command: python manage.py makemessages -all can anybody help me what's wrong here? run : py manage.py makemessages -all then it should add all strings which are calling _() method should be added to .po file. -
Django TemplateDoesNotExist error - wrong path to templates folder
I am currently watching the Django lecture from CS50W and was coding along with Brian just fine. But now I keep getting the same error no matter what I do. I want to render the simple HTML5 page with Django and even though I have specified the correct path to the templates folder and index.html. from Django.shortcuts import render from datetime import datetime # Create your views here. def index(request): now = datetime.now() return render(request, 'newyear/index.html', { 'newyear': now.month == 1 and now.day == 1 }) And I get an error as stated below Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.app_directories.Loader: /home/gaba/cs50w/week3-Django/lecture3/hello/templates/newyear/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /usr/local/lib/python3.10/dist-packages/django/contrib/admin/templates/newyear/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /usr/local/lib/python3.10/dist-packages/django/contrib/auth/templates/newyear/index.html (Source does not exist) Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/usr/local/lib/python3.10/dist-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gaba/cs50w/week3-Django/lecture3/newyear/views.py", line 8, in index return render(request, 'newyear/index.html', { File "/usr/local/lib/python3.10/dist-packages/django/shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "/usr/local/lib/python3.10/dist-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/usr/local/lib/python3.10/dist-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) Exception Type: TemplateDoesNotExist at /newyear/ … -
How to call a function in django view.py
I need to call the function get_context_data in my VacanciesView. Code views.py: def VacanciesView(request): navigate_results = Navigate.objects.all() context_vac = { 'navigate_results': navigate_results} get_context_data(self, **kwargs) return render(request, 'main/vacancies.html', context_vac) def get_context_data(self, **kwargs): context = super(VacanciesView, self).get_context_data(**kwargs) context['vacancies'] = sorted(get_vacancies(), key=lambda item: item["published_at"][:10]) return context I try to do it by get_context_data(self, **kwargs), but it takes: name 'self' is not defined -
I want to integrate LDAP authentication in Django, but missing some configuration I guess
I want to integrate LDAP authentication in Django, but even authentication is not happening i.e even after providing the correct LDAP credentials the user details in the Django admin panel the user details are not getting stored in the Django user model. Here's my setttings.py file in Django AUTH_LDAP_SERVER_URI = 'ldaps://xxxxxx:636' AUTH_LDAP_BIND_DN = 'CN=xxxxx,OU=Service,OU=Accounts,OU=SF_SAP,DC=sf,DC=priv' AUTH_LDAP_BIND_PASSWORD = 'xxxxxxxx' AUTH_LDAP_USER_SEARCH = LDAPSearch('OU=User,OU=Accounts,OU=SF_SAP, DC=sf,DC=priv',ldap.SCOPE_SUBTREE, '(CN=%(user)s)') AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", "username": "uid", "password": "userPassword", } AUTH_LDAP_PROFILE_ATTR_MAP = { "home_directory": "homeDirectory" } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_CACHE_TIMEOUT = 3600 AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) Can someone please point out what am I missing? -
Zabbix events.api giving HTTP Error 500: Internal Server Error in django for selected time range
I am new to usage of zabbix api. I am trying to fetch the events using zabbix events.get() api in postman as below I am pretty sure this is correct, because I am getting values for other time range except this range i.e October 1st to 31st. Any idea? -
Set Extra Fields In Django Generic Many to Many Relationship
Wondering how I could set a generic many to many relationship including additional fields through a post request. Note that I removed some irrelevant fields to make it easier to read. I have only included one of the objects (message) that can have these labels for simplicity. Models class Message(models.Model): text = models.CharField(max_length=250, default='text') labels = GenericRelation(to=Label) class Tag(models.Model): color = serializers.Charfield() class Label(models.Model): tag = models.ForeignKey(to=Tag, on_delete=models.CASCADE) # Generic foreign key object_id = models.PositiveIntegerField() content_type = models.ForeignKey(to=ContentType, on_delete=models.CASCADE) content_object = GenericForeignKey() confidence = models.IntegerField() section = models.IntegerField() class Meta: indexes = [ models.Index(fields=["content_type", "object_id"]), ] Serializers class LabelSerializer(ModelSerializer): class Meta: model = Label fields = ['id', 'confidence', 'level'] class MessageSerializer(serializers.ModelSerializer): labels = serializers.ManyRelatedField( child_relation=LabelSerializer(), required=False) class Meta: model = Message fields = ['id', 'text', 'labels'] The idea would be to have the following post request which would set the relationship between tags and messages, using the custom through table Labels with the additional fields confidence and section set. { 'text': 'Message Text', 'labels': [ { 'tag': 1, 'confidence': 0.9, 'section': 1 }, { 'tag': 2, 'confidence': 0.7, 'section': 1 } ] } -
Can't install whitenoises library on my django project
I am using the conda environment and I cannot load the white noise library, but it says that the library is installed. enter image description here enter image description here[[[[enter image description here](https://i.stack.imgur.com/QcVTw.png)](https://i.stack.imgur.com/PXIy9.png)](https://i.stack.imgur.com/6qMSC.png)](https://i.stack.imgur.com/TNOYx.png) I try all, but i can't fix this error -
Django-filters resets after using the UpdateView
I have a Model with a lot of entries, so I'm using django-filters to filter the model, I initially load an empty table and from there I use the filter to view the items. Everything works fine, the page loads initially with no entry, after I filter, django shows the correct items. The Url gets a parameter: /retetabloc/?acordcadru=532(532 is the filter) but when I try to update an entry, the filter resets(the parameter is still in the URL) and the whole db is loaded. I don't quite understand how to pass the filter parameter to the RetetaBlocUpdate, so that after the update is done it returns to the filtered items like in the ListView. views.py class RetetaBlocListview(LoginRequiredMixin, CoreListView): model = RetetaBloc def get_queryset(self, *args, **kwargs): pdb.set_trace() acordcadru = self.request.GET.get("acordcadru") queryset = RetetaBloc.objects.filter(acordcadru=acordcadru) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = RetetaBlocFilter(self.request.GET, queryset=self.get_queryset()) pdb.set_trace() return context class RetetaBlocUpdate(LoginRequiredMixin, AjaxUpdateView): model = RetetaBloc form_class = RetetaBlocForm Thank you. -
Django throws an error: LookupError: No installed app with label 'admin'
Today after installing django-cryptography for encrypting all fields in my models using this website, this error is keep showing on my terminal after running python manage.py runserver: File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\urls\resolvers.py", line 494, in check for pattern in self.url_patterns: File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\ADAMUDEE\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\ADAMUDEE\Desktop\school\project\school\urls.py", line 23, in <module> path('admin/', admin.site.urls), File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\utils\functional.py", line 266, in inner self._setup() File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\contrib\admin\sites.py", line 595, in _setup AdminSiteClass = import_string(apps.get_app_config("admin").default_site) File "C:\Users\ADAMUDEE\Desktop\school\myv\lib\site-packages\django\apps\registry.py", line 165, in get_app_config raise LookupError(message) LookupError: No installed app with label 'admin'. I try to solve it using these answer in this question, but no one works, I also deleted sqlite in my project folder … -
How to get different names in request.post method
I got a problem, I'm making a web for SQLServer Agent Jobs execution, where if my job got parameters it redirects me to another page where I can enter my parameters. My problme is submiting these parameters. I don't know how to send all the parameters from my html to my view.py. All inputs have different names and I really don't know how to make the request accept different input names. I'll add some code below. IM commenting the line where I have the problem parameters.html <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{% block title %} Parametros {% endblock %}</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> </head> <div class="container"> <div class="row"> <div class="col-md-4 offset-md-4"> <br><br> <div class="card"> <div class="card-header"> <h3>Parámetros</h3> </div> <div class="card-body"> <form method="post"> {% csrf_token %} {% for i in parameters %} <!-- Parameters input --> <div class="form-outline mb-4"> <label class="form-label" for="form2Example1">{{ i.parameter_name }}</label> {% if i.parameter_type == 'Int' %} <input type="number" id="form2Example1" class="form-control" name="int" /> {% else %} {% if i.parameter_type == 'Decimal' %} <input type="text" id="form2Example1" class="form-control" name="decimal" /> {% else %} {% if i.parameter_type == 'String' %} <input type="text" id="form2Example1" class="form-control" name="string" /> {% else %} {% if i.parameter_type == 'Date' %} <input type="date" id="form2Example1" … -
Django filter with Q objects not working or I am doing it wrong
I have this view to check if two users are friends and in this case they are because the logged in user and the author of the blog are indeed friends BUT the model for friendship only works one way and I need to make provision for that, which is why I wrote this function. After all if user1 is friends with user2 then automatically user2 is friends with user1: The friendship model: class Friendship(models.Model): person = models.ForeignKey( User, on_delete=models.CASCADE, related_name="person" ) friend = models.ForeignKey( User, on_delete=models.CASCADE, related_name="friend" ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") The serializer method: def get_friends(self, obj): loggedUser = self.context.get('view').kwargs.get('user') post_author = obj.user_id friends = Friendship.objects.filter(Q(person=loggedUser), Q(friend=post_author) | Q(person=post_author), Q(friend=loggedUser)) if friends: return True else: return False Please tell me what I am doing wrong cause it says they are not friends even though they are? -
Using CSV file in Django choices
I have this function that calls the choices and activates them in each Model, however, I would like to know if there is a way to use this CSV file automatically, without having to call it item by item... def Equipe(): with open("controle_pav/static/texto/equipes.csv", 'r') as arquivo: equipes = arquivo.read() EQUIPE = ( ('equipes', equipes.split()[0]), ('equipes', equipes.split()[1]), ('equipes', equipes.split()[2]), ) return EQUIPE Is there a way to use an iterator or something like that. ? I tried to make a router with the for but I was not successful -
In Django I am getting an Integrity Error while testing to create an object
In my Django REST API project I am getting an Integrity Error when I run my tests. models.py class Tag(models.Model): """Tag for filtering recipes.""" name = models.CharField(max_length=255) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.name And here is my test that fails: def test_create_tag(self): user = get_user_model().objects.create_user(email="user@example.com",password="password123") tag = models.Tag.objects.create(user=user, name="Tag1") self.assertEqual(str(tag), tag.name) This is the error that I have been getting: Traceback (most recent call last): File "/app/core/tests/test_models.py", line 80, in test_create_tag tag = models.Tag.objects.create(user=user, name="Tag1") django.db.utils.IntegrityError: null value in column "user_id" of relation "core_tag" violates not-null constraint DETAIL: Failing row contains (1, Tag1, null). Why while this test running creates an error? -
How do I ensure that a Foreignkey field is always referenced in a Django model?
I was thinking of creating an instance of a foreignkey field and referring it every time an instance of a model is created, but I didn't find any solution for this. Usually we need to create a model of foreignkey type and then refer to it from the model, but I want it to automatically create one foreignkey instance from the beginning of and always refer to it. To provide an example let's say we've 2 model fields called User and WeeklySchedule. Everytime an instance of a User is created,another corresponding instance of a WeeklySchedule model is also created that will be referred to by the instance of the User. -
djongo query_set with filter on boolean field
I have a django application with djongo as a database driver. My model is simple: from django.db import models from djongo.models import ObjectIdField class TmpModel(models.Model): _id = ObjectIdField() is_deleted = models.BooleanField(default=False) When I run in shell simple filter command: >>> TmpModel().save() >>> TmpModel(is_deleted=True).save() >>> TmpModel.objects.filter(is_deleted=False).all() I got an error: (0.000) QUERY = 'SELECT "solutions_tmpmodel"."_id", "solutions_tmpmodel"."is_deleted" FROM "solutions_tmpmodel" WHERE NOT "solutions_tmpmodel"."is_deleted" LIMIT 21' - PARAMS = (); args=(); alias=default Traceback (most recent call last): File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 933, in _select return SelectQuery(self.db, self.connection_properties, sm, self._params) File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 116, in __init__ super().__init__(*args) File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__ self.parse() File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 152, in parse self.where = WhereConverter(self, statement) File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\converters.py", line 27, in __init__ self.parse() File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\converters.py", line 119, in parse self.op = WhereOp( File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\operators.py", line 476, in __init__ self.evaluate() File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\operators.py", line 465, in evaluate op.evaluate() File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\operators.py", line 258, in evaluate self.rhs.negate() AttributeError: 'NoneType' object has no attribute 'negate' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__ self._query = self.parse() File "C:\Users\user\AppData\Local\pypoetry\Cache\virtualenvs\test-task-YJIxAxLW-py3.10\lib\site-packages\djongo\sql2mongo\query.py", line 885, in … -
Filtering in DJANGO with OR condition
I have a restfull API created with Django and DRF. When I try to filter with OR condition (), it doesn't detect the condition and return all the objects. I want to make it work by a diferent way other than modifying the "get_queryset" method. I want to find the way to implement some module or backend filter package to implement that filters -
Python Django functions
I tried everything, why my 'POST request' from 'send' function isn't considered in the 'checkview' function ? def send(request): room = request.POST['room_name'] #YAHOO API import yfinance as yf aapl = yf.Ticker(room) ainfo = aapl.history(period='1y') #Plot the Chart import plotly.graph_objects as go fig = go.Figure(data=go.Scatter(x=ainfo.index,y=ainfo.Close, mode='lines')) #x = fig.show() #DB inject plot rx = str(randint(9999,99999)) fig.write_image("/Users/Xlibidish/Desktop/Django/static/"+room+rx+".png") #DB Inject from send plot_id = str(room+rx) new_message = Message.objects.create(room=plot_id) new_message.save() return HttpResponse('All Good in send') def checkview(self): send(self) chart_id = Message.objects.get(room=plot_id) return JsonResponse(chart_id.room, safe=False) Here is the error: django.utils.datastructures.MultiValueDictKeyError: 'room_name' I ultimately need to transfer through AJAX the plot_id variable. -
How to make each product have functioning plus minus button on my product page and add its price to the total amount?
I'm working on Ecommerce Website that sells Coffee and my problem is that the only working plus and minus button is the first coffee. The plus and minus buttons on the others are not functioning. Is it about the for statement where I'm wrong? or the structure of the html isn't right. I've copied some of the code on cart.html file to make the product page had the option of adding products to the cart and also has a proceed button to the checkout page. The before structure of the site was you click on the image of a product and directed to the addtocart page then to the checkout page. -
Django test factory post with foreign key
I'm trying to test a view-function with django's RequestFactory's post-method. The view-function should create a new ObjA-instance. ObjA has a foreign key field to an ObjB. My test currently looks like this (names changed for better reading): request = self.factory.post('/create-objA/', data={'objB': objB.id, 'field1': 'dummy'}) request.user = self.user request.POST.is_bound = True create_objA(request) self.assertTrue(ObjA.objects.filter(field1='dummy').exists()) objB does exist, this is tested few lines before in the same test function. However the test in the snippet fails. The reason is that in the following create function form.is_valid() is never true: def create_objA(request): if request.method == 'POST': form = ObjAFormCreate(request.POST) if form.is_valid(): .... So the ObjA is not created. Form is not valid because it has an error in the ObjB reference field: Select a valid choice. That choice is not one of the available choices. though objB.id is inside form.data. Question: How should I write the test, so that the form would not have the error? Model: class ObjA(models.Model): id = models.BigAutoField(primary_key=True) obj_b_id = models.ForeignKey(ObjB, on_delete=models.CASCADE) field1 = models.CharField(max_length=10) Form: class ObjAFormCreate(ModelForm): objB = forms.ModelChoiceField(queryset=ObjB.objects.all()) field1 = forms.CharField(max_length=10) -
How can I redirect the user to the form page while keeping some data from the previous page
I am trying to allow customers to place an order for a specific product on my website, and I want to create a button for each product that contain the product's unique id so that I can associate the order with the correct product in admin dashboard. how can I do this? i have displayed the products and i did the order form this is the code I have : models.py: from email.policy import default from unicodedata import name from django.db import models class Product(models.Model): name = models.CharField(max_length=10, null=True) price = models.DecimalField(max_digits=6, decimal_places=0,null=True) description = models.TextField(null=True) image = models.ImageField(upload_to='photos',null=True) productid = models.CharField(max_length=10, null=True) def __str__(self): return self.name class Order(models.Model): product = models.OneToOneField(Product , on_delete=models.PROTECT , null=True) fullname = models.CharField(max_length=10, null=True) phone= models.CharField(max_length=10, null=True) address = models.CharField(max_length=10, null=True) date = models.DateField(blank=True , null=True) views.py: def order(request): name = request.POST.get('name') phone = request.POST.get('phone') address = request.POST.get('address') date = request.POST.get('date') orderdata = Order(fullname = name , phone = phone , address = address , date = date) orderdata.save() return render(request,'order.html') def products(request): products = Product.objects.all() return render(request, 'products.html', {'products':products}) order.html: <section class="content" id="content" name="content"> <div class="row"> <div class="col-75"> <div class="container"> <form method="post"> {% csrf_token %} <div class="row"> <div class="col-50"> <h3>Enter your details</h3> <label …