Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Create ,Get and update JSON data in Django model?
I seen many answer related this problem but I confused how to implement this. My requirement is: (Create)First create data with key and value: {"pradip" : 80} and store in user_rate_details model field. (Update)Second time append new data in this field : {"pradip" : 80,"exz" : 70} and save it. How to achieve this in my views.. models.py: class UserPhoto(models.Model): user = models.ForeignKey(to = User,on_delete = models.CASCADE,related_name='userPhoto') ...... rated_by = models.ManyToManyField(Profile,blank=True,related_name='rate_by') user_rate_details = models.TextField() ⬅⬅⬅⬅⬅ Here store JSON data created_date = models.DateTimeField(auto_now_add=True) views.py: class PhotoRate(APIView): permission_classes = [IsAuthenticated] def get_userPhoto(self,pk): try: return UserPhoto.objects.get(id = pk) except UserPhoto.DoesNotExist: raise Http404 def post(self,request,formate = None): pk = request.data.get('photo_id') rate = request.data.get('rate') photo = self.get_userPhoto(pk) ???????? How to create or update Json data here??? return Response(??JSON DATA??) Any other best way you know please tell me.. Thank you.. -
Stanza predicting different labels to the same word and same version
I'm trying to predict 'excited' using stanza model, the same function is used in a colab notebook and in a aws ec2 API. When I try to predict this word, Im getting the label 'positive' in the colab notebook and 'neutral' in the API which is an app from django. I'd checked the Stanza version in both environment and both are using: Name: stanza Version: 1.2 Summary: A Python NLP Library for Many Human Languages, by the Stanford NLP Group Home-page: https://github.com/stanfordnlp/stanza Author: Stanford Natural Language Processing Group Author-email: jebolton@stanford.edu License: Apache License 2.0 Location: /usr/local/lib/python3.7/dist-packages Requires: numpy, requests, tqdm, torch, protobuf Required-by: However, one thing that I'm not sure if is the same is the folder stanza_resources (if the version is the same for both, this should be the same?). Function: !pip3 install stanza import stanza stanza.download('en', package='ewt', processors='tokenize,sentiment,pos', verbose=True) stanza.download('en', package='default', processors='tokenize,sentiment', verbose=True) stanza.download(lang="en",package=None,processors={"pos":"combined"}) stNLP = stanza.Pipeline(processors='tokenize,sentiment,pos', lang='en', use_gpu=True) def stanza_predict(text): ''' :param text: text to be predicted :param verbose: 0 or 1. Verbosity mode. 0 = to predict text, 1 = to predict labels. :return: POSITIVE or NEGATIVE prediction ''' data = stNLP(text) sentiment_map = {'0': 'NEGATIVE', '1': 'NEUTRAL', '2': 'POSITIVE'} #print(data) for sentence in data.sentences: pred_sentiment … -
Retain django form data even if validation using recaptcha fialed
I am writing a contact form for my website, and I am using reCaptcha to validate the user prior form submission. I can't figure out how to structure my logics so that if reCaptcha fails, I can still redirect the user to the same page WITHOUT deleting the fields that they already have typed. In my views.py I have the followings. class hdnytorv(View): def __init__(self, *args, **kwargs): self.ContextObject = ContextBuilder() #building a dict with context keywords if 'contactFrom' in kwargs: #Then this comes from a post that has failed and data needs to be saved self.form = kwargs['contactForm'] else: self.form = contactForm() self.context = {'contactForm' : self.form} #When the page is generated first the below will be shown def get(self, request, *args, **kwargs): .. return render(request, template_name='welcome.html', context = self.context) def post(self, request, *args, **kwargs): form = contactForm(request.POST) newsletterForm = newsLetterForm(request.POST) if form.is_valid(): #check recaptcha validate = Validate(request = request) validate.result['success'] =False if validate.result['success'] is False: messages.warning(request, 'Validation failed. Try again.', extra_tags='contactSubmitStatus') return redirect('/welcomePage#contactForm') The problem is everytime I redirect to `'/welcomPage#contactForm' a new class instance will be made and the get will be called and the form will be rerendered so all the fields are empty and user's data … -
Django, error in form submission, Django form unable to take entered text
The code is to receive a text and search database, below code work well <form method="GET" action="{% url 'search:search' %}"> <input placeholder="Search"> <button type="submit">{% trans "Search" %}</button> </form> However I decided to change UI, but after form submission, Django does not getting entered text <form class="example" method="GET" action="{% url 'search:search' %}"> <input type="text" placeholder="Search" name="search"> <button type="submit"><i class="fa fa-search"></i></button> </form> -
Django TypeError: allow_migrate() got multiple values for argument 'model_name'
Whilst trying to migrate my django project, I keep getting the following traceback every time I try to run python3 manage.py migrate. TypeError: allow_migrate() got multiple values for argument 'model_name' This error also occurs when I try to run python3 manage.py --test -
How do you import custom classes into Django views.py?
I'm trying to import a group of python classes from my mdt folder into views.py, but every time I try and run the view with the localhost, I get a ModuleNotFoundError for the Network class. I also know my FoliumMap class is not importing properly as when I remove the part of the code that returns the error for the Network class, I can't access a function from the FoliumMap class. I've seen some questions about this, and tried to do what they've said, but I still either get the same ModuleNotFoundError, or it can't find the file at all. I'm just really struggling to see what I'm missing. Other than what I have below, I haven't changed any of the Django generated files except to get the urls & localhost working. Here's the file structure at the moment, where I'm trying to import the FoliumMap class in FoliumMap.py file, and the Network, Segment and Node classes from the Network.py file. Here's the error page that I keep getting. This is all the code in views.py: from .mdt.FoliumMap import * from .mdt.Network import * import pickle from django.shortcuts import render from django.http import HttpResponse def show_emissions(request): fol = FoliumMap() network … -
Best practice to filter and paginate queryset in django
What is the best way to filter a model and paginate it? I tried using django-filter, but when I pass filtered queryset to paginator, for some reason, it duplicates some of queryset's objects and renders them in template twice, I tried to find solution for 3 days and ended up with nothing. So, what is the right way to do this? Maybe I should use not django-filter but something diffrent? I will be very happy if someone gives me advice on this topic! -
Django Rest Framework multiple field upload with serializers.FileField
I am trying to upload multiple files through and API using DRF. It works, what I want is created, but I don't understand why it always ends in an error. I currently handle it with a try/except which seems to do the job until I find an answer. Here is the error: TypeError: 'RelatedManager' object is not iterable Here are some snippets of my current code (Giveaway and GiveawayMedia are 2 models which should be straight forward from the code below): class GiveawayViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] serializer_class = SimpleGiveawaySerializer # Irrelevant to this question parser_classes = (MultiPartParser, FormParser,) def get_serializer_class(self): if self.action == "create": return GiveawayPostSerializer # /giveaways - POST def create(self, request, *args, **kwargs): try: super().create(request, *args, **kwargs) except TypeError: pass return Response("Created - Giveaway created.") class GiveawayPostSerializer(serializers.ModelSerializer): media = serializers.ListField(child=serializers.FileField(), required=False) class Meta: model = Giveaway read_only_fields = ["id"] fields = [ "id", "media", # more fields ] def create(self, validated_data): new_giveaway = Giveaway.objects.create(...) # other fields to create here if "media" in validated_data: for m in validated_data["media"]: GiveawayMedia.objects.create(giveaway=new_giveaway, media=m) new_giveaway.save() return new_giveaway Any help appreciated! -
Django-React App Static/Media Serving Method
Me and my friend have started a project including Django, Django REST and React. I have a little experience in deploying standalone django apps but not in django-react. The plan for now is, that the admin will upload pictures via django-admin and the website will be displaying new pictures as admin is going to upload them. (If thats even possible with this combination.) And the question is: How am I supposed to serve static files? I know that one of the best solutions is to store static files (photos, templates, css etc.) on things like Amazon AWS S3 if working on standalone django project, but I have no idea if thats the right solution in our case because as I said, I've never done anything like that and I can't find any answers for my question and every setup tutorial doesn't say anything about that. And if that's the best solution, could anyone please give me some link for that tutorial or anything that could help us? Im responsible for Django and my friend for React. Thank you. -
ValueError at / Cannot query "user5": Must be "Customer" instance
even though user5 is an in the user but when I login It gives me this message ValueError at / Cannot query "user5": Must be "Customer" instance. Here are the models of my website. Please suggest some solution This website also enables you to checkout without having an account. I am stuck on this, please tell me a solution. models.py class Customer(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE, related_name = 'customer', null=True, blank=True) name = models.CharField(max_length= 200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey(Customer, on_delete= models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, blank=False, null=True) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def shipping(self): shipping=False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping=True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total views.py def loginPage(request): if request.method=="POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user: login(request, user) messages.success(request, "Logged In") return redirect('store') else: messages.error(request, "Invalid Credentials") return redirect("login") context = {} return render(request, 'store/login.html', context) def … -
TemplateSyntaxError at /polls/ Invalid block tag on line 27
I'm currently working through the Django tutorial and just finished part 3, but am getting this error when trying to access http://127.0.0.1:8000/polls/: TemplateSyntaxError at /polls/ Invalid block tag on line 27: '<span', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Django Version: 3.1.7 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 27: '<span', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Error during template rendering I think there's a problem with my views.py file, but I've copy/pasted everything from the tutorial trying to avoid these issues. This is the view that the error is being thrown on: def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) I'm very new to this so if I'm missing something obvious, please point it out. index.html: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url ‘polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} -
Webscraping project + webpage
I am building a django project with a webpage where the user can search for documents. I use a webscraper to retrieve documents and store them in a database. The scraping should be run every two hours and takes roughly 5 minutes. I have used apscheduler and created a scraping_app in my django project. But when it is scraping I cannot have any search calls from the webpage. How can I make sure that the scraping is not stopping the webpage? As I am new to web development I was wondering what the best practice is. Should I have the scraping completely independent from the webpage project and only share the same database? Or integrate both in the same project? -
Can I change the list in the foreign key dependant on the Boolean in the models class?
class Batting(models.Model): home_team = models.BooleanField(blank=True, null=True) member = models.ForeignKey(Member, on_delete=models.CASCADE, default='') Im using Django tables and was wondering is there a way to choose a different table in the foreign key with what the home_team variable is? I want the home team selection of players to be different from that of an away team. -
How can insert list items to database in django?
Here is my template : {% for pr in productlist %} <ul> <li>{{ pr.productid }} <input type="hidden" id="prid" name="mylist" value="{{ pr.productid }} "></li> <li>{{ pr.productname }} <input type="hidden" id="prname" name="mylist" value="{{ pr.productname }}"></li> <li><input type="number" name="mylist" id="prqty"/></li> </ul> {% endfor %} I get list of items in view : pd = request.POST.getlist("mylist") and result is: 1 product1 23 2 product2 44 3 product3 18 and complete view is this : def post(self, request): if request.user.is_authenticated: pd = request.POST.getlist("mylist") #invoice invoice = models.Sellinvoice.objects.create( type = "5", date = datetime.datetime.now() ) #invoiceItems for item in pd: qty = 1 models.Sellinvoiceitems ( productid = <<-- problem, productname = <<-- problem, totalnumber = <<-- problem, sellinvoice = invoice, stockid = stock ).save() invoice.save() My question is how i save all item in above list using for each? -
Is there a way to error on related queries in Django ORM?
I have a Django model backed by a very large table (Log) containing millions of rows. This model has a foreign key reference to a much smaller table (Host). Example models: class Host(Model): name = CharField() class Log(Model): value = CharField() host = ForeignKey(Host) In reality there are many more fields and also more foreign keys similar to Log.host. There is an iter_logs() function that efficiently iterates over Log records using a paginated query scheme. Other places in the program use iter_logs() to process large volumes of Log records, doing things like dumping to a file, etc. For efficient operation, any code that uses iter_logs() should only access fields like value. But problems arise when someone innocently accesses log.host. In this case Django will issue a separate query each time a new Log record's host is accessed, killing the performance of the efficient paginated query in iter_logs(). I know I can use select_related to efficiently fetch the related host records, but all known uses of iter_logs() should not need this, so it would be wasteful. If a use case for accessing log.host did arise in this context I would want to add a parameter to iter_logs() to optionally use .select_related("host"), … -
how to connect input tags with form fields in django
I have input tags in an HTML page and I want to connect those with form fields I have linked forms with a model to save the details in the database. when I am adding signup-form as a parameter in return, the model is displaying its own form and my own form is also displaying. I want the code to connect my Html form with the Django form using the name attribute login.html <form method = "POST" enctype="multipart/form-data" id="register" class="input-group-register needs-validation" novalidate oninput='up2.setCustomValidity(up2.value != up.value ? "Passwords do not match." : "")'> <!-- {{ signup_form.as_p }} --> {% csrf_token %} <input type="text" class="input-field" id="firstname" placeholder="First Name" name = "first_name" required> <div class="invalid-feedback">Please enter a valid first name.</div> <input type="text" class="input-field" id="lastname" name = "last_name" placeholder="Last Name" required> <div class="invalid-feedback">Please enter a valid last name.</div> <input type="email" class="input-field" id="email" name = "emailid" placeholder="Email" required> <div class="invalid-feedback">Please enter a valid Email Address.</div> <input type="number" class="input-field" id="mobile" name = "number" placeholder="Mobile" required> <div class="invalid-feedback">Please enter your Mobile Number.</div> <input type="password" class="input-field" id="password" placeholder="Enter Password" name="up" required> <div class="invalid-feedback">Please enter your password.</div> <input type="password" class="input-field" id="confirmpassword" placeholder="Confirm Password" name="up2" required> <div class="invalid-feedback">Password doesn't match.</div> <input type="checkbox" class="check-box" required> <span> I agree to the Terms … -
How to send live camera feed from react page to django server
Hello I want to send the live video captured from my react app to Django server. but I am confused how to share the same and process it faster can someone help me -
Django custom list_display in admin - problem in production server
I have a form where users submit sequences that are stored in the user_submission model. In Django admin, I have added a custom list display naming_algorithm (like below). It takes the obj. sequence and runs an external script and displays the output in HTML. It works locally well. When I try to use it on the production server it shows nginx 502 Bad Gateway. FYI: I use nginx and uWSGI for deployment. I am using Django 2.2 and Python3.7. class UserSubmissionAdmin(admin.ModelAdmin): list_display = ( 'submittersname', 'accession_url', 'naming_algorithm', ) def naming_algorithm(self, obj): if ">" in str(obj.sequence).split('\n')[0]: obj.sequence = '\n'.join( str(obj.sequence).split('\n')[1:]) return format_html('<a href="/run_naming_algorithm/?fulltextarea={0}&submission_id={1}" target="_blank">Naming Algorithm</a>'.format(obj.sequence, obj.id)) I have a few questions In the production server if I change DEBUG=True the above function works. If I change it to DEBUG=False nginx reports 502 Bad Gateway. Why this happens and how to approach the problem and fix it. Any pointers will help. As you can see in the screenshot, I am passing the sequence through the URL. It seems to me there must be a better way to do it. I am unaware of it. Do you have any suggestions or alternative ways? -
Filtering in Django html template
I'm passing two models into the html template listings - has all the properties of the listed items (like on an auction site) bids - has a listing field as a foreign key to link to listings (and the user who made a bit, plus the amount) I'm looping through the listings items to display all their attributes of the individual listings on cards (that works nicely) I want to display the bid that belongs to the individual listing if there is any (only the highest bid is passed on for each listing in the 'bid' queryset) I suspect the problem is with the syntax here, but can't find a solution. <p>{{bids.filter(listingID=listing.listingID)}}</p> The error message: Could not parse the remainder: '(listingID=listing.listingID)' from 'bids.filter(listingID=listing.listingID)' This is my HTML template {% extends "auctions/layout.html" %} {% block body %} <h2>Active Listings</h2> <div></div> {%for listing in listings%} <div class="listingItem"> <div class="listingLeft"> <a href={{listing.id}}><img class="listingImage" src="{{listing.listingImage}}"></a> </div> <div class="listingRight"> <a href={{listing.id}}><h4>{{listing.listingName}}</h4></a> <p>{{listing.listingDesc}}</p> <p>Current bid: ${{listing.listingFirstBid}}</p> <p>{{bids.filter(listingID=listing.listingID)}}</p> <p class="created">Created: {{listing.listingCreated}}</p> </div> </div> {%endfor%} {% endblock %} -
How can I Represent a list of dictionary in a tabular form in Django in my view.py
[{'card pin 0': 4925795801642108, 'card pin 1': 6184551705968070, 'card pin 2': 8818636104783618, 'card pin 3': 8085277979531543}, {'serial 0': 'WRN7677', 'serial 1': 'WRN2637', 'serial 2': 'WRN7464', 'serial 3': 'WRN7917'}] This is the result I get from these two functions below when called from my view.py: def generate_card_serial(total=10, prefix='SCH', length=4): range_start = 10 ** (length - 1) range_end = (10 ** length) - 1 times_run = 0 serial_dict = {} while times_run <= total - 1: gen1 = randint(range_start, range_end) serial_dict.update({'serial' + ' ' + str(times_run): prefix + str(gen1)}) times_run += 1 return serial_dict def generate_card_pin(length_of_pin=16, duplicate=5): range_start = 10 ** (length_of_pin - 1) range_end = (10 ** length_of_pin) - 1 pin_dict = {} times_run = 0 while times_run <= duplicate - 1: gen1 = randint(range_start, range_end) pin_dict.update({'card pin ' + str(times_run): gen1}) times_run += 1 return pin_dict What this two functions do is to generate a "10" '4' digit card serial number with a prefix and a "5", '16' digit card pin; and in this format as shown in the result above. this is my view.py function: def card_gen(request): prefix = request.GET["initial"] number_of_cards_to_generate = request.GET["total"] prefix = str(prefix) number_of_cards_to_generate = int(number_of_cards_to_generate) card_serial = generate_card_serial(prefix=prefix, total=number_of_cards_to_generate) card_pin = generate_card_pin(duplicate=number_of_cards_to_generate) card_detail = list([card_pin, … -
Setup certificate for multiple subdomain
I have 30+ subdomain with http connection and 1 domain with https connection I need to setup SSL certificate on all subdomain. How to do it? My assembly: nginx, Django, -
how can i install psycopg2 in windows 10 when i have error and
I have a problem I cant install with pip install pycopg2 help please it say could not find a version that satisfies the requirement psycopg2 i help pip install psycopg2 but its not work -
Django + Procfile on AL2
To setup the WSGIPath for the app running on my instances, I used to have the code below in my .ebextensions. option_settings: aws:elasticbeanstalk:container:python: WSGIPath: app/wsgi.py NumProcesses: 3 NumThreads: 20 The instances are Amazon Linux 2, and I have now replaced the above with a Procfile (in my project's root). However, I am having trouble to get it to work as Elastic beanstalk's eb deploy always gives me an ERROR message, and sets the WSGI path to application.py (file does not exist). Your WSGIPath refers to a file that does not exist. Contents of Procfile: web: gunicorn --bind :8000 --workers 3 --threads 2 app.wsgi:application Any ideas on how I can get it to update the path using the Procfile? -
jquery-3.1.1.min.js:4 POST 500 (Internal Server Error) | error in ajax with Django
I try to build a comment system in Django With ajax but when I type comment and try to submit this error appear in the console jquery-3.1.1.min.js:4 POST 500 (Internal Server Error) . I am using Django in the backend I let my comment model as MPTTModel My HTML template <form id="commentform" class="commentform" method="post"> {% csrf_token %} {% with comments.count as total_comments %} <h2> {{ total_comments }} comment{{total_comments|pluralize}} </h2> {% endwith %} {% load mptt_tags %} <select class="d-none" name="video" id="id_video"> <option value="{{ video.id }}" selected="{{ video.id }}"></option> </select> <label class="small font-weight-bold">{{ comment_form.parent.label }}</label> {{ comment_form.parent }} <div class="d-flex"> <img class="avatar_comment align-self-center" src="{% for data in avatar %}{{ data.avatar.url }} {% endfor %}"> {{ comment_form.content }} </div> <div class="d-flex flex-row-reverse"> <button value="commentform" id="newcomment" type="submit" class="newcomment btn btn-primary">Submit</button> My Javascript ajax $(document).on('click', '#newcomment, #newcommentinner', function (e) { e.preventDefault(); var button = $(this).attr("value"); var placement = "commentform" if (button == "newcommentform") { var placement = "newcommentform" } $.ajax({ type: 'POST', url: '{% url "video:addcomment" %}', data: $("#" + button).serialize(), cache: false, success: function (json) { console.log(json); $('<div id="" class="my-2 p-2" style="border: 1px solid grey"> \ <div class="d-flex justify-content-between">By ' + json['user'] + '<div></div>Posted: Just now!</div> \ <div>' + json['result'] + '</div> \ <hr> … -
Django==1.8.6 POSTGRES 9.2.24: create blank database
I have an app build with Django==1.8.6 and connected to a POSTGRES 9.2.24 database. It records timesheets and financial data of my company. We want to use the same app for a sister company but I need a blank database: save the superusers to add new users (using the django admin) and delete all other data. Is there a utility that can do that or do I have to empty data table by table?