Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Invalid block tag on line 17: 'provider_login_url', expected 'endblock'. Did you forget to register or load this tag?
I am using the following tutorial:. As the topic name suggests , I got an error : Invalid block tag on line 17: 'provider_login_url', expected 'endblock'. Did you forget to register or load this tag? The following div has the error . <div class="signin text-center"> <a href="{% provider_login_url 'google' %}" class="text-dark"> <!--Error is here--> <img src="{% static "btn_google_signin_light_normal_web@2x.png"%}"style="width:14rem; height:auto"> </a> </div> Thanks. -
How can i send mail form submittion in Django
I want to send the data I added to the table as an e-mail at the same time, how can I do this? When i put the "send_mail(adsoyad, aciklama, alinanaksiyon, ['admin@example.com'])" after try methot in view its getting error with definitions. views; from django.core.mail import send_mail def gcreate(request): if request.method == 'POST': gmember = gunluk( adsoyad=request.POST['adsoyad'], adsoyad2=request.POST['adsoyad2'], vardiya=request.POST['vardiya'], aciklama=request.POST['aciklama'], incident=request.POST['incident'], alinanaksiyon=request.POST['alinanaksiyon'], ulasilmayanekip=request.POST['ulasilmayanekip'], ulasilmayanbilgisi=request.POST['ulasilmayanbilgisi'],) try: gmember.full_clean() send_mail(subject, message, from_email, ['admin@example.com']) except ValidationError as e: pass gmember.save() messages.success(request, 'Ekleme İşlemi Başarılı!') return redirect('/gunlukistakibi') else: return render(request, 'gcreate.html') settings.py; EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'XX' EMAIL_HOST_PASSWORD = 'XX' -
pivottable.js not showing properly in django project
I am testing pivottable.js in a django project, here is the code I am using in the HTML template: {% load static %} {% block content %} <script src={% static 'js/jquery-3.6.0.min.js' %}></script> <script src={% static 'js/jqueryui/jquery-ui.min.js' %}></script> <script type="text/javascript" src={% static 'pivot/dist/pivot.min.js' %}></script> <script type="text/javascript"> $(function() { $("#output").pivotUI( [ {color: "blue", shape: "circle"}, {color: "red", shape: "triangle"}, {color: "red", shape: "triangle"}, {color: "red", shape: "circle"}, {color: "red", shape: "circle"}, {color: "red", shape: "triangle"}, ], ); }); </script> <div id="output" style="margin: 10px;"> </div> {% endblock %} The following is the output: Any idea why it is not showing properly like the screenshot below from the website? Even though, I have all the files of the pivottable.js project locally in my django project? -
makemigration - Create model and insert data only once
I've a model as below: from django.db import models class Country(models.Model): cid = models.SmallAutoField(primary_key=True) label = models.CharField(max_length=100) abbr = models.CharField(max_length=3) countries = { "AFG": "Afghanistan", "ALB": "Albania", "DZA": "Algeria", "ASM": "American Samoa", "AND": "Andorra", "AGO": "Angola", "AIA": "Anguilla" }; for c in countries: row = Country(label = countries[c], abbr = c) row.save() Now whenever I run the following command: python manage.py makemigrations The first time, it creates the table and populates it. The 2nd, 3rd and so on times, it keeps inserting the same data (It is definitely possible that I will be using the makemigration command many times, so I don't want it to insert it everytime the command is run) Any way to achieve this? Create and insert once? -
Please how can I create url using slug in my url.py django 3?
I am sorry for long explanation I am newbie to Django and come across a book titled "Tango with Django" version 1.9 but I am coding mine in the latest version of Django i.e 3.2. But when I came to chapter 6 I get stucked because slug. I tried my level best to resolve but merely spent hours without anything. So this is a brief of what I want to do, I have a django project called tango_with_django_project, and I created new app called rango so inside the rango app in mode.py I created my models including slug. The problem I am getting is whenever I write the route in urls.py it raises an exception of TypeError at /rango/category/other-frameworks/ cannot unpack non-iterable Category object Request Method: GET Request URL: http://127.0.0.1:8000/rango/category/other-frameworks/ Django Version: 3.2.7 Exception Type: TypeError Exception Value: cannot unpack non-iterable Category object Exception Location: C:\Users\Userpc\code\env\lib\site-packages\django\db\models\sql\query.py, line 1283, in build_filter Python Executable: C:\Users\Userpc\code\env\Scripts\python.exe Python Version: 3.8.5 Python Path: ['C:\Users\Userpc\code\tango_with_django_project', 'C:\Program Files (x86)\Python38-32\python38.zip', 'C:\Program Files (x86)\Python38-32\DLLs', 'C:\Program Files (x86)\Python38-32\lib', 'C:\Program Files (x86)\Python38-32', 'C:\Users\Userpc\code\env', 'C:\Users\Userpc\code\env\lib\site-packages'] Server time: Sat, 16 Oct 2021 14:20:06 +0000 #my urls.py from django.urls import path from rango import views urlpatterns = [ path('', views.index, name='index'), path('about/', views.about), path('index/', … -
Create django query from string
I have a list of strings that come in a strange format like this: OR(EQUAL(id,111),EQUAL(id,222)) AND(EQUAL(id,333),EQUAL(name,"John")) I want to parse these strings and run them as a filter in Django like this: from django.db.models import Q People.objects.filter(Q(id=111) | Q(id=222)) People.objects.filter(Q(id=333) & Q(name="John")) Is there a parser that can help me with this? Or would I have to write one from scratch? -
OperationalError (1366, "Incorrect string value: '\\xE2\\x80\\x8ESen...') MySQL Django
I develop django website on cpanel with MySQL database. I have a function that pull feeds from this website https://travelcommunication.net/feed/ and create an object from that (web scraping using beautifulsoup4). But when I try to grab the content section, the error appears. But that only happens with certain items, not all. I try on my local (with sqlite database) and all working fine. I have also tried on heroku (with PostgreSQL database) and all working fine. Here is my code: #views.py def pull_feeds(request, pk): if request.user.is_superuser: source = Autoblogging.objects.get(pk=pk) url = requests.get(source.url) soup = BeautifulSoup(url.content, "html.parser") length = source.items items = soup.find_all('item')[:length] contents = soup.find_all('content:encoded')[:length] for i in range(length-1, -1, -1): content = contents[i].text title = items[i].title.text body = content[content.find('<p>'):] #the problem is here .. when i comment this, everything works fine category = Category.objects.get(pk=source.category.id) if not Post.objects.filter(title=title).exists(): post = Post(title=title, body=body, #the problem is here .. when i comment this, everything works fine category=category) link = content[content.find('src=')+5:content.find('alt')-2] img_data = requests.get(link).content with open('temp_image.jpg', 'wb') as handler: handler.write(img_data) with open('temp_image.jpg', 'rb') as handler: file_name = link.split("/")[-1] post.cover.save(file_name, files.File(handler)) os.remove("temp_image.jpg") return redirect("news:autoblogging") else: return HttpResponse("Sorry you are not allowed to access this page") Does anyone know how to fix this error? Thanks. -
What should be the error code 400 or 500, for the given scenario?
I am just starting on Django rest framework and i was creation a function based Rest API as below: @api_view('POST') def temp_view(request): #do something ..... ..... ..... command to copy a static file from a server if command fails: return Response ..... ..... return Response If my API fails at the 'copy command line' then what should be the status code for the response(400 or 500). And if 500 should i send error message as: command to copy ...file failed or is this not recommend to share any message with 500 error code? I know its a very naive question but i am bit confused. Thanks in advance. -
ChoiceFields to give two different forms or different fields in html template and django
I am trying to make a registration form for a dentist and a student, where I have a choice field for a dentist and a student. What I want to happen is, when dentist is picked, I should be able to see the specialties field in the html as well as Django to pick that form, and for student, to pick student_email and institution. I am confused to how to write its code in the template and I looked almost everywhere and couldn't find anything that could help with what I want. I also included an image with what the registration image looks like. form.py from django import forms from django_countries.fields import CountryField class RegistrationForm(forms.Form): Specialties = [ ('pediatric','Pediatric'), ('oral surgeon','Oral Surgeon'), ('periodontist','Periodontist (Restorative; Esthetic)'), ('orthodontist','Orthodonsit'), ('endodontist','Endodontist'), ('prosthodontist','Prosthodontist'), ('oral pathologist','Oral Pathologist'), ('oral radiologist','Oral Radiologist'), ('public health dentist','Public Health Dentist'), ('research and academics','Research and Academics'), ] username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), required=True, unique=True) email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}), required=True, unique=True) student_email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}), required=True, unique=True) password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}), required=True) password_repeat = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}), required=True) first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), required=True) last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), required=True) date_of_birth = forms.DateField(label = "Date of Birth", widget=forms.SelectDateWidget([x for x in range(1920,2021)]), required=True) country = CountryField().formfield(required=True) gender = forms.ChoiceField(widget=forms.RadioSelect, choices=[('male','Male'),('female','Female')], required=True) specialty = forms.CharField(widget=forms.Select(choices= … -
"https" in URL but "http" in google search results
I've added a free Let's encrypt SSL certificate using certbot(nginx) to my site. Everything works fine but in google search results my site url is displayed as "http://example.com" but when I open the link, in the page url it is displayed as "https://example.com". How do I get it to display the same https url in google search results. I am provinding my nginx server config. server { server_name domain.com www.domain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/nithish/myproject/home; } location /media/ { root /home/nithish/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/nithish/myproject.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.domain.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = domain.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name domain.com www.domain.com; return 404; # managed by Certbot } -
Integrating Pivottable.js with django
I am trying to use pivottable.js in my django project to explore the data that I have stored in the django model called "Interview". in views.py: from pivottablejs import pivot_ui qs = Interview.objects.all().values() df = pd.DataFrame(qs) pv = pivot_ui(df) return render(request, 'table.html', {'pivot': pv}) Can you help me with the code to render the pivot table in 'table.html'? -
Django wrong url?
I have two urls.One is for blogs and the other is for games.I have app for games and blogs. path('',include('games.urls')), path('blog',include('blogs.urls')), My gameapp url is like this: path('<slug:platform>/<slug:slug>',views.oyun,name='detail'), My blogapp urls are like this: path('', views.blogs, name='blog'), path('/<slug:slug>', views.blog_id, name='blog_id'), This url is going to(path('/<slug:slug>', views.blog_id, name='blog_id')), views.oyun so it is giving error. How can i solve this? -
Import model from another project
I have 2 Django projects with their Postgres databases. And they run on two different servers. They are models in each project which is usable by both projects. How can I import the model of Project1 in Project2? Regards, Gegham -
why do I get this Uncaught Typeerror error?
I have js code to update the cart, it works when the cart is on the same page as the add to cart button, but when the cart is on a different page it I got Uncaught Typeerror: cannot read property 'innerHTML' of null error. -
How to create multiple types of users using OneToOne field in Django?
I want to create 2 types of users - Customer and Company. I've already created a custom user shown below. These are their model files - class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, is_staff=False, is_superuser=False, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', is_staff) extra_fields.setdefault('is_superuser', is_superuser) return self._create_user(email, password, **extra_fields) class User(AbstractUser): """User model.""" username=None contact = models.CharField(max_length=100) USERNAME_FIELD = 'id' REQUIRED_FIELDS = ['password'] objects = UserManager() class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=100) email = models.EmailField(_('email address') class Company(models.Model): """User model.""" user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company_name = models.CharField(max_length=100) company_email = models.EmailField(_('email address'), unique=True) I'm stuck at creating the serializer file. Most of the other answers use forms for creating multiple types of users, but I just want to create an API. Can anyone help me to create the serializer file for this? class UserListSerializer(serializers.ModelSerializer): class Meta: model = User … -
Upload, read an excel and save values in DB using Python and Django framework
How to save values to database after reading all the Excel data Is there any way By Defining a template to accept in excel -
Heroku not accepting Django app ! [remote rejected] main -> main (pre-receive hook declined)
I got the ! [remote rejected] main -> main (pre-receive hook declined) My app was made in Django and I put Django==3.2.5 Jinja2==2.11.2 in my requirements.txt file; the build is Python. In the error message it also said: App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz I don't understand what this means. Isn't Heroku the host you are supposed to use with Django apps? I didn't use any other apps. I also use some Javascript, is that a problem? Please help; I really have no idea how to make this work. -
How to pass all value from one page to another page efficiently/elegantly in django
Well I am working on a project where there were multiple pages, now in django usually capture individual values and then pass it to next page via context parameter. For example if we want to go from page1 to page2, I would do something like this. from django.shortcuts import render def page1(request): value1 = request.session["value1"] value2 = request.session["value2"] context = {"value1":value1,"value2":value2} return render(request, "page2.html", context) Now this solution is working, but as the project grows number of variable is increasing day by day and in each page we have to capture the values and pass it to next page. And in the last page we are storing in the database. Is there any elegant way to pass the entire dataset or entire request to the next page so that and then the next page till the last page. In the last view will get the individual values and save it in database. Hope I am able to express my issue. Note:- There might be a scenario where the variable passed by page1 will be displayed in page2 HTML file (using jinja). -
Cannot connect to amqp://guest:**@127.0.0.1:5672//:
I want to create a progress bar for one of my functions. I call this function in views. I research and find that I should use Celery to make a progress bar. (I am doing some download processes and the user should track it) I found a tutorial and try to do the same but I get an error: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [WinError 10061] When target machine actively rejects n connection failed. I am developing this app in localhost and I am using sqlite for db. Where is my mistake and what should I do? settings.py ... CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_BACKEND = 'django-db' CELERY_BROKER_URL = '127.0.0.1' functions.py class myFunction(): def __init__(self, user, password, url, port, db_password, username): .... @shared_task(bind=True) def send_download(self): progress_recorder = ProgressRecorder(self) for in_file in glob.glob(self.location + "\*\*.xyz"): try: i = 0 progress_recorder.set_progress(i+1, len(array), f'On iteration {i}') with open(in_file) as f: if os.path.getsize(in_file) > 0: ... function... time.sleep(0.02) i = i + 1 except: pass .... views.py ... task = (functions.myFunction(setup.username, setup.password, setup.url, setup.port, setup.db_password, username=request.user.username)) -
Multiple different foreign objects as "resources"
So say I have a model, Agenda: class Agenda(models.Model): ... resource_comments = models.Field... class ResourceComment(models.Model): comment = models.TextField() resource = models.ForeignKey... | GenericRelation Say I wanted resource_comment to be one or more of several other models, like.. Restaurant, PetrolStation, CarPark with a comment. So in a meeting agenda we might want to talk about a particular restaurant and a couple of petrol stations nearby. Whatever, it's a usecase. How would I go about this? Should I have a separate field for each..? That doesn't feel quite right... like I don't want class Agenda(models.Model): ... restaurants = models.... parking_lots = models.. petrol_stations = models.. ... I suppose I could have a model like... class Resource(models.Model): resource_id = Int resource_model = String # (e.g. Restaurant) comment = String # (a comment pertaining to resource from having the agenda meeting) Kind of also feels off as I then have to manually get the objects.. Like get restaurants_in_agenda(self): ids = self.filter(resource_model="Restaurant").value_list('ids') return Restaurant.objects.filter(id__in=ids) Or, is this OK? Another solution would be to make the Agenda the generic model, but I kind of don't want this field on all the business models... because.. what do I do then with the resource comment? class Agenda(models.Model): attendants … -
Django Model not recognising model fields using Serialiser Class Generic Views
I am trying to get a list of templates from a Django model, but I always get an error. Below is the error whenever I attempt to retrieve the list of job templates. I get this error because it doesn't recognise the field template_name. AttributeError: Got AttributeError when attempting to get a value for field template_name on serializer ListJobTemplateSerializer. | The serializer field might be named incorrectly and not match any attribute or key on the Job instance. | Original exception text was: 'Job' object has no attribute 'template_name'. Job Model: class Job (Dates, ID): name = models.CharField(max_length=255, validators=[name_validation]) is_remote = models.BooleanField(default=False) company = models.ForeignKey(to="companies.company", related_name="%(class)s", on_delete=models.CASCADE) Template Model: class JobTemplate(Dates, ID): template_name = models.CharField(max_length=255) jobs = models.ForeignKey(to="jobs.Job", related_name="%(class)s", on_delete=models.CASCADE) objects = BulkUpdateOrCreateQuerySet.as_manager() class Meta: db_table = 'job_template' def __str__(self): return name class ListJobTemplateSerializer(serializers.ModelSerializer): """List all templates of a job.""" job_title = serializers.CharField(source="name") class Meta: model = JobTemplate fields = ["id", "job_title", "template_name"] -
Django Form make calculations
Hi, a im new in Django. My first application is a simulator for bank loan, just for learn, not professional. I have created in models.py a class named EntradasMaisAlimentos with the following struture: class EntradasMaisAlimentos(models.Model): valor = models.DecimalField(max_digits=7, decimal_places=2, blank=False, default=0.00) divisao = models.DecimalField(max_digits=7, decimal_places=2, blank=False, default=0) carencia = models.PositiveIntegerField(default=0) taxa = models.DecimalField(max_digits=7, decimal_places=2, blank=False,default=0.0) Than i write in forms.py: from django import forms from .models import class simulaForm(forms.ModelForm): class Meta: model = EntradasMaisAlimentos fields='__all__' The form is rendered for: from django.shortcuts import render from django.http import HttpResponse from PronafMaisAlimentos.forms import simulaForm def index(request): dadossimulacao=simulaForm() dados={ 'dadossimulacao': dadossimulacao } return render(request, 'index.html', dados) Please, dont think it is a silly question, but how i can get the values inserted in form input by the user and make some calculations and than show the results in a new template named results.html? -
Data Exploration in django
I am new to django and just started building a database of some data I have. The next step would be to create a GUI that allows the user to explore the data from the database models. I was doing some research online and came across pivottable.js https://github.com/nicolaskruchten/pivottable , which allows the integration of pivot tables and charts, which seems like a decent solution, instead of building the GUI from scratch! How can Integrate it in my django project? -
why use put method if I can use post
how exactly http methods work. the both view function do the same thing django code: //post method def create1_post(request): if request.method=="POST": any_model=AnyModel(title="example") any_model.save() //put method def create2_post(request): if request.method=="PUT": any_model=AnyModel(title="example") any_model.save() I read a lot about http methods ,But all I learned is PUT method is for update or create resource and POST method is for create resource Now I am confused . if I can edit and create models with python why I need to use put or any other http methods -
Save different instances on different get request in ajax
I am building a simple blog app and I made a view to save the instance or update the instance in model field. So, I am getting request.GET of button But It was working only when clicks on that particular class. so, I made a another elif statement to get another button But it is not working second not first. What I am trying to do ? :- I am trying to update the instance in model on different button click, like first button will update "First" in model and second button will update "Second" in model. models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=1000) recommend_name = models.CharField(max_length=1000) views.py def save_instance(request, user_id): profile = get_object_or_404(Profile, user=user_id) if request.GET.get('submit') == 'first': profile.recommend_name = "First" profile.save() return redirect('home') elif request.GET.get('submit_2') == "second": profile.recommend_name = "Second" profile.save() return redirect('home') template.html <form method="GET" class="myForm" action="{% url 'save_instance' user.id %}" data-pk="{{ user.id }}"> <span id="idForm{{user.id}}"> <button type='submit' name="First">Save First</button> </span> </form> <form method="GET" class="second_form" action="{% url 'save_instance' user.id %}" data-pk="{{ user.id }}"> <span id="second_form{{user.id}}"> <button type='submit_2' name="second">Save First</button> </span> </form> <script> document.addEventListener('DOMContentLoaded', function() { window.addEventListener('load', function() { $('.unpro').submit(function(e) { e.preventDefault(); let thisElement = $(this) $.ajax({ url: thisElement.attr('action'), data: {'submit': 'first'}, dataType: 'json', method: …