Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FieldError django
Please I need help, I dont know where the problem is coming from, please see the code below @api_view(['GET']) @permission_classes([IsAuthenticated]) def post_feed_view(request, *args, **kwargs): user = request.user profiles = user.follow_user.all() followed_users_id = [] if profiles.exists(): followed_users_id = [x.user.id for x in profiles] followed_users_id.append(user.id) queryset = Post.objects.filter(user__id__in=followed_users_id).order_by("-date_posted") serializer = PostSerializer(queryset, many=True) return Response(serializer.data, status=200) I keep getting this error: Cannot resolve keyword 'user' into field. Choices are: author, author_id, although, in my models, I dont have "User" what I have is "Author". But I dont know where exactly to put in author. I think my problem is that i dont fully understand "request.user". Please help!. =========== This is the Profile and Follow models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=245, null=True) image = models.ImageField(default='default.png', upload_to='profile_pics') interests = models.ManyToManyField(Category, related_name='interests_user') stripe_customer_id = models.CharField(max_length=50, blank=True, null=True) one_click_purchasing = models.BooleanField(default=False) is_vendor = models.BooleanField(default=False) # vendor bvn = models.CharField(max_length=10, null=True, blank=True) description = models.TextField(null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) company = models.CharField(max_length=100, null=True, blank=True) # follow_user = models.ManyToManyField('users.Follow') def __str__(self): return f'{self.user.username} Profile' @property def followers(self): return Follow.objects.filter(follow_user=self.user).count() @property def following(self): return Follow.objects.filter(user=self.user).count() def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size … -
How to modify Bootstrap 4 form validation information presentation in Django?
I am using Django and Bootstrap 4. I want to customize the way form validation information is displayed in a template I am using. When an error occurs in the current template, the invalid input element has a red outline and the error message is displayed as a pop-up. Also, the input elements that have been inputted correctly don't have a green outline, they just remain without an outline. I'd like to do the following: display the error message underneath the field when an error occurs give the green outline to the fields whose input is correct I tried multiple solutions, including: this tutorial this GitHub gist the Stack Overflow answers from this question None worked from my case. My current code: submit_job_listing.html (the template): {% extends "base.html" %} {% block title %} Submit a job {% endblock %} {% block nav_item_post_a_job %}active{% endblock nav_item_post_a_job %} {% block head %} {{ job_listing_form.media.css }} {% endblock %} {% block content %} <h1>Submit a job listing</h1> <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="row text-center"> <h2> <b>Job listing information</b> </h2> </div> <br/> {% for field in job_listing_form.visible_fields %} <div class="form-group"> <div class="row"> <p>{{ field.label_tag }}</p> </div> <div class="row"> {% if … -
Django graphen Create Mution fireing Error
These are my schmema import graphene from graphene import relay, ObjectType, Mutation from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from cookbook.models import Ingredient class IngredientType(DjangoObjectType): class Meta: model = Ingredient class IngredientCreate(Mutation): class Arguments: name = graphene.String(required=True) note = graphene.String(required=True) id = graphene.ID() ingredient = graphene.Field(IngredientType) @classmethod def mutate(cls, root, info, name, note, id): ingredient = IngredientType.objects.create( name = name, note = note ) return IngredientCreate(ingredient=ingredient) class Query(graphene.ObjectType): create_ingredient = IngredientCreate.Field() and this is my models. class Ingredient(models.Model): name = models.CharField(max_length=100) notes = models.TextField() I am trying to create Ingredient from graphql django gui but fires me syntax error { createIngredient( name: 'rice cooking', note: 'a simple note', ) } Can anyone tell me please what is the possible reasone that i cant create a record? -
Django/Pillow ImageField - image not showing
I am trying to follow along to a Codemy Youtube tutorial and I am not having the same results. I want to display an image on a Django website. I have installed Pillow correctly and followed the tutorial step by step but I am only getting a broken image icon on the webpage. Copied image url from broken img icon - http://127.0.0.1:8000/media/images/MX1A1063.JPG [1]: https://i.stack.imgur.com/51HgB.png - settings.py [2]: https://i.stack.imgur.com/bMy0F.png - Broken img icon [3]: https://i.stack.imgur.com/gg55Z.png - forms.py [4]: https://i.stack.imgur.com/AYeGm.png - terminal window [5]: https://i.stack.imgur.com/3UhvU.png - pip freeze [6]: https://i.stack.imgur.com/5QzGR.png - models.py [7]: https://i.stack.imgur.com/PKHxF.png - product_detail.html [8]: https://i.stack.imgur.com/EyzDy.png - images folder in main src folder Tutorial - https://www.youtube.com/watch?v=ygzGr51dbsY&ab_channel=Codemy.com -
how can i get all attribute data from ManyToMany field Django?
i want to get all attribute data of articles in SetRundown forms like title, category, author via ManyToManyfield i want to show all article in Rundown form with title category and author name can anybody know how can i do this...? if i run my code with {% render_field form.articles %} then it will show the all articles title but i want the category and author name too with titles.... models.py class Article(models.Model): title = models.CharField(max_length=300, help_text="Short title") category = models.ForeignKey(Category, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) class SetRundown(models.Model): pool_title = models.CharField(max_length=200) articles = models.ManyToManyField(Article) forms.py from django import forms class SetRundownForm(forms.ModelForm): class Meta: model = SetRundown fields = ['pool_title', 'time_pool', 'articles'] def __init__(self, *args, **kwargs): super(SetRundownForm, self).__init__(*args, **kwargs) self.fields['articles'].queryset = Article.objects.filter(story_status='fr') create_form.html <form method="POST">{% csrf_token %} {% render_field form.pool_title type="text" %} {% render_field form.time_pool type="menu" %} {% for article in form.articles %} {{ article.title }} {{ article.category }} {{ article.author.username }} {% endfor %} <button class="btn btn-secondary" type="submit">Submit</button> </form> {% endblock %} -
How can I create model instances in a .py file?
So when I create a model instance using the CLI, it works. The model: class Post(models.Model): title = models.CharField(max_length=100) cover = models.ImageField(upload_to='images/') description = models.TextField(blank=True) def __str__(self): return self.title Then I did: $ python manage.py shell >>>from blog.models import Post >>>filename = 'images/s.png' >>>Post.objects.create(title=filename.split('/')[-1], cover=filename, description='testing') And it worked, it showed up on the page that I'm displaying these models at. However, when I take this same code and put it in a file, portfolio_sync.py, it doesn't work. from blog.models import Post filename = 'images/s.png' Post.objects.create(title=filename.split('/')[-1], cover=filename, description='testing') I get this error: Traceback (most recent call last): File "portolio_sync.py", line 1, in <module> from models import Post File "/Users/rfrigo/dev/ryanfrigo/blog/models.py", line 4, in <module> class Post(models.Model): File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/db/models/base.py", line 87, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 249, in get_containing_app_config self.check_apps_ready() File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 131, in check_apps_ready settings.INSTALLED_APPS File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 42, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. How can I fix this, and create a model instance in a .py file? (Because I need to loop through a bunch of … -
Calculate File upload time on server
I want to calculate how much time a particular encryption algorithm takes while uploading files on the server. I have used time.process_time() , time.time() like function to calculate the time taken by Encryption algorithm,but they are giving inaccurate values on server. start_time = time.process_time() encryption_algo() toatl_time = time.process_time() - start_time The output on the local machine is accurate but on the server, it's not. Ex:- if 6.00s on local then it is like 0.444s on a server, So how can I effectively calculate the time taken to encrypt file? -
I want to make virtual payment method but its not working
i am trying to make a system where customer can buy with thier coin.I have already assigned some coin to make purchase but its not workin.Actually i am trying to substract with the product price and account balance but its not working.For this i made a post method: view.py: def post(self, request, *args, **kwargs): ids = list(request.session.get('cart').keys()) cart_products = Product.get_products_id(ids) product_prices = list(map(self.map_func, cart_products)) total_due = sum(product_prices) balance = request.session['customer']['coin'] if balance >= total_due: balance = balance - total_due print(balance) # Customer.objects.filter(id = request.session['customer']['id']).update(coin=balance) customer = Customer.objects.get(id = request.session['customer']['id']) customer.coin = balance customer.save() # request.session['customer']['coin'] = balance return HttpResponse(balance) return HttpResponse("Failed") Here is my index {% extends 'Home/header.html' %} {% load cart %} {% block content %} {{user_orders.product.name}} {{user_orders.product.price}} {{total_due}} <form action="" method="POST"> {% csrf_token %} <input type="submit" name="payment_coin"> </form> {{request.session.customer}} {% endblock %} I dont know why its not working well. I got stuck here please help -
How to clean a list in a template
I am currently working on my first website. Which is a rna to a protein translator. What it does is you input a dna chain and it translates it into a protein. However, when i get the protein, it appears like this: As you can see, the protein isn't cleaned, which means that instead of appearing as Isoleucine, glycine; it appears as ['Isoleucine','Glycine'] Here's the code for that: (my guess is there's a problem in the output part) class TranslatorView(View): template_name = 'main/translated.html' rna_mapper = { "a": "u", "t": "a", "c": "g", "g": "c" } amino_mapper={ "aat": "Asparagine", "aac": "Asparagine", "aaa": "Lysine", "aag": "Lysine", "act": "Threonine", "acc": "Threonine", "aca": "Threonine", "acg": "Threonine", "agt": "Serine", "agc": "Serine", "aga": "Arginine", "agg": "Arginine", "att": "Isoleucine", "atc": "Isoleucine", "ata": "Isoleucine", "atg": "Methionine", "cat": "Histidine", "cac": "Histidine", "caa": "Glutamine", "cag": "Glutamine", "cct": "Proline", "ccc": "Proline", "cca": "Proline", "ccg": "Proline", "cgt": "Arginine", "cgc": "Arginine", "cga": "Arginine", "cgg": "Arginine", "ctt": "Leucine", "ctc": "Leucine", "cta": "Leucine", "ctg": "Leucine", "gat": "Aspartic", "gac": "Aspartic", "gaa": "Glutamic", "gag": "Glutamic", "gct": "Alanine", "gcc": "Alanine", "gca": "Alanine", "gcg": "Alanine", "ggt": "Glycine", "ggc": "Glycine", "gga": "Glycine", "ggg": "Glycine", "gtt": "Valine", "gtc": "Valine", "gta": "Valine", "gtg": "Valine", "tat": "Tyrosine", "tac": "Tyrosine", "taa": "Stop", "tag": "Stop", … -
Django delete item from popup window
I want to delete specific order from my popup window in django. So my urlpatterns is something like [I guess I have something wrong here] in url.py: urlpatterns = [ path('panel', views.home, name='panel'), path('panel/profile/<str:customer_username>', views.profile, name='profile'), path('<str:order_id>', views.deleteOrder, name='delete_order'), ] and in view.py I have a function for deleting specific order: def deleteOrder(request, order_id): order_item = Order.objects.get(id=order_id) print(order_item) if request.method == 'POST': order_item.delete() return redirect('') context = {'order_item': order_item} return render(request, '', context) And finally in URL [each user profile page] localhost:8000/panel/profile/testuser I have: <!-- Button trigger modal --> <a href="" data-toggle="modal" data-target="#exampleModalCenter"> <i class="la la-edit edit"></i> </a> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Delete Order</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <h5>{{order.oid}}</h5> </div> <div class="modal-footer"> <div class="col-6 text-left"> <div class="previous"> <form action="{% url 'delete_order' order_item.id %}" method="POST"> {% csrf_token %} <input class="btn btn-danger btn-sm btn-block" type="submit" name="Yes" value="Yes"> </form> </div> </div> <div class="col-6 text-left"> <div class="next"> <a class="btn btn-warning btn-sm btn-block" href="">No</a> </div> </div> </div> </div> </div> </div> The error is abount addressing I guess: DoesNotExist at /panel/profile/{% url 'delete_order' order_item.id -
OneToOneField in Django is not working properly
In my 'users' app in my Django project I have the following code for my model: from django.db import models from django.contrib.auth.models import User class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField (default='default.jpg', upload_to='profile_pics') bio = models.TextField(blank=True) def __str__(self): return f'{self.user.username} Profile' I have done the migrations correctly and registered this to admin.site.register My problem is that the field 'user' does not make an Account instance. In other words I cannot access to the data in the fields of Account model through User instances. For example I cannot access to user.account.bio or user.account.image -
Django/Js: how to post a form without reloading whole page
My application currently flows through 3 pages: User selects question in index page User submits answer in answer page User is presented with result in results page. I want to compress that down to a single page where the user submits an answer to the question and result is shown on the same page. The following django-template code separates questions with Bootstrap accordion. How do I post the form without refreshing the whole page? I want to be able to display the result on the page, update CSS styling with Javascript etc. <h2>{{ category.title }}</h2> <div class="accordion" id="accordion{{category.title}}"> {% for challenge in category.challenge_set.all %} <div class="card"> <div class="card-header" id="heading{{challenge.id}}"> <h2 class="mb-0"> <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapse{{challenge.id}}" aria-expanded="true" aria-controls="collapse{{challenge.id}}"> {{ challenge.question_text }} - {{ challenge.point_value }} points </button> </h2> </div> <div id="collapse{{challenge.id}}" class="collapse in" aria-labelledby="heading{{challenge.id}}" data-parent="#accordion{{category.title}}"> <div class="card-body"> <p>{{ challenge.description }}</p> <form action="{% url 'challenges:answer' challenge.id %}" method="post"> {% if challenge|is_answered:request %} <label for="answered">Answer</label> <input type="text" name="answered" id="answered" value="{{ challenge.answer_text }}" readonly> {% else %} {% csrf_token %} <label for="answer">Answer</label> <input type="text" name="answer" id="answer"> <input type="submit" value="Submit"> {% endif %} </form> </div> </div> {% endfor %} </div> Here is the view: def index(request): context = {'challenges_by_category_list': Category.objects.all()} return … -
Sending data from ESP8266 to server [closed]
I need to somehow send data from my ESP8266 to my pc. I want to receive data from esp on pc and log them to csv file for example. I would like to visualise them and make some kind of gui but it's not necessary. Minimum goal is to be able to receive data from many esp devices and log them. I don't really know what should i use to do so. At the moment i am able to send messages through MQTT but i have no clue how to make some kind of server on my pc. I thought about doing website with django but i'm not sure if it is a good idea tbh. I know about generally available sites as thingspeak.com but i want to avoid using it. Any tips what technologies, languages, frameworks would be best to use in this case? I would be grateful for any advices. -
How to allow to edit field in django admin list depending on a value?
I need to allow to change a value of a field if it doesn't equal to 0. I found that I need to override get_changelist_form but don't know how. I tried to override form but it raised Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form OrderChangeListForm needs updating. What I need: def get_changelist_form(self, request, **kwargs): # if instance.status == 0 make it not editable return super(MyModelAdmin, self).get_changelist_form(request, **kwargs) My Model: class ModelAdmin (admin.ModelAdmin): list_display = ['id', 'client', 'status'] list_editable = ('status',) -
channels.layers.get_channel_layer() is returning None type object | Django Channels 3.0.2
I want to send messages to the channel but for that, I am not able to find the reason why the below code is not working in the shell of the project(justchat): >>> from channels.layers import get_channel_layer >>> print(get_channel_layer()) > None I have followed the complete "channels 3" documentation hence all the configurations are the same as there in the documentation. # justchat.settings ASGI_APPLICATION = 'justchat.asgi.application' CHANNELS_LAYERS = { 'default':{ 'BACKEND':'channels_redis.core.RedisChannelLayer', 'CONFIG':{ 'hosts':[('127.0.0.1',6379)], }, }, } # consumers.py import json from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) # justchat.asgi import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack import chat.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'justchat.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket":AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ) }) -
How to pass context result as argurment for another function in django?
I have my django app which searches youtube and return result as a dictionary which i render them in template, one of the returned value is link , now I have a download button they way i wish it to function is whenever you click a button it should take the url for the clicked result and pass it to another download function as an argument. How do I accomplish that ? Here is my view.py def index(request): if request.method == 'POST': query = request.POST['video_name'] n = 12 search = SearchVideos(str(query), offset = 1, mode = "json", max_results = n) ytresults = search.result() result_dict = json.loads(ytresults) context = { "result" : result_dict, } template_name = "youloader/results.html" return render(request, template_name, context) else: query = "no copyright sound" n = 12 search = SearchVideos(str(query), offset = 1, mode = "json", max_results = n) index_results = search.result() result_dict = json.loads(index_results) context = { "result" : result_dict } template_name = "youloader/index.html" return render(request, template_name, context) def downloading_video(request): try: with youtube_dl.YoutubeDL(video_opts) as ydl: ydl.download(link) except: pass here are my template.html <div class="my-4" > <div style="padding-top: 20px"> <div class="row" > {% for result in result.search_result %} <div class="col-12 col-sm-6 col-md-4 col-lg-4"> <div class="card shadow-sm border-0 my-2"> … -
Nginx and Uwsgi not working working on Google cloud Platform(Django, Debian-10 vm instance)
I am trying to deploy my django project on google cloud vm instance(debian 10). But when I start nginx and access External ip of instance it shown nginx but when I run uwsgi then it shows 502 bad gateway. I even don't know if my sockets working or not. here is my config files. Nginx config for my project. # the upstream component nginx needs to connect to upstream DemoProject { server unix:///tmp/DemoProject.sock; } server { listen 80; server_name my_vm_instance_external_ip; return 301 https://my_vm_instance_external_ip$request_uri; } server { listen 443 ssl; ssl_certificate /home/User/Production/DemoProject/ssl/DemoProject.crt; ssl_certificate_key /home/User/Production/DemoProject/ssl/DemoProjectkey; server_name my_vm_instance_external_ip; access_log off; error_log /home/User/Production/DemoProject/logs/nginx_error.log; location / { include /etc/nginx/uwsgi_params; uwsgi_pass DemoProject; } location /static/ { alias /home/User/Production/DemoProject/static/; } } Uwsgi config for my uwsgi [uwsgi] # variables projectname = DemoProject base = /home/User/Production/DemoProject # configuration master = true virtualenv = /home/User/Production/djangorest pythonpath = /usr/lib/python3.7 chdir = /home/User/Production/DemoProject env = DJANGO_SETTINGS_MODULE=DemoProject.settings.pro module = DemoProject.wsgi:application socket = /tmp/DemoProject.sock chmod-socket = 666 And allowed host setting in django settings ALLOWED_HOSTS = ['my_vm_instance_ip.com','www.my_vm_instance_ip'] And also I did add this lines on /etc/nginx/nginx.conf include /home/User/Production/DemoProject/config/nginx.conf -
index 33 is out of bounds for axis 1 with size 33
I am getting this error at this line my_predictions = prediction_matrix[:,current_user_id-1]+Ymean.flatten() This is the code. Please tell me how do I fix it? def recommend(request): if not request.user.is_authenticated: return redirect("login") if not request.user.is_active: raise Http404 df=pd.DataFrame(list(Myrating.objects.all().values())) nu=df.user_id.unique().shape[0] current_user_id= request.user.id # if new user not rated any movie if current_user_id>nu: movie=Movie.objects.get(id=15) q=Myrating(user=request.user,movie=movie,rating=0) q.save() print("Current user id: ",current_user_id) prediction_matrix,Ymean = Myrecommend() my_predictions = prediction_matrix[:,current_user_id-1]+Ymean.flatten() pred_idxs_sorted = np.argsort(my_predictions) pred_idxs_sorted[:] = pred_idxs_sorted[::-1] pred_idxs_sorted=pred_idxs_sorted+1 print(pred_idxs_sorted) preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pred_idxs_sorted)]) movie_list=list(Movie.objects.filter(id__in = pred_idxs_sorted,).order_by(preserved)[:10]) return render(request,'web/recommend.html',{'movie_list':movie_list}) -
How to disable autoescape when using django template from_string() and render()?
I am sending an email using django-post_office, which renders the subject line using django templates: subject = engine.from_string(self.template.html_content).render(self.context) Django templates automatically sets autoescape=True for security, which means if you have an HTML character such as Here's an email it will produce a string with the character escaped: Here&#x27;s an email. How can I disable autoescape when using from_string and render in this way to display the email subject appropriately? An alternative example: from django.template import engines template = engines['django'].from_string("My name is {{ my_name }}.") context = {"my_name": "<FooBar's>"} print(template.render(context)) Results in: My name is &lt;FooBar&#x27;s&gt;. -
TemplateDoesNotExist at /wiki/CSS/edit_entry error in djano
I have tried other answers in StackOverflow, but didn't find a solution. I have a function that edits the page content: def edit_entry(request, title): content = util.get_entry(title) if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] util.save_entry(title, content) return redirect('edit_entry', title) return render(request, "encyclopedia/edit_entry", { "title": title, "content": content }) My urls.py looks like: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry, name="entry"), path("search", views.search, name="search"), path("add_entry", views.add_entry, name="add_entry"), path("wiki/<str:title>/edit_entry", views.edit_entry, name="edit_entry") ] Here is my edit_html template: {% extends "encyclopedia/layout.html" %} {% block title %} Edit page {% endblock %} {% block body %} <form action="{% url 'edit_entry' title %}" method="POST"> {% csrf_token %} {{ title }} {{ content }} <input type="submit" value="Save Editing"> </form> {% endblock %} As you see, the template exists here: But it says TemplateDoesNotExist at /wiki/CSS/edit_entry The template belongs to my application, so, I guess, no need to add it to DIRS = [], which is located in settings.py. And other routes except this one are working fine. -
'ForwardManyToOneDescriptor' object has no attribute 'id' - Error
I am having model: class TextBook(models.Model): code = models.CharField(max_length=200, unique=True) type = models.CharField(max_length=200) name = models.CharField(max_length=200) open_qty = models.DecimalField( max_digits = 4, decimal_places = 0,default = 0) recived_qty =models.DecimalField( max_digits = 4, decimal_places = 0,default = 0) return_qty=models.DecimalField( max_digits = 4, decimal_places = 0,default = 0) issue_qty=models.DecimalField( max_digits = 4, decimal_places = 0,default = 0) bal_qty = models.DecimalField( max_digits = 4, decimal_places = 0,default = 0) avgcost =models.DecimalField( max_digits = 5, decimal_places = 2,default = 0.00) price =models.DecimalField( max_digits = 5, decimal_places =2,default = 0.00) class_name = models.ManyToManyField(SchClass, help_text='Select a class for this book') term = models.ManyToManyField(SchTerms, help_text='Select Terms') class TransBody(models.Model): trans_header = models.ForeignKey(TransHeader,on_delete=models.CASCADE,null=True) book = models.ForeignKey(TextBook,on_delete=models.CASCADE) quantity = models.IntegerField(default=0) price = models.FloatField(default=0) def get_absolute_url(self): """Returns the url to access a detail record for this book.""" return reverse('select_stock_report', args=[str(self.id)]) my view: def listSelectStkTrans(request,id): # (note:return(HttpResponse(id) gives correct book id) allstktrans =TransBody.objects.filter(id=TransBody.book.id) context = {'allstktrans': allstktrans} return render(request, 'wstore/list_stk_trans.html', context) my url: path('listselectstktrans/<int:id>/', views.listSelectStkTrans, name='select_stock_report'), my template has link: {{ book.code }} I am getting 'ForwardManyToOneDescriptor' object has no attribute 'id' - Error. -
Python: How to assign Python function to HTML button using Django
Python 3.8.5 Django 3.1.2 I created a Django Project. I have an HTML page created with a button. I need to assign the following urlpattern to that HTML button... path('', views.output, name='output'), That URLpattern is linked to a function called 'output' which runs successfully on it's own. I'm using the following HTML code to assign that function to my HTML button... <button onclick="Location.href='{% url 'output' %}'"> Enter </button> This does not work. I cannot get this button to run my function. Does anyone know how to assign this function successfully? Here is my code in my urls.py file... from django.contrib import admin from django.urls import path, include from myapp import views urlpatterns = [ path('app/', include('myapp.urls')), path('admin/', admin.site.urls), path('', views.output, name='output'), ] -
i want my balance keep updates when a purchase has been made
Hello i want create a virtual payment system.All the functions works properply but whenevr i purchase something my balance is not updating. Here is my views.py : def post(self, request, *args, **kwargs): ids = list(request.session.get('cart').keys()) cart_products = Product.get_products_id(ids) product_prices = list(map(self.map_func, cart_products)) total_due = sum(product_prices) balance = request.session['customer']['coin'] if balance >= total_due: balance = balance - total_due Customer.objects.filter(id = request.session['customer']['id']).update(coin=balance) request.session['customer']['coin'] = balance return HttpResponse(balance) return HttpResponse("Failed") Here is my index: {% extends 'Home/header.html' %} {% load cart %} {% block content %} {{user_orders.product.name}} {{user_orders.product.price}} {{total_due}} <h5>{{request.session.customer.coin}}</h5> <form action="" method="POST"> {% csrf_token %} <input type="submit" name="payment_coin"> </form> {% endblock %} What i actually i want is when a purchased has been made account balance will be automaticly update. -
Rest Framework serializer raises "NotImplementedError: `create()` must be implemented." error
So, I'm following a React and Django Tech with Tim tutorial, but it's raising an error saying NotImplementedError: 'create()' must be implemented. Models.py from django.db import models import string import random def generate_unique_code(): length = 6 while True: code = ''.join(random.choices(string.ascii_uppercase, k=length)) if Room.objects.filter(code=code).count() == 0: break return code class Room(models.Model): code = models.CharField(max_length=8, default="", unique=True) code = models.CharField(max_length=50, unique=True) guest_can_pause = models.BooleanField(null=False, default=False) votes_to_skip = models.IntegerField(null=False, default=1) created_at = models.DateTimeField(auto_now_add=True) Serializers.py from rest_framework import serializers from .models import Room class RoomSerializer(serializers.Serializer): class Meta: model = Room fields = ('id', 'code', 'host', 'guest_can_pause', 'votes_to_skip','created_at')``` Views.py from django.shortcuts import render from rest_framework import generics from .models import Room from .serializers import RoomSerializer class RoomView(generics.CreateAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer How can I make this code work? I tried changing class RoomSerializer(serializers.Serializer): to class RoomSerializer(serializers.ModelSerializer): but that just raised another error: Field name 'host' is not valid for model 'Room'. Any help is appreciated :) -
Django Serializer for 3 models, with chained foreignKeys
Let's use these 3 simple models for example. A city can have multiple shops, and a shop can have multiple products models.py class City(models.Model): name=models.CharField(max_length=300) class Shop(models.Model): name = models.CharField(max_length=300) city = models.ForeignKey(City, related_name='related_city', on_delete=models.CASCADE) class Product(models.Model): name=models.CharField(max_length=300) shop=models.ForeignKey(Shop, related_name='related_shop', on_delete=models.CASCADE) serializers.py class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields=['id','name'] class ShopSerializer(serializers.ModelSerializer): related_shop = CitySerializer(many=True, read_only=True) class Meta: model = Shop fields=['id','name','related_city'] class ProductSerializer(serializers.ModelSerializer): related_shop = ShopSerializer(many=True, read_only=True) class Meta: model = Product fields=['id','name','related_shop'] ProductSerializer will give me all products, and will fetch the foreignKey shops, and I will also get the names of the shops where this product is found. ShopSerializer, in a similar way, will give me all shops names, and all the cities where this shop can be found. But how can I make a serializer, that will retrieve from all 3 tables at once? The fields I want are: fields=['product_name','shop_name', 'city_name'] That list I will get will have repetitions, and can be considered 1NF or 2NF, opposed to the model design I have as database 3NF. I was actually thinking of denormalizing my database, so I can easily achieve this. My second question is, is it better to denormalize it to 1NF, and have repetitions, so …