Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: Cannot assign "'A0A0B2SJI5'": "Protein.protein" must be a "ProteinSequence" instance
I'm trying write a python script to add data from a .csv file (django and sqlite) and I'm stuck on this issue since days. My django model looks like this: class Protein(models.Model): protein = models.ForeignKey(ProteinSequence, on_delete=models.DO_NOTHING, null=True, blank=True, db_constraint=False) protein_taxonomy = models.ForeignKey(Taxonomy, on_delete=models.DO_NOTHING) protein_length = models.IntegerField(null=True, blank=True) protein_domains = models.ForeignKey(ProteinFamily, on_delete=models.DO_NOTHING) def __str__(self): return self.protein.protein_id class ProteinSequence(models.Model): protein_id = models.CharField(max_length=10, null=False, blank=False) protein_sequence = models.TextField(null=True) def __str__(self): return self.protein_id Python script: for entry in protein: if entry[0] in proteinSequence_rows: row = Protein.objects.create(protein=proteinSequence_rows[entry[0]],protein_length=entry[1],protein_domains=proteinFamily_rows[entry[2]],protein_taxonomy=taxonomy_rows[entry[3]]) row.save() else: row = Protein.objects.create(protein=entry[0],protein_length=entry[1],protein_domains=proteinFamily_rows[entry[2]],protein_taxonomy=taxonomy_rows[entry[3]]) row.save() I've added 'db_constraint=False' to the protein field, when I try to run the script, it still gets stuck on the line that it cannot find in the ProteinSequence model. ValueError: Cannot assign "'A0A0B2SJI5'": "Protein.protein" must be a "ProteinSequence" instance. Any pointers how to fix this? I don't want to enforce the foreign key constraint but I still need it, when it exists. Entries get written in the database before the script finds a protein_id that doesn't have a matching pair in the proteinSequence table. I have also tried deleting the database and migration files and migrate again, still the same. -
django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
I am working on a Django project without docker, and I am using Mysql database for local and production environements. I am using windows 10 OS and I also have WSL on my windows. My Python version for windows is 3.9.10 and my python version for WSL is 3.8.10. When I was working with 3.9.10 using Windows command line, there was no issue with mysql connection and project was running successfully, however, I lost some requirement dependencies. I was not allowed to loose those dependecies by my client. So I asked my client about python version they were already using and it was python3.8.10 and it worked using WSL and I didn't lose any requirement dependency. My Problem: Now the problem is I am facing issue of django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket when I run python3 manage.py runserver after installing all the requirements successfully. I have searched a lot and I came to know that there is something wrong in my.cnf file. I searched for my.cnf file in MySql/etc/my.cnf folder but there is no file in the whole mysql folder. Can I create a my.cnf file manually? NOTE: Mysql8 is already running. How can I … -
Upload file and convert on the fly- django
I have this file in txt that am cleaning and converting it to excel which have been able to, i just wanted to make an in interface for the user to do the conversion instead of using the raw code.. I have tried to upload the file but now unable to connect the 'dots' -
What do I do to fix my PostgreSQL database connection problem in Django?
I am trying to connect my Django project to a PostgreSQL database I created on AWS but I keep getting this error message each time I run py manage.py runserver. Here is the error message: django.db.utils.OperationalError: connection to server at "database-1.ce7oz69tjzjc.us-east-1.rds.amazonaws.com" (52.3.150.111), port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections? I followed the tutorial on w3school and followed all instructions. I created a PostgreSQL database then I updated my settings with the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'codekeen', 'USER': 'baseuser', 'PASSWORD': 'database', 'HOST': 'database-1.ce7oz69tjzjc.us-east-1.rds.amazonaws.com', 'PORT': '5432' } } as I was told to, but I keep getting the error each time try migrating or running the server. What do I do to fix this? -
Import .VCF file directly without downloading to storage
5 I am creating a HTML page with JavaScript, I want it to work at both iOS and Android, when my button is clicked, the browser should ask to open this .vcf by “contact”, or default opening by “contact” and user can save it. Especially for Android, An Android phone need to import manually the VCF by opening “contact” and select “import from” storage. That isn’t user friendly! I am wondering if the code itself can request automatically the inbuilt “contact”app. Open vCard with Javascript this is similar question but did not solve for android I tried window.open() and it download my VCF on chrome instead of opening it, I will test on phone tomorrow but probably same situation will happen because browser can’t recognize VCF format -
Can't able to load the api monkeydev in java script
I am trying to make a chat bot using java script by using the django framework just to ;load the content, but i am getting the console error : Access to XMLHttpRequest at 'https://api.monkedev.com/fun/chat?msg=hi' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET https://api.monkedev.com/fun/chat?msg=hi net::ERR_FAILED 200 Uncaught (in promise) D {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …} here is my html: ChatBot AI ChatBot Send here is the cdn for axios: https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.2/axios.min.js here is my javascript code: function init() { let res_elm = document.createElement("div"); res_elm.innerHTML="Hello Myself AI, How can I help you?" ; res_elm.setAttribute("class","left"); document.getElementById('msg').appendChild(res_elm); } document.getElementById('reply').addEventListener("click", async (e) => { e.preventDefault(); var req = document.getElementById('msg_send').value ; if (req == undefined || req== "") { } else{ var res = ""; await axios.get(`https://api.monkedev.com/fun/chat?msg=${req}`).then(data => { res = JSON.stringify(data.data.response) }) let data_req = document.createElement('div'); let data_res = document.createElement('div'); let container1 = document.createElement('div'); let container2 = document.createElement('div'); container1.setAttribute("class","msgCon1"); container2.setAttribute("class","msgCon2"); data_req.innerHTML = req ; data_res.innerHTML = res ; data_req.setAttribute("class","right"); data_res.setAttribute("class","left"); let message = document.getElementById('msg'); message.appendChild(container1); message.appendChild(container2); container1.appendChild(data_req); container2.appendChild(data_res); document.getElementById('msg_send').value = ""; function scroll() { var scrollMsg = document.getElementById('msg') scrollMsg.scrollTop = scrollMsg.scrollHeight ; } scroll(); } }); -
get original file name and extension for TemporaryUploadedFile for django
i am uploading file from react form to django rest framework.In django, i am using following code to get uploaded files array. images_data =dict((self.context['request'].data).lists()).get('images', None) in settings.py file, i am using TemporaryFileUploadHandler FILE_UPLOAD_HANDLERS = ['django.core.files.uploadhandler.TemporaryFileUploadHandler'] i want to know the original name of the file that was sent to server. in name i just get a random string with no extension. i want to save the file with original extension and name. how can i get the original name and extension of the file? i am using python 3.7.12 -
How to add Likes without asking user for Authentication?
I have a pretty simple Django app for quotes. I want to add likes to every single quote but I don't want user to login for that. How can I achieve this without Logging in the user? I tried to uniquely identify users without logging in. -
Django Return the rank of each subject for each student
in my django project I have a model like this using SQLite database class assessment(models.Model): className = models.ForeignKey(classArmTeacher, on_delete=models.CASCADE, null=True) student = models.ForeignKey(students, on_delete=models.CASCADE, null=True) subjectName = models.ForeignKey(allsubject, on_delete=models.CASCADE, null=True) firstCa = models.IntegerField(default=0) secondCa = models.IntegerField(default=0) exam = models.IntegerField(default=0) i would like to a query that will return the List of each student the SUM of firstCa ,secondCa and exam for each subject offered by each student The rank of each sum for each student here is what i have which gives me the sum examtotal as expected but i cant get the Rank subjectRank to work student_ids = students.objects.filter(id__in=assessment.objects.filter(className=self.kwargs['pk']).values('student_id')) context["all_students"] = student_ids.annotate( examtotal=Sum(F('assessment__firstCa') + F('assessment__secondCa') + F('assessment__exam'), output_field=FloatField()), subjectRank= Window(expression=Rank(), order_by=F('examtotal').desc()), ) -
How to remove label of `ModelSelect2Multiple` widget?
Here's a form using django-autocomplete-light from dal import autocomplete from django import forms from core.models import TModel class TForm(forms.ModelForm): class Meta: model = TModel fields = ('name', 'test') widget = autocomplete.ModelSelect2Multiple( 'select2_many_to_many_autocomplete' ) widgets = {'test': widget} which generates the view below I want to remove Test: from the second field, how can I do so? -
Is Django application affected by the server timezone?
I have the below settings: TIME_ZONE = UTC USE_TZ = True My server timezone is UTC+1 and the end user's timezone is UTC+2. Should I care about the server timezone or it is not related at all? -
Is current time zone detected by default if USE_TZ=True
It is mentioned in docs that the current time zone should be activated. You should set the current time zone to the end user’s actual time zone with activate(). Otherwise, the default time zone is used However, I see that the values are parsed in my local timezone in the forms correctly without activating it from my side, and TIME_ZONE is UTC which is different from my local timezone. -
HTML convert to PDF not wysiwyg in Django
I'm trying to convert HTML to PDF using xhtml2pdf in django. I use ckeditor to input and in HTML it's look wysiwyg like this. But after i convert to PDF, it looks like this. Why in PDF is not same like in HTML ? -
calculate percentages over ArrayAgg column
I am trying to calculate the percentages of an aggregate column using this model function: def get_data(self, e_type, district, s_id): a = ( self.select_related("modelC") .select_related("modelP") .values("date_e", "e_type", "a_name", "a_type") .filter( e_type__iexact=e_type, a_name__iexact=district, s_id=s_id ) .annotate(c_ids=ArrayAgg("modelC__c_name")) .annotate(all_v=ArrayAgg("t_v")) .annotate(p_ids=ArrayAgg("modelP__p_name")) .order_by("-date_e") ) Say I get this value for all_v {2,3,4,5}, if I need to generate a new Aggregate column for each value in all_v, i.e. {14%, 21%, 29%, 36%}, how can I extend what I currently have or (rewrite it if that is the only option) to get percentages as well? I know I can get the aggregate sum of all_v by adding .annotate(percentages=(Sum("t_v"))), but not sure how to get percentages from there. -
Django: The view core.create_bet.PredictionCreate didn't return an HttpResponse object. It returned None instead in django?
I am creating an update view that would perform some calculations an return some result based on the calculations, however i keep getting this error whenever i try submitting my form. class PredictionCreate(LoginRequiredMixin, ProductInline, CreateView): ... def form_valid(self, form): new_form = form.instance user = self.request.user if user.profile.wallet_balance > new_form.amount: if new_form.amount >= 10: user.profile.wallet_balance -= new_form.amount user.profile.save() else: messages.warning(self.request, "Your bet amount cannot be less than $10.") return redirect("core:dashboard") else: messages.warning(self.request, "You don't have enough fund to create this bet, fund your wallet and try again.") return redirect("core:dashboard") -
Django {% include %} tag does not behave as expected
I have a post form that I want to include in my profile template using another template (post_template.html). I created the template and try to render it from post view, but when I try to include it in my parent template, is not including the form, just the button. forms.py class PostForm(forms.Form): title = forms.CharField() tag = forms.ChoiceField(choices=tags) date_time = forms.DateTimeField() description = forms.CharField(widget=forms.Textarea(attrs={'name': 'body', 'rows': 2, 'cols': 40})) post_file = forms.FileField() class Meta: model = Posts fields = ['title', 'tag', 'date_time', 'description', 'post_file'] exclude = ['post_relation'] view.py @login_required(login_url='login_user') def post(request): user = request.user user_id = request.user.id post_form = PostForm() if request.method == 'POST': post_form = PostForm(request.POST, request.FILES) if post_form.is_valid(): post_file = post_form.cleaned_data.get('post_file') title = post_form.cleaned_data.get('title') tag = post_form.cleaned_data.get('tag') date_time = post_form.cleaned_data.get('date_time') description = post_form.cleaned_data.get('description') post_form.save() if not Posts.objects.filter(id=get_id): post_data = Posts(post_relation_id=user_id, title=title, tag=tag, date_time=date_time, description=description, post_file=path_post_file) post_data.save() else: return redirect("feed") return http.HttpResponseRedirect(reverse(f"user_profile", kwargs={"username": str(user.username)})) else: print("Post form is not valid!") return render(request, "includes/post_template.html", {'post_form': post_form}) post_template.html <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in post_form %} <div class="post_form_class"> {{ field.label_tag }} {{ field }} </div> {% endfor %} <button class="post_button" id="post_button_id" name="post_btn" type="submit">Done</button> </form> Parent template. {% include "includes/post_template.html" with post_form=post_form %} {% include "includes/post_template.html" only … -
Getting a 404 page not found, The current path, product/, matched the last one
urls.py from django.urls import path from . import views urlpatterns = [ path('', views.product, name='products-page'), path('add-product', views.ProductAddView.as_view(), name='add-product'), path('<int:pk>/delete/', views.ProductDeleteView.as_view(), name='product-delete'), # path('product/<int:id>', views.product_detail, name='product-detail-page'), # path('product/<int:pk>', views.SingleProductView.as_view(), name='product-detail-page'), path('<int:pk>/', views.ProductUpdateView.as_view(), name='product-update'), ] Views.py def product(request): try: products_all = Product.objects.all() num_products = products_all.count() product_dict = { "data":products_all, "total": num_products } return render(request, 'products/product.html', context=product_dict) except: # Http404 will automatically look for a 404 html in templates raise Http404() Seems to be something related to the query to the database. If I print the results to the console and remove the results from the context, the page loads. -
How to remove the default "Successfully deleted ..." message for "Delete Selected" in Django Admin Action?
In the overridden delete_queryset(), I deleted loaded messages and added the new message "Deleted successfully!!" as shown below: # "store/admin.py" from .models import Person from django.contrib import admin, messages @admin.register(Person) class PersonAdmin(admin.ModelAdmin): def delete_queryset(self, request, queryset): msgs = messages.get_messages(request)._loaded_messages # Delete loaded messages for i in range(len(msgs)): del msgs[i] # Add a new message self.message_user(request, "Deleted successfully!!", messages.SUCCESS) queryset.delete() Then, when clicking Go to go to delete the selected persons as shown below: Then, clicking Yes I'm sure to delete the selected persons: But, the default message "Successfully deleted 2 persons." is not removed as shown below: So, how can I remove the default message for Delete Selected in Django Admin Action? -
How to save div elements in form post
I have a form currently with a text area. However, I want it to have rich-text formatting (bold, bullet points etc..) and for that, I have found Quill, which is amazing. I'm not sure how to get the contents of div id=editor and save that to the Django function, because it won't be part of the post, will it? <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet"> <!-- Create the editor container --> <div id="editor"> <p>Hello World!</p> <p>Some initial <strong>bold</strong> text</p> <p><br></p> </div> <!-- Include the Quill library --> <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script> <!-- Initialize Quill editor --> <script> var quill = new Quill('#editor', { theme: 'snow' }); </script> -
Redirect the user to the previous page which uses a Primary Key (PK)
I'm currently trying to create a form that, upon success, redirects the user to the previous page (which is using a PK key). Example of previous page : http://127.0.0.1:8000/object/update/8/ (1) What I tried: def get_success_url(self, **kwargs): return reverse_lazy('task_update:update', kwargs={'id': self.object.id}) (2) And currently I'm trying to load my form with the same pk than the precedent form (he don't need pk, example : http://127.0.0.1:8000/tag/create/8/) And then use that PK in the URL for load the precedent page like that : def get_success_url(self, **kwargs): return reverse_lazy('task_create', self.kwargs.get('pk')) but it generates an error : The included URLconf '8' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. The goal: Globally, users start at "http://127.0.0.1:8000/object/update/8/", then they press a button which redirects them to a new page to create a tag, and then they get redirected back to the first page. -
Python package for API development, testing and consume/invoke other APIs
I have been using Flask for API development for a while and requests module for test automation of APIs. I found lot of materials over internet but I am still bit confused about some of these fundamentals. If i need to develop API shall I use 'requests' module in python or that is only meant to use it for api testing/automation or just to call other apis ? is it always better to use frameworks like flask,fastapi, or Django to develop API in python platform ? and for example if I develop a API in flask and also I need a call another API within Flask, should I use the functionality of Flask to call external APIs or should I use 'requests' library only ? so some one who has well experienced all these frameworks suggest please .. thanks -
Validation message "Please fill out this field" displaying with <form novalidate>
I'm attempting to create a form with an <input type="text" /> field where client side validation is disabled with the novalidate keyword. Yet when the Enter key is pressed the Please fill out this field message is still displayed when no input value is provided. When a value is provided, the message is not displayed. How can the validation message be disabled for simply pressing Enter in the input box with no value? class UserSearchForm(Form): search = CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['search'].widget.attrs.update({ "placeholder": "Filter by user", "autocomplete": False, "required": False, }) <form id="api_user_search_form" novalidate> {% for field in form %} {{ field }} {% endfor %} </form> let form = document.querySelector("#api_user_search_form"); form.addEventListener("submit", function(event) { event.preventDefault() }) -
I am beginner to programming .I have started learning python and django. I want my dropdown to get data from my dataset
I'm trying to build a machine learning algorithm and then deploy it to my website using django.So here comes the problem I want drop downs on my forms and.Im using the select tag on html while creating my dropdown but it is very hectic to give each value/option individually.Is there anyway i could get my values from dataset in my dropdowns so i dont have to go through above process. I imported my model and done it successfully using streamlit.I am expecting to do same with my website that m building in django.I want those values from my dataset that i have loaded in my views.py to be diplay on my drop down. kindly help in this regard.[enter image description here](https://i.stack.imgur.com/Z6vmZ.png) -
How to get iteration number of outer loop jinja
I need to get the iteration number of the outer loop in jija templates, for example: {% for el in data %} {% if el == '' %} Nothing found. {% else %} Iteration {# here I need to get iteration number #}. Found {{ el }} {% endif %} {% endfor %} I tryed to use {% loop.index %} but I get this error: jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'loop'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'. -
django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query')
I create a django app to shared hosting. Everything is good but when i came to createsuperuser i see this problem... I made lots of things, i increased connect timeout and read timeout but nothing changed. How can i solve this? i made connect_timeout=100000, i made read_timeout=120, i tried to shell for create super user, i wrote username, no error, i wrote email, no error, i wrote pass and i got this error....