Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
weasyprint with django renders digits as images
I'm trying to print an invoice using python-django 3.0.5 and django-weasyprint 1.0.1, using the base method described here. Both my static files and my stylesheets are loaded correctly. Returning my generated html string as normal django HttpResponse works fine. However, rendering my content to PDF always renders every digit as low-res image like below: The numbers are generated as regular text, I would expect them to be rendered as regular text using the same font as the letters around them. Did I miss a setting? Or is this a bug? -
ImportError: cannot import name 'login' from 'django.contrib.auth.views' [duplicate]
My Code : from django.conf.urls import url from . import views from django.contrib.auth.views import login app_name='accounts' urlpatterns = [ url(r'^$', views.home , name='home'), url(r'^login/$' , login , {'template_name':'login.html'}) ]' And Error: ImportError: cannot import name 'login' from 'django.contrib.auth.views' (C:\Python\Notes\lib\site- packages\django\contrib\auth\views.py) -
How to store a large number of keys/codes in a database. DJANGO
Let me explain. I've built a website using python, django. One of the issues i've run into now is i'm not sure how i should go about this. Every user on the website will be uploading a LARGE amount of basically keys/codes onto the website which will be linked to their accounts. It will be in the thousands per user. I'd imagine having a row for every single key/code is not efficient at all. Is there maybe any way to store lists or something similar? If i have a row per code/key after only 100 users it would be up in the hundreds of thousands rows. -
how to make a form field exact?
In django how to make form field exact, i.e it will have choices? My forms.py: from django import forms class FilterForm(forms.Form): category = forms.CharField() price = forms.IntegerField() My models.py: CATEGORY_CHOICES = ( ('Fruits and Vegetables', 'Fruits and Vegetables'), ('Electronics', 'Electronics'), ('Clothing', 'Clothing'), ('Books', 'Books'), ) class Item(models.Model): title = models.CharField(max_length=120) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=120, null=True, blank=True) image_url = models.CharField(max_length=2083, null=True, blank=True) slug = models.SlugField(null=True, blank=True) description = models.TextField(null=True, blank=True) -
How to avoid page reloading in my django front end?
every time I press submit button page gets reloaded.I have included preventdefault on submit.But it is not working. Please help me. This is part of html code . Every time on submit I got redirected to another page. I don't want page to reload. How to fix this. <form id='form' method="POST"> {% csrf_token %} {{form.as_p}} <input type='hidden' id='myusername' value='{{user}}'> <input type="submit" class='btn btn-primary'> </form> {% block script %} <script src='https://cdnjs.cloudflare.com/ajax/libs/reconnecting-websocket/1.0.0/reconnecting-websocket.js'></script> <script> var loc=window.location var wsStart='ws://' var formData=$("#form") var me=$("#myusername").val() var Holder=$("#items") var msgInput=$("#id_message") if(loc.protocol=='https:'){ wsStart='wss://' } var endpoint=wsStart + loc.host + loc.pathname+'/' var socket=new ReconnectingWebSocket(endpoint) socket.onmessage=function(e){ console.log('message',e) var Data=JSON.parse(e.data) chatHolder.append('<li>'+Data.message+' via '+Data.username+'</li>') } socket.onopen=function(e){ console.log('open',e) formData.submit(function(event){ event.preventDefault() var msgText=msgInput.val() var finalData={ 'message':msgText } socket.send(JSON.stringify(finalData)) formData[0].reset() }) } socket.onerror=function(e){ console.log('error',e) } socket.onclose=function(e){ console.log('close',e) } </script> {% endblock %} -
How to make a field dependant on another field inside one model in django
I would like the field joinkey pass the primary key of the project into the function random_int to generate a default joinkey for every new model being created. Is there a way to do this or am I approaching this problem the wrong way? class Project(MainAbstractModel): users = models.ManyToManyField(User) title = models.CharField(max_length=25, default="") joinkey = models.IntegerField(default=random_int(self.pk)) def other_user(self): return self.users.exclude(username=user.username) -
How can use Facebook login only from Django-allauth
I want to know how I can use only the facebook login method from django-allauth package and the rest to keep my login and register models that I customized for my need! Just facebook login! Thanks! -
jQuery and HTML, how to use localstorage in dropdown toggle menu
I have a question for you. I'm trying to use localstorage in my dropdown toggle menu. I have the following HTML code: <li class="nav-item" id="sidebar"> <a class="sidebar-heading" href="#thirdSubmenu" data-toggle="collapse" class="dropdown-toggle">Anagrafica</a> <ul class="collapse list-unstyled" id="thirdSubmenu"> <li> <a class="nav-link" href=""> <span data-feather="database"></span> Categorie Materiale</a> </li> <li> <a class="nav-link" href=""> <span data-feather="database"></span> Sottocategorie Materiale</a> </li> .. I want that, when I click on Anagrafica and dropdown menu is opened, when I update my page it remains open too, storing if the dropdwon was opened or not. I'have tried the following code but does work. I'm not good at jQuery, so I hope that someone of you could help me. Here my jQuery code: $("#thirdSubmenu li a").on("click", function() { var container = $(this).closest("li"); var selected_item_index = $("#thirdSubmenu li a").index(container); localStorage.setItem("sidebar_selected", selected_item_index ); }); $(function() { $("#thirdSubmenu li").eq(parseInt(localStorage.getItem("selected_item_index "))).addClass("active"); }); -
how to retrive data as list in django database
I am trying to get a list of questions that i have stored in database in django.While retriving i am getting a list of quetions queryset something like below on browser Output <QuerySet [<Question: what is your name ?>, <Question: what is sky color ?>, <Question: which mobile used ?>]> needed output only questions My Code: models.py class Question(models.Model): question=models.CharField(max_length=50) def __str__(self): return self.question class Choice(models.Model): choice1=models.CharField(max_length=20) choice2=models.CharField(max_length=20) choice3 = models.CharField(max_length=20) choice4 = models.CharField(max_length=20) question = models.ForeignKey(Question, on_delete=models.CASCADE) html page <div> {{q}} <div> admin.py from django.contrib import admin from .models import GeeksModel, Question,Choice # Register your models here. admin.site.register(GeeksModel) #admin.site.register(Choice) class ChoiceInline(admin.StackedInline): model = Choice extra = 0 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question']}), ] inlines = [ChoiceInline] admin.site.register(Question, QuestionAdmin) views.py def Quetionpaper(request,id): # dictionary for initial data with # field names as keys # add the dictionary during initialization q=Question.objects.all()[0:3] c=Choice.objects.all() context = {'q':q,'c':c} return render(request, "list_view.html", context) -
Extending ObtainJSONWebToken with custom permissions
I have the following extension to ObtainJSONWebToken as I'd like only users that are anonymous to be able to log in. Here is my views.py class APILoginView(ObtainJSONWebToken): permission_classes = [AnonymousUserPermission, ] def post(self, request, *args, **kwargs): return super().post(request, *args, **kwargs) Here is my custom permissions class AnonymousUserPermission(permissions.BasePermission): def has_permission(self, request, view): return not request.user.is_authenticated However, when I include a valid token in my headers (hence being logged in?) and send the request, I obtain a new valid token. I'd like to be able to obtain this valid token only when I do not send a valid token along in my header (hence when I'm an anonymous user). It is worth mentioning that this permissions works fine for other views. -
Django equivalent to HAVING in MySQL
I have two tables: table1 ----------------- | id | salary | | 1 | 2500 | | 2 | 500 | ----------------- table2 ------------------------------- | id | outlay | table1_fk | | 1 | 20 | 1 | | 2 | 40 | 1 | | 3 | 1000 | 2 | ------------------------------- and I need to select all rows from table1 + sum of outlays where salary is bigger than SUM of outlays the MySQL query would be: SELECT t1.*, COALESCE(SUM(t2.outlay),0) AS total_outlay FROM table1 AS t1 LEFT JOIN table2 AS t2 ON t1.id = t2.table1_fk GROUP BY t1.id HAVING total_outlay < t1.salary; Is it possible with Django ORM? So far I have this: Model1.objects.filter(somefilterlogic).annotate(outlay_total=Sum("model2__outlay")) I'm using Django 2.2.5 and MySQL -
How to make 5 star rating system in django
I have a django project with Course model, and i want to make 5 star rating system, for example like on Udemy, and also i want to show stars dynamically in the template. Who has any ideas how to implement that? Maybe some library and so on -
How do I put max and min limit on Django Admin Table's float fields?
I have a Details model as below: class Detail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=50) skype_session_attendance = models.FloatField() internal_course_marks = models.FloatField() programming_lab_activity = models.FloatField() mid_term_marks = models.FloatField() final_term_marks = models.FloatField() def __str__(self): return f'{self.user.username}-{self.subject}' I want the Admin Panel to have the min and max limit on all the Float Fields, such as, when Admin try to enter the values through Admin Panel in the Detail's Table float fields, he/she should not be allowed to enter the values except within the range of min and max limit. Can anyone help me in this? -
Django not displaying query in template
I am trying to display filtered objects in my django template however for some reason I don't know django does not display them. I have a similar views function and template which does indeed display but this particular function does not. Here are my urls.py, html template and views.py files: The views.py function responsible for the url: def game_category_list(request, slug): template = 'game_category_list.html' category = get_object_or_404(gameIdentifier, game_choice=slug) post = gameIdentifier.objects.filter(game_choice=category) context = { 'category':category, 'post':post, } return render(request, template, context) Url.py (which contains another url called and this does display all the posts associated with the slug. urlpatterns = [ path('', views.index, name='index'), path('categories/<slug:slug>', views.game_category_list, name='game_category_list'), path('<slug:slug>/', views.category_detail, name='game_category'), ] Here is the html file for the game_category_list function: {% extends 'base_layout.html' %} {% block content %} <div class='gamecategories'> {% for game in post %} <div class='gamecategoriesdisplay'> <h1>{{game.game_name}}</h1> </div> {% endfor %} </div> {% endblock %} I don't know why this doesn't work. Any help would be appreciated. -
Django - Pass context dictionary between views?
I have a detail view for each page and a CommentView for typing comments directly on to those pages. In the comment view, an instance of the Comment model is created which stores: the content of the comment, the author and the page id for the page it was written on. The 'context' dictionary stores the page it was written on, but this is not defined in the CommentView. My question: How do I pass the context dictionary from the detail view to the CommentView so I can access the page id? Or is there a better way to do this? class CityDetailView(DetailView): model = City template_name = 'blog/city.html' context_object_name = 'cities' def get_context_data(self, **kwargs): context = super(CityDetailView, self).get_context_data(**kwargs) context['form'] = CommentForm() return context class CommentView(View): #template_name = 'comment.html' def post(self, request): form = CommentForm(request.POST) if form.is_valid(): content = form.cleaned_data['content'] print(form.cleaned_data) ######################## This is where I need to use context ######################## new_comment = Comment(content=content, author=request.user, page_id=City.objects.filter(title=context['cities']).first().id) ###################################################################################### new_comment.save() return HttpResponseRedirect('/about') else: return HttpResponseRedirect('/about') -
Issue connecting Django to database
Im currently using python 3.6 and django 2.1.11. I have a db im trying to connect to to make migrations. Currently my settings looks like: 'Project': { 'ENGINE': "sql_server.pyodbc", 'HOST': os.environ.get("DJANGO_DB_SERVER"), 'USER': os.environ.get("DJANGO_DB_UID"), 'PASSWORD': os.environ.get("DJANGO_DB_PWD"), 'NAME': "Project", 'CONN_MAX_AGE' : 600, 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', } }, I have the settings set in a powershell script that i run to set up the env variables. When i try and make migrations i get the following error: django.db.utils.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'mssql_appuser'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); [28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'mssql_appuser'. (18456); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0)") I went into pyodc base file and added a print statement to see what my connection string looked like : DRIVER=ODBC Driver 17 for SQL Server;SERVER=db_name;UID=test;PWD=test;DATABASE=Project;MARS_Connection=yes Not sure whats wrong here. If i attempt to add {} around the driver in the ps1 file the connection comes up like this: DRIVER={{ODBC Driver 17 for SQL Server}}};SERVERNAME=db_name;UID=test;PWD=test;DATABASE=Project which seems incorrect Any advice on how to fix this would be appreciated … -
JWT implementation for phone and otp login in Django-rest framework
i want to use jwt for my login authentication system. I am making the user login only through phone and otp validation. Now when otp validation is done i want to send "refresh and access" token AS response to client with a message that otp is validated and user authenticated to login, but i am not using any username and password authentication , and for token generation in simplejwt rest framework , we need username and password. I checked many blogs and github codes , but i am finding it so complex to understand. This is my first jwt implementation. I would like to understand how should i go about this problem. Any help would be highly appreciated!!! -
Getting an error: "object of type 'type' is not JSON serializable" while returning a JSONResponse
Code snippet where I'm getting an error: return(JsonResponse({ 'success': True, 'message': 'Failed', 'data': including_val, 'details': None, 'failureReason': failure_reason })) Here, including_val is a bool with value False and failure_reason is a nested dictionary. Getting an error: Object of type 'type' is not JSON serializable Internal Server Error: /my_func Traceback (most recent call last): File "/Users/AjayB/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/AjayB/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 137, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view Apis.views.my_func didn't return an HttpResponse object. It returned None instead. "POST /my_func HTTP/1.1" 500 27 I've tried a print statement of the variable who gets this JSON response. But that variable ain't getting printed. and I'm sure that code is failing at this point coz all print statements above this JSONResponse are getting printed. I've even tried with a = json.dumps(failure_reason) return(JsonResponse({ 'success': True, 'message': 'Failed', 'data': including_val, 'details': None, 'failureReason': a })) but the error remains the same. How to tackle this? Where am I messing up conceptually? -
Django form with variable amount of fields
class Challenge(models.Model): pass class Round(models.Model): challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE) index = models.IntegerField() description = models.CharField(max_length=100) I have a use case in which I have a model for challenges and rounds. In this use case, each challenge has at least one round so I modeled it as a one-to-many relationship. So far, I have not found a solution to create CRUD forms for this model since most tutorials do not take foreign keys into account and tutorials that do use fk's have a set amount of records in the model with the foreign key (e.g: a challenge always has 2 rounds). In this use case, a challenge can have at least one round and there is no maximum amount of rounds set. How would I be able to create dynamic forms that allow me to perform CRUD operations on these two models? -
Django class-based views: upload a pdf file
How can I modify this class so the user can upload a pdf file? views.py: class OrderUpdateView(UpdateView): model = Order template_name = 'order_update.html' form_class = OrderEditForm def get_success_url(self): return reverse('update_order', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) instance = self.object qs_p = Product.objects.filter(active=True)[:12] products = ProductTable(qs_p) order_items = OrderItemTable(instance.order_items.all()) RequestConfig(self.request).configure(products) RequestConfig(self.request).configure(order_items) context.update(locals()) models.py: class Order(models.Model): ... pdf = models.FileField(upload_to='documents/', default='documents/test.pdf') ... forms.py: class OrderEditForm(BaseForm, forms.ModelForm): class Meta: model = Order fields = [ 'pdf' ] I already have tried to do it but it never saves the PDF file. -
Attaching a queryset-to-csv file in a django mail
I'm trying to attach this csv file that's created by the library django-queryset-csv (see docs), but when I recieve and open the file in my inbox, it's just empty. mail = EmailMessage(subject, text, from_email, [to]) with open(f'Orders for {date.today().strftime("%b-%d-%Y")}.csv', 'wb+') as f: write_csv(todays_orders, f) mail.attach(f.name, f.read()) mail.send() The csv is being created properly (it's located in the same directory as manage.py), but it won't get attached. I think it is because I'm accessing it wrong by calling f.name and f.read(). How can I get the file that I've just created in order to attach it and send it? -
Django listview doesn't show the recent data added to the database
For some reason Listview doesn't retrieve the fresh data being added to the database. Here is my code: class UserThreadsListView(ListView): model = Thread template_name = 'tweetsview.html' paginate_by = 20 context_object_name = 'threads_list' def get_context_data(self, **kwargs): context = super(UserThreadsListView, self).get_context_data(**kwargs) responsible = ConciergeSpecialist.objects.get(id=self.kwargs['pk']) if self.request.user.is_superuser: context['teammates_list'] = ConciergeSpecialist.objects.all().exclude(active=False) else: context['teammates_list'] = ConciergeSpecialist.objects.filter(Q(org_unit_name=self.request.user.org_unit_name) & Q(active=True)) context['responsible'] = responsible return context def get_queryset(self): responsible = ConciergeSpecialist.objects.get(id=self.kwargs['pk']) queryset = super(UserThreadsListView, self).get_queryset() return queryset.filter(tweet__responsible=responsible).order_by('id', '-tweet__created_at').distinct('id') Then I use {% for thread in threads_list %} to iterate through the threads in my template tweetsview.html. I can see the data in my database, however it doesn't get retrieved to the template for some reason. Only the old data that was retrieved the first time is showing up in a template properly. How do I fix this? -
Django or Spring boot for my personal web project ? or something else?
I read multiple articles about Django vs Spring boot, watch some videos on youtube, but I'm still struggling to choose the right Framework for my project. I have the knowledge in both languages, I learned learned Java in school (1year, so POO, multithread, IO steam, Servlet etc.), but I mostly use Python for my small personal project. The web project will have different page like : Listing products (min 17k products), where people will be able to filter them by type etc. Details about the product selected Page that provide some information related to a Seller/Shop Guides A map (using Google Map API) that show the nearest shops/sellers etc. The user will be able to register, rate and comment a product/seller, post create a guide etc. For the Database I was thinking to go for PostgreSQL (I'm familiar with MCD Diagram, so it will be easier to structure the DB). Requirement : Secure, but I believe it mainly depends of my code. -> I want to make sure my users are very safe Great performance when querying the DB to filter the products -> I will make it dynamic with Ajax. High Availability of the Website -> I know how … -
Archive section for objects in django admin
I want to customize Django Admin to have specific section for objects of my models (Such as Post or Product models) that use as an archive section. I now that, I need one field in my models that shown status of objects (Such as is_archive field), but I don't have any idea about how to display them in Django Admin. Does anyone have an opinion on this? -
DRF 2-way nested serialization with many to many relationship
I have a many-to-many relationship between my Student and Macro models, using an intermediary model class Person(models.Model): # cf/NIN optional by design cf = models.CharField(_('NIN'), unique=True, blank=True, null=True, max_length=16) first_name = models.CharField(_('first name'), blank=False, max_length=40) last_name = models.CharField(_('last name'), blank=False, max_length=40) date_of_birth = models.DateField(_('date of birth'), blank=False) class Meta: ordering = ['last_name', 'first_name'] abstract = True def __str__(self): return self.first_name + ' ' + self.last_name class Macro(models.Model): name = models.CharField(_('name'), unique=True, blank=False, max_length=100) description = models.TextField(_('description'), blank=True, null=True) class Meta: ordering = ['name'] def __str__(self): return self.name class Student(Person): enrollment_date = models.DateField(_('enrollment date'), blank=True, null=True) description = models.TextField(_('description'), blank=True, null=True) macro = models.ManyToManyField(Macro, through='MacroAssignement') class MacroAssignement(models.Model): student = models.ForeignKey(Student, related_name='macros', on_delete=models.CASCADE) macro = models.ForeignKey(Macro, related_name='students', on_delete=models.CASCADE) def __str__(self): return str(self.student) I configure serializers in order to exploit the nested serialization when I serialize students class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ('id', 'cf', 'first_name', 'last_name', 'date_of_birth') abstract = True class StudentSerializer(PersonSerializer): macro = serializers.StringRelatedField(many=True, read_only=True) class Meta(PersonSerializer.Meta): model = Student fields = PersonSerializer.Meta.fields + ('enrollment_date', 'description', 'macro') extra_kwargs = {'enrollment_date': {'default': date.today()}, 'description': {'required': False}} class MacroSerializer(serializers.ModelSerializer): students = StudentSerializer(many=True, read_only=True) class Meta: model = Macro fields = ('id', 'name', 'description', 'students') Untill here no problem, when I …