Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Allauth - Cannot retrieve profile picture from Facebook
I am trying to build a website and integrate it with Facebook to authenticate. I'm also trying to get the profile picture and show it in the website. As Django Authentication I'm using django-allauth. I managed to login in and authenticate with Facebook, however I seems to have an issue when trying to get the profile picture. I'm using this html code in my template: <img class="rounded-circle account-img center-align" src="{{ user.socialaccount_set.all.0.get_avatar_url }}" width="80" height="80"> Am I'm getting this picture. Any help please on what I'm doing wrong or maybe there is an alternative to get the profile picture of a user? Thanks -
Postman-django for messaging between users
I just installed postman-django so that site users can exchange messages, but after installation according to the instructions, everything that appears on the screen (attached), no response when pressed. Links such as for example {% url 'inbox'%} do not work, in the admin panel everything works there is an opportunity to compose messages. what are my next steps? -
One view for two models with redirect
I have Django app with the following model: class Author(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) This is now using simple generic view: class AuthorDetail(DetailView): model = Author def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # some additional context thingies return context and with the following URL configuration: path('author/<slug:slug>/', AuthorDetail.as_view(), name='author-detail'), Now I want to introduce simple aliases for authors, so for example instead of /author/william-shakespeare I can reach the page also as /author/ws or /author/my-favourite-author. I came up with this idea (I know that destination could be key to Author, but that (I think) would not change much in the case): class AuthorAlias(models.Model): slug = models.SlugField(max_length=200, unique=True) destination = models.CharField(max_length=200) So to achieve the redirect I came up with the following in the view: def get(self, request, **kwargs): slug = kwargs['slug'] try: self.object = self.get_object() except Http404: self.object = get_object_or_404(AuthorAlias, slug=slug) return redirect(reverse('author-detail', args=[self.object.destination])) context = self.get_context_data(object=self.object) return self.render_to_response(context) Everything seems to be working fine, but I was wondering it there is a better approach and if this approach can cause any issues I'm not seeing? -
adding a new path or something other that will work, pls help :(
So im trying t implement a feature to my project that will add a new article. Basically the project is creating my own wikipedia. I have been stuck on this problem for a few weeks so i really need help as i dont have unlimited amount of time. What i want to happen is after pressing a button in new article page it should "put" a link in the index page where all the links to articles are. views: from django.shortcuts import render from django.http import HttpResponse from . import util import random def index(request): entries = util.list_entries() random_page = random.choice(entries) return render(request, "encyclopedia/index.html", { "entries": util.list_entries(), "random_page": random_page, }) def CSS(request): return render(request, "encyclopedia/css_tem.html", { "article_css": "css is slug and cat" }) def Python(request): return render(request, "encyclopedia/python_tem.html", { "article_python": "python says repost if scav" }) def HTML(request): return render(request, "encyclopedia/HTML_tem.html", { "article_HTML": "game theory: scavs are future humans" }) def Git(request): return render(request, "encyclopedia/Git_tem.html", { "article_Git": "github is git" }) def Django(request): return render(request, "encyclopedia/Django_tem.html", { "article_Django": "this is a framework" }) def new_article(request): return render(request, "encyclopedia/new_article_tem.html", { "article_Django": "this is a framework" }) index: {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block … -
Flask UnboundLocalError
I have a simple flask application and there is an option to register in this application but I am getting the UnboundLocalError error. I did not understand this error and could not solve it please help. App: from flask import Flask,render_template,request,redirect import os,string from random import choices #from wtform_fields import * from datetime import datetime from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////storage/emulated/0/Download/mysite/site.db' db = SQLAlchemy(app) @app.route("/") @app.route("/home") def index(): return render_template("index.html") @app.route("/login") def login(): return render_template("login.html") @app.route("/register",methods=["GET","POST"]) def register(): error='' if request.method=="POST": username=request.form["username"] email=request.form["email"] password=request.form["password"] re_password=request.form["re_password"] # if not username or not email or not password: # error="" if username == "": error="Please , enter a username" elif password == "" or re_password == "": error="Please,enter a password" elif password != re_password: error="Passwords are not the same." elif email == "": error="Plesase, enter a email." else: check_mail=user.query.filter_by(email=email).first() check_user=user.query.filter_by(username=username).first() if check_user: error="This username already in use." elif check_mail: error="This email already in use." else: user=user( username=username, email=email, password=password, re_password=re_password ) db.session.add(user) db.session.commit() return render_template("register.html",error=error) class user(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(15)) email = db.Column(db.String) password = db.Column(db.String) def __repr__(self): return "<user(id='%s' , username='%s',email='%s',password='%s')> " % (self.id,self.username,self.email,self.password) if __name__=="__main__": app.run(debug=True) But I'm getting this error UnboundLocalError:Local variable … -
Delete file after updating or deleting a file or an image in Django
I have the following Django models: class Dealer(models.Model): user = models.OneToOneField(User,on_delete=models.PROTECT) kyc_verified = models.BooleanField('kyc status',default=False) aadhar = models.FileField(upload_to='aadhar_images/') pan = models.FileField(upload_to='pan_images/') Here kyc,aadhar and pan are file fields. When we update or delete record, how to delete the file corresponding after the db is updated or the record is deleted. Also, how to change the name of the file before saving the record. I am updating the record as follows: def update(request): if request.method=='POST': dealer = request.user.dealer if request.FILES.get('aadhar',None): dealer.aadhar = request.FILES['aadhar'] dealer.save() if request.FILES.get('pan',None): dealer.pan = request.FILES['pan'] dealer.save() if request.FILES.get('gts',None): dealer.gts = request.FILES['gts'] dealer.save() -
Custom from validation in ModelForm
I am new in Django and i start writing my first web application. https://ibb.co/jDPwSHG I want to make custom validation, for exemple winner cannot be also lost. How can i do that using ModelForm ? Can anybody show me a example of this solution ? -
Django | Decimal Field is required even tho i set it to NULL=True
im trying to play a little bit around with django but i have run into problems... I have a Decimal Field which is not required so i set it to "blank=True" and "null=True". But it still says its required :( Here is my models.py from django.db import models weightUnit = { ('kg' , 'kilogram'), ('g', 'gram'), ('t', 'tons'), ('n', '-'), } class Product(models.Model): pname = models.CharField( max_length=50, ) pdesc = models.TextField( max_length=5000, ) pprice = models.DecimalField( max_digits=6, decimal_places=2, ) psn = models.CharField( max_length = 30, null=True, blank=True, ) pweightunit = models.CharField( choices=weightUnit, default='n', null=True, blank=True, max_length=5, ) pweight = models.DecimalField( null=True, blank = True, max_digits=10000, decimal_places=2, ) plimage = models.ImageField( blank=True, null=True, ) -
Flask/Django modules of converting files [duplicate]
I'm trying to build a little converter website. pdf to docx, images to pdf, csv to excel etc... I really want to use node as my static files host server. But as I know node doesn't have that cool modules to handle such convertations. I think of using another server of python, e.g flask or django frameworks. So what are the best modules for python for converting files? Is there anything you could suggest me for solving this problem? -
Submit form with other modal forms Django
I'm trying to create an HTML page with a form, I have a button that open a modal with another form. The form within the modal is being submitted correctly but when I try to submit the other form the button doesn't send any request but I don't know why. I'm not very skilled using Django and HTML/JS so I could be missing something but I didn't have this problem on other pages. I'm also using crispy-bootstrap-forms. This is my HTML code: {% extends 'scenarios/home.html' %} {% load crispy_forms_tags %} {%block subtitle%} <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <h1 style="text-align:center"> Create your scenario </h1> {%endblock%} {% block body %} <div class="container"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{scenario_form|crispy}} <h1> VM List </h1> {%if vm_list%} <ul> {% for vm in vm_list %} <h3>{{vm.nome}}</h3> <span></span> <button> Edit Machine</button> {% endfor %} </ul> {% else %} <h2>No VMs at the moment</h2> {% endif %} <div class="container"> <!-- Trigger/Open The Modal --> <button type="button" class="btn btn-default btn-lg" id="myBtn">Add VM</button> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} … -
How can i use Uniqueconstraint for asymmetrical purposes?
How can i customize UniqueConstraint for this purpose: -user1 can follow user2. -user2 can follow user1. The problem right now is when user1 follows user2,user2 can't follow user1 because of unique constraint. Is there anyway to do it? class FollowUserModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user1 = models.ForeignKey(User,on_delete=models.CASCADE,related_name='followers') user2 = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') timestamp = models.DateTimeField(auto_now_add=True) class Meta: constraints = [models.UniqueConstraint(fields=['user1','user2'],name='unique_followuser')] -
How to include a variable in api call in python?
I am trying to implement a searchbar in django. I am getting the search input as movie_title from the html form. Now, how do i include it in my api call ? I tried with curly braces. Here's is the code def searchbar(request): if request.method == 'GET': movie_title = request.GET.get('movie_title') searched_movie = requests.get( 'http://www.omdbapi.com/?apikey=9a63b7fd&t={movie_title}') -
Flask/Django converting files
I'm trying to build a little converter website. pdf to docx, images to pdf, csv to excel etc... I really want to use node as my static files host server. But as I know node doesn't have that cool modules to handle such convertations. I think of using another server of y, e.g flask or django frameworks. So what are the best modules for converting files? -
django export to PDF using WeasyPrint working in development server whereas not working in production with "https"
I am trying to do Django export HTML containing image to PDF with WeasyPrint. IT is working fine in development server. whereas in production server, It is not showing image. it is showing TEXT content properly. I am using "https" . @login_required def html_to_pdf_view(request,bogId): bog = Brideorgroom.objects.get(bogId='bogId') html_string = render_to_string('brideorgroom/bogdetail_pdf.html', {'bog': bog}) base_url = request.build_absolute_uri() html = HTML(string=html_string, base_url=base_url) pdf_file = html.write_pdf() response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'attachment;filename="profile.pdf"' return response -
Tempus Dominus, Moments JS, Strftime and Timepicker in boot-strip modal forms
I have model called workshift with the fields work_shift , start, end, shift_hours and location. l want to use time picker for the fields start and end and calculate the shift_hours. Now instead of time picker only l get datetimepicker when l run the app. How do l get only time picker in the start and end forms fields? How do l calculated and display the results in the shift_hours forms fields anytime start and end time is picked? Below is my codes class WorkShift(BaseModel): work_shift = models.CharField(max_length=50, verbose_name='Work Shift', unique=True) start = models.TimeField(verbose_name='Start Time') end = models.TimeField(verbose_name='Closing Time') shift_hours = models.IntegerField(default=0, verbose_name='Shift Hours') location = models.ForeignKey(Location, on_delete=models.CASCADE, verbose_name='Shift Location') def __str__(self): return self.work_shift def save(self, force_insert=False, force_update=False, using=None, update_fields=None): user = get_current_user() if user is not None: if not self.pk: self.user_creation = user else: self.user_updated = user super(WorkShift, self).save() def toJSON(self): item = model_to_dict(self) item['start'] = self.start.strftime('%%H:%M:%S') item['end'] = self.end.strftime("%H:%M:%S") item['location'] = self.location.toJSON() return item class Meta: verbose_name = 'Wor kShift' verbose_name_plural = 'Work Shifts' ordering = ['id'] form.py class WorkShiftForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = WorkShift fields = '__all__' widgets = { 'work_shift': TextInput(attrs={ 'class': 'form-control', }), 'start': TimeInput( format='%I:%M %p', attrs={ 'value': … -
django: Pass additional data to context in FormView
I’m new to this forum and this is my first question, so please be kind Before I state my question, here is the code to the regarding model, form, view and template class Medium(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) dateiname = models.CharField(max_length=100) dateipfad = models.CharField(max_length=100) MEDIEN_TYP = ( ('f', 'Foto'), ('v', 'Video'), ('d', 'Dokument'), ) typ = models.CharField( max_length=20, choices=MEDIEN_TYP, blank=True, default='Foto') URHEBER_NAME = ( ('a', 'Person A'), ('b', 'Person B'), ) urheber = models.CharField( max_length=20, choices=URHEBER_NAME, blank=True, default='Person A') datum_erstellung = models.DateField( null=True, blank=True, verbose_name='Erstelldatum') personen = models.CharField( max_length=100, null=True, blank=True, verbose_name='Person(en)') ort = models.CharField(max_length=20) inhalt = models.CharField( max_length=100, null=True, blank=True, verbose_name='Inhalt/Anlass') kommentar = models.TextField(max_length=1000, null=True, blank=True) rating = models.DecimalField( max_digits=3, decimal_places=2, null=True, blank=True) def get_absolute_url(self): return reverse('medium-detail-view', args=[str(self.id)]) def __str__(self): return self.dateiname class AbfrageForm(forms.Form): medien_typen = ( ("f", "Foto"), ("v", "Video"), ("d", "Dokument"), ) medien_typ = forms.ChoiceField(choices=medien_typen) personen = ( ("Person X", "13: Person X"), ("Person Y", "14: Person Y"), ("Person Z", "14: Person Z"), ) vorname = forms.ChoiceField(choices=personen) orte = ( ("Place A", "Place A"), ("Place B", "Place B"), ) ort = forms.ChoiceField(choices=orte) class AbfrageView(LoginRequiredMixin, FormView): template_name = 'abfrage.html' form_class = AbfrageForm success_url = '.' def get_context_data(self, **kwargs): context = super(AbfrageView, self).get_context_data(**kwargs) #context['auswahl'] = self.auswahl return context … -
Is there any possible way to deploy Django app without "setup python app" feature in Cpanel?
I was trying to deploy my Django app on a Hostgator Cpanel. But there is no "set up python app" feature present on my Cpanel. I have come to know that I have to buy the CloudLinux feature to get that. Is there any way to set the application root, startup file, and other things provided by that(including starting and stopping my app anytime) to run my Django app? -
accessing context data in a class
I want to use DeleteView for different cases instead of rewritting a new function for every case. So I thougt I pass the model as an argument in the url and then select wich delete to use by overiding the get_context_data function. My problem is how to access the context variable: views.py: class PDelete(DeleteView): template_name='kammem/delete.html' if context['model']=='Person': model=Person success_url=reverse_lazy('personer') elif context['model']=='Concert': model=Concert success_url=reverse_lazy('concert') def get_context_data(self,**kwargs): context=super().get_context_data(**kwargs) context['model']=self.kwargs['model'] return context urls.py path('pdelete/<int:pk>/<str:model>',PDelete.as_view(),name='pdelete'), the problem is that the context variable is undefined in the class. Any suggestions? -
attribute Error using django Model Forms choicefield
I am trying to use ChoiceField in ModelForms follow is my code in forms.py Format_Choices=[('Line Numbering','Line Numbering'),('Header Numbering','Header Numbering')] class EstimateForm(forms.ModelForm): class Meta: model=Estimate estimateFormat=forms.ChoiceField(choices=Format_Choices,widget=forms.RadioSelect()) this form is link with following estimate model in models.py class Estimate(models.Model): estimateFormat=models.CharField(max_length=25,default='Line Numbering') in the template when I use {{form.estimateFormat| as_crispy_field}} it generate following error |as_crispy_field got passed an invalid or inexistent field which field should I use in models.py to make ChoiceField compliant with models.py -
What event.target will contain if I added submit event listener on the form
I have a lot of forms on the page and when one of them is submitted I want to send request via ajax to the view and have an id of the article and other info. So I need to check if form that has been clicked is the same as event.target. I did something like this but don't know if it is correct(first console.log works but second not): <div id = "list"> {% for article in news %} <a href="{{ article.resource }}"><h1>{{ article.title }}</h1></a> <p>{{ article.published }}</p> <img src = "{{ article.url }}"> <p> <button><a href="#" class="vote" id="{{ article.id }}" action = "upvote">Upvote</a></button> <button><a href="#" class="vote" id="{{ article.id }}" action = "downvote">Downvote</a></button> </p> <div id="span"> {% with article.upvotes.count as total_upvotes and article.downvotes.count as total_downvotes %} <span upvote-id = "{{ article.id }}">{{ total_upvotes }}</span><span> upvote{{ total_votes|pluralize}}</span> <span downvote-id = "{{ article.id }}">{{ total_downvotes }}</span><span> downvote{{ total_votes|pluralize}}</span> {% endwith %} </div> <form method = 'post' action = '{% url "news:news_list" %}' form-id = '{{ article.id }}' class="form"> {{ form.as_p }} {% csrf_token %} <input type = "submit" value = "post"> </form> {% endfor %} </div> {% endblock %} {% block domready %} const list = document.getElementById('list'), items = document.getElementsByClassName('vote'); forms = … -
How to "add another row" in Django on change input
I am using TabularInline formset in admin view with extra=1 to have only a row of formset. I wish to automatically add a row (like when I click on "add another row") when a row is filled, that means using "on change". To do that I tried to intercepet onChange input overwriting change_form.html in this way: $(document).on('change', '#myform_set-group .field-mymodel select', function () { // test console.log("changed!"); // I tried this $('#myform_set-group tbody tr.add-row').formset(); // and this $('#myform_set-group tbody tr.add-row').click(); // and this $("#myform_set-group .tabular.inline-related tbody tr").click(); // and this $("#myform_set-group .tabular.inline-related tbody tr").formset(); }); but don't work -
Dots and boxes solving algorithm/heuristic
I'm currently working on a "dots and boxes" program and I can't make good algorithm(heuristic). Can anyone help me or does anyone have a code in python? -
python manage.py runserver: TypeError: argument 1 must be str not WindowsPath
I am following up a django tutorial and I have just installed django using 'pip install django=2.1' and it was successfully install and then created a project using 'django-admin startproject pyshop .' after that I am trying to runserver using 'python manage.py runserver' and I am getting a 'TypeError: argument 1 must be str not WindowsPath'. Am i missing something. Please help! -
( Python ) { MCQ } What advice would you give to this company about the user interface for this appliction?
{ Python } (MCQ) A company uses an offline system order for selling products. The company wants to build a new online site. The data trends of current order shows that customers typically buy once or twice a year. The company has the following requirement for the site. Should have ability to shop quickly from application Should have ability for the web designers to modify the user interface to provide a new user experience There should be ability to browse the catalog and find the product with 3 clicks What advice would you give this company about the user interface for this application? -
Multiple Choice with django
Im working on a quiz application with Django. Im struggling with making a form that can act as the multiple choice. I have to pull the questions and answers from the database so, i then display them on the page. I was going to just put booleanfield checkboxes beside the displayed choices, is there a better way to do this? I recently became aware of the multiple choice field, but i believe it aids in displaying the choice as well. I just want there to be 'boxes' i can customize with css. Is there anyway to have the field pull from the database or can i use the multiple choice field to display the wanted boxes by the answer choices already displayed.