Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
return type of annotate
I want to get date when first order was placed for each item in database. filter = Q(prev_order_items__order_id__order_type='Normal') & Q(prev_order_items__order_id__final_approval='Yes') f_date_ord = F('prev_order_items__order_id__created_at') event_queryset3 = OrderItemTable.objects.filter(filter).annotate(f_date=Min(f_date_ord)) event_queryset3 = OrderItemTable.objects.annotate(f_date=Min(f_date_ord, filter=filter)) -
How do i compare JSON with my data from request in django?
I created API but also i must have taken JSON file from request. I just dont know how to i compare that file with data which i have in my project and how to i response it back if its true or false. I cant complete my code. i tried some codes like: def send_json(request): json_data = {'existing_binaries': ['firmware-0.3', 'cfirmware-0.6', 'firmware-0.1', 'efirmware-0.7', 'dfirmware-0.7', 'firmware-0.2', 'firmware-0.4']} #data = json.loads(request.body) serializer = CloudSerializer (json_data,many = True) if serializer.to_representation(json_data): return JsonResponse (serializer.data, print('upload et') ,safe = False) else: return JsonResponse(print('olmadı'),safe = False) def send_json(request): data = Cloud.objects.all() serializer = CloudSerializer (data, many = True) return JsonResponse (serializer.data, safe = False) -
django customize truncatechars
I'm using truncatechars but it have a problem; For example, content is: Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature using truncatechars:160 Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin litera {% block description %}{{ content|truncatechars:160 }}{% endblock %} I want like this: Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin If the word has reached the limit of 160 letters before the end of that word, don't include that word -
After migrating the models in django, I am unable to see the data in admin panal
I am trying to solve this problem whole day. My code is shown below. Actually, I created my tables in Pgadmin4. I created the table "atmpokhara" having 10 columns with id field as varchar(20) datatype. After that, I drop the id filed from my atmpokhara table. I render this table to django model using python manage.py inspectdb > models.py All the row are already in tables. Everything is going good, but when I try to open my table inside my admin panel, I get following error: operator does not exist: character varying = bigint LINE 1: ...number" FROM "atmpokhara" WHERE "atmpokhara"."id" = 57173664... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Request Method: GET Request URL: http://localhost:8000/admin/webmap/atmpokhara/5717366409/change/ Django Version: 2.1.7 Exception Type: ProgrammingError Exception Value: operator does not exist: character varying = bigint LINE 1: ...number" FROM "atmpokhara" WHERE "atmpokhara"."id" = 57173664... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Exception Location: D:\coding time\Django+ GeoDjango\Django Enviroment\venv\lib\site-packages\django\db\backends\utils.py in _execute, line 85 Python Executable: D:\coding time\Django+ GeoDjango\Django Enviroment\venv\Scripts\python.exe Python Version: 3.7.2 Python Path: ['C:\\Users\\Tekson\\Desktop\\Web-GIS-Django\\Project', 'C:\\Program Files\\Hexagon\\ERDAS IMAGINE ' '2015\\usr\\lib\\Win32Release\\python', 'C:\\Users\\Tekson\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', … -
building a quiz app local variable 'answer_selection' referenced before assignment
hey guys so I'm trying to build an app which manage an electronic quizzes, the model is right works perfectly fine when I try to add a question but the problem is when I try to post the user answers it wont work I tried so hard to fix it but couldn't! models.py class Question(models.Model): course = models.ForeignKey(CourseType, default=1, on_delete=models.CASCADE) exam = models.ForeignKey(Exam, default=1, on_delete=models.CASCADE) answer = models.CharField(max_length=50, default="") question = models.TextField(max_length=200,default="") option1 = models.CharField(max_length=50,default="") option2 = models.CharField(max_length=50, default="") option3 = models.CharField(max_length=50, default="") option4 = models.CharField(max_length=50, default="") def __str__(self): return self.question forms.py MULTIPLE_CHOICE= [ ('A', 'A'), ('B', 'B'), ('C', 'C'), ('D', 'D'),] class TestForm(forms.Form): right_answer= forms.CharField(widget=forms.RadioSelect(choices=MULTIPLE_CHOICE)) views.py def test_view(request, question_id): if request.user.is_anonymous: return redirect('cal:signin') form = TestForm() if request.method == "POST": form = TestForm(request.POST) if form.is_valid(): right_answer = form.cleaned_data['right_answer'] quiz = form.save(commit=False) answer_selection = Question.objects.get(id=question_id.answer) scores = 0 for find_right_answer in answer_selection: if find_right_answer == option1 or find_right_answer == option2 or find_right_answer == option3 or find_right_answer == option4: find_right_answer = Question.objects.filter(id=question_id) scores += 1 else: scores -= 1 quiz.save() return redirect('cal:quiz-page') context = {'form':form,'answer_selection':answer_selection} return render(request, 'cal/quiz_page.html', context) quiz_page.html {% extends "cal/base.html" %} {% load crispy_forms_tags %} {% block title %}Quiz !t{% endblock title %} {% block content %} <br> … -
How to Redirect to login if not authenticated in django?
I am making a forum site where if a user is not logged in, he or she will be redirected to login page. But I don't understand how to do it. -
TypeError: cannot unpack non-iterable bool object
When I run the code it redirects and showing TypeError at /accounts/register cannot unpack non-iterable bool object The problem is when I put the below condition in my code User.objects.filter(username==username).exists(): User.objects.filter(email=email).exists(): Please help from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth # Create your views here. def register(request): if request.method == 'POST': last_name = request.POST['Last_name'] first_name = request.POST['first_name'] username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] if password1==password2: if User.objects.filter(username==username).exists(): print("username taken") elif User.objects.filter(email=email).exists(): print('email exists') else: user = User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name) user.save() print('User Created') else: print('password doesnt match') return redirect('/') else: return render(request,'accounts/register.html') TypeError: cannot unpack non-iterable bool object [16/Jul/2019 17:51:22] "POST /accounts/register HTTP/1.1" 500 98878 -
django translate text inside html tags and maintain html tags
I've found a tool I can use to translate text googletrans this is how it works from googletrans import Translator translator = Translator() result = translator.translate(text, dest=lang) print(result.text) but in the case that my text might come from django-ckeditor so it includes html tags for example <h1>Some Title</h1> <p>Some Text</p> I need to pass this text to it and still maintain the html tags, so far it tends to break that symetry and the text formatting gets ruined to mention it fails to translate correctly. There's tools like beautiful soup that can help you read html text, that direction looks like it's going to be bloated code that "barely" works, I'm curious if someone knows of a way to get it to work more cleanly. -
How to change the parent page?
I have custom view and form for article page in admin single view. In form I have html5 select for change parent (section). How to change the parent page in admin edit view? i try ty use edited wagtail.admin.views.pages.edit: #wagtail code revision = page.save_revision( user=request.user, submitted_for_moderation=is_submitting, ) #my code new_parent_page_id = request.POST.get('parent_page_id') if int(new_parent_page_id) != parent.id: parent = SectionPage.objects.get(id=new_parent_page_id) page.move(parent, pos='last-child') page.save() and it doesn't work wagtail==2.4 -
CS:GO Roulette Game Script
What is needed to develop a roulette game? I'm python developer and I'm also making websites with django. I have front end knowledge of css js jquery vs.. (The roulette game I want is like https://csgoempire.gg/) -
Django model form with only view permission puts all fields on exclude
Using a custom ModelForm in my default (django admin) change view gives me an empty variable self.fields if the form gets rendered for a user with only view permissions (new in Django 2.1). This is my code: # models.py class Door(ValidateOnSaveMixin, models.Model): ... motor_type = models.ForeignKey( MotorType, on_delete=models.SET_NULL, default=None, blank=True, null=True) ... door_type = models.CharField( max_length=3, choices=DOOR_TYPES, null=True, default=None) ... vehicle_variant = models.ForeignKey( VehicleVariant, on_delete=models.CASCADE) class Meta: unique_together = ("vehicle_variant", "location", "motor_type") ... # admin.py @admin.register(Door) class DoorAdmin(ImportExportModelAdmin): form = DoorAdminForm list_display = ('descriptor', 'get_customer_link', 'get_variant', 'location', 'get_motor_type_link', 'window_type', 'door_type', 'drum_diameter', 'dist_per_motor_rotation') fields = ('vehicle_variant', 'description', 'location', 'motor_type', 'drum_diameter', 'window_type', 'door_type') ... # forms.py class DoorAdminForm(ModelForm): class Meta: model = Door fields = '__all__' widgets = { 'motor_type': DoorMotorTypeWidget, } def __init__(self, *args, **kwargs): super(DoorAdminForm, self).__init__(*args, **kwargs) # this line is crashing on access with a user who has only the view permission, as self.fields is empty self.fields['vehicle_variant'].queryset = VehicleVariant.objects.all().prefetch_related('customer').order_by('customer__name', 'name') The root cause is related to the exclude attribute of the Meta class in DoorAdminForm. No matter what i write to the fields/exclude attributes, always all of the model's fields get automatically put to the exclude list and prevent self.fields to be populated. And this makes my code crash. … -
(Django 2.1)I can't serve static files while media files is bieng served perfectly?
The static files always give me a 404 error and I can't see why,I copied a style I've used before but not with this version of django. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_DIR = [ os.path.join(BASE_DIR,"static") ] STATIC_ROOT = os.path.join(BASE_DIR, 'static' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I was using cdn and style tag for the whole time working on the project but now i want to wrap it up and use some css/js files already ready for me. Every kind of help is appreciated and thank you. -
How to edit PDF in GUI using django
I am looking for a solution to edit PDF in web interface for my django project. My aim is to add comments and tags to a PDF uploaded by user. I could not find any package for this purpose. I have even searched for converting PDF to html and then edit and again convert to PDF. Can anyone help. -
Django pass data into easy_pdf
i have problem with passing data from view request into PDFTemplateView class. Package documentation: Django easy_pdf My files: url.py urlpatterns = [ url(r'^create_pdf/$', create_pdf, name='create_pdf'), url(r'^create_pdf/pdf/$', HelloPDFView.as_view()) ] views.py currently i redirect post request into created pdf file @login_required def create_pdf(request): if request.method == "POST": #handle posted data data = computed data # how to pass calculated data into test.html ??? return redirect('pdf/') return render(request, 'clients/create_pdf.html') from easy_pdf.views import PDFTemplateView class HelloPDFView(PDFTemplateView): template_name = 'render_pdf/test.html' test.html {% load static %} <html> <body> <img src="{% static '/some.png' %}> </body> </html> I'm trying to get data from POST create_pdf view and then pass all collected data into test.html Thank you for your attention -
Django Form text input field not showing in browser
I have a Django model and form for a comment submission form i want under my blog post. The form however, does not show in my browser and i assume isn't loaded. I'm new to coding and have been looking for a solution for a long time to no avail. models.py from django.db import models from datetime import datetime from django import forms from django.contrib.auth.models import User from django.conf import settings class Comment(models.Model): post = models.ForeignKey('blog.post', on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) text = models.TextField(max_length=200) created_date = models.DateTimeField(default=datetime.now()) def __str__ (self): return self.text forms.py from django import forms from django.forms import ModelForm from .models import Comment from django.db import models class CommentForm(forms.ModelForm): class Meta: model = Comment exclude = ['post' 'author'] form = CommentForm views.py from django.shortcuts import render,get_object_or_404,redirect from django.views import generic from .forms import CommentForm from .models import Comment, Post def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('/blog/<int:pk>', pk=post.pk) else: form = CommentForm() return render(request, 'blog/post.html', {"form":form}) form = CommentForm(request.POST) urls.py from django.urls import path, include, re_path from django.views.generic import ListView, DetailView from .models import Post from . import … -
How to cache dynamically generated image in browser?
I generate a dynamic image on http://example.com/image/some_param1/some_param2/ I do: HttpResponse(img.image, content_type=magic.from_file(img.image.path, mime=True)) It is displaying image fine, however, it is not cached in browser. I tried adding: location /image { uwsgi_pass django; include /home/tomas/Desktop/natali_reality/uwsgi_params; expires 365d; } But it doesn't work. Is there a solution for this? -
How can I rename field in search_fields of django rest_framework?
I have class ProductSearch(ListAPIView): queryset = Product.objects.all() permission_classes = [AllowAny] serializer_class = ProductSearchSerializer filter_backends = [SearchFilter] search_fields = ['meta_data', 'store__district__id'] but when I make search through api I need to enter "store__district__id": "blabla" but instead of this I just want "district_id": "x" anyone can help? -
Upload, parsing and save with django.forms
Hi everyone) I'm new in Django. I need to upload a .csv file, validate is this a csv file, parse him and save to database with django.forms. This is my model class CvsModel(models.Model): a = models.CharField(max_length=50) b = models.CharField(max_length=50) c = models.CharField(max_length=50) forms.py from .models import CvsModel class CvsForm(forms.Form): file = forms.FileField(label='') views.py from .forms import CvsForm def upload_view(request): my_form = CvsForm(request.POST or None) context = { "form": my_form } return render(request, 'upload.html', context) upload.html {% extends 'base.html' %} {% block title %}Upload{% endblock %} {% block content %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} </form> {% endblock %} -
How to make Ajax delete Django's object instance?
There is a list generated in HTML, that represents all objects (Cards). There is already a delete button, but it's using Django functionality, and it requires a page to reload to take effect. Is there a simple way to include AJAX into the program? I am a beginner to JavaScript and AJAX. I have tried some copy-paste solutions. I even tried to deconstruct a simple Django Ajax CRUD app, but it has too many functionalities, and it seemed like an overkill for my app (i would have to rewrite all the views, templates and urls). So I decided to ask a question over here with my own code. views.py (List objects view) def all_cards(request): cards = Card.objects.all() return render(request, 'all_cards.html', {'cards':cards}) all_cards.html <body> {% if cards %} <table class="table" id="card-table"> <tr> <th>Card owner name</th> <th>Card balance</th> </tr> {% for card in cards %} <tr> <td>{{ card.cardholders_name }}</td> <td>{{ card.card_balance }}€</td> <td><form action="{% url 'card_delete' card.id %}" method="post"> {% csrf_token %} <input type="submit" value='Delete'> </form></td> </tr> {% endfor %} {% else %} <p>There are no cards registered.</p> {% endif %} </table> </body> urls.py url(r'(?P<id>\d+)/$', views.card_delete, name='card_delete'), views.py (Delete object view) def card_delete(request, id): card_that_is_ready_to_be_deleted = get_object_or_404(Card, id=id) if request.method == 'POST': … -
Django - Multiple forms with different submit buttons not working
I'm trying to add a contact form and a login form on the same page but when entering the login information to the right form and then click on the submit button triggers the this field is required from the contact form mandatory fields. I'm using Django 2.1 and postgreSQL. My View: def landing_view(request): if request.method == 'GET': contact_form = ContactForm() login_form = CustomAuthForm(request.POST) else: contact_form = ContactForm(request.POST) login_form = CustomAuthForm(request.POST) if request.POST.get('submit') == 'contact_form': if contact_form.is_valid(): name = contact_form.cleaned_data['name'] phone = contact_form.cleaned_data['phone'] from_email = contact_form.cleaned_data['from_email'] message = contact_form.cleaned_data['message'] subject = name + " Contact Beta Landing" msg = "\n \n Mail: " + str(from_email) + \ "\n \n Phone: " + str(phone) + \ "\n \n Message: \n \n" + message from_send_mail = "'\"" + \ name + \ "\" <contactBeta@ekiter.com>'" try: send_mail( subject, msg, from_send_mail, ['contact@ekiter.com']) except BadHeaderError: return HttpResponse('Invalid header found.') messages.add_message(request, messages.SUCCESS, 'Success! Thank you for your message, we will contact you.') return redirect('landing') elif request.POST.get('submit') == 'login_form': if login_form.is_valid(): username = login_form.cleaned_data['username'] password = login_form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('home') else: return redirect('landing') return render(request, "../templates/landing.html", {'form': contact_form, 'loginForm': login_form}) This is the contact form … -
How to fill models attributes with data from internet
First of all let me say that I'm new to Django. I've created a small application that gathers information from trasnfermrkt to create football players. In my Models I've defined Player with some attributes: name, age, position... One of the attribute is the trasnfermrkt URL link. I'd like to add the URL and the application to auto-filled all the attributes using info from that URL. The function that collects info from transfermrkt is not part of the Model (I'm trying to follow the services module approach) so, from Models, I'm modifying the save method to call the external function. So far this appraoch is working, but I'd like to know if there's a better approach for what I want to achieve (maybe using signals?). scrapping.py class PlayerData(): """Class that gathers data from transfermrkt. It needs a URL""" headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'} def get_transfrmrkt(self): page = self pageTree = requests.get(page, headers=PlayerData.headers) soup = BeautifulSoup(pageTree.content, 'html.parser') player_name = soup.find("div", class_="dataMain").find("h1").text [...] models.py from library.scrapping import PlayerData [...] def save(self, *args, **kwargs): self.name=PlayerData.get_transfrmrkt(self.transfermarkt_link) # Call the "real" save() super(Player, self).save(*args, **kwargs) -
How to filter against URL in a nested serializer in django REST
I want to filter my generic API View against an URL by passed id and by year. The passed id is on the model, yet the year is nested. Example of the data structure looks like so: This is one Building Group: [ { "description": "BG1", "buildings": [ { "id": 1, "name": "Building13", "demandheat_set": [ { "id": 1, "year": 2019, }, { "id": 2, "year": 2013, }, { "id": 2, "year": 2013, } I would like to filter this view against an URL to only show the demandheat_set for, let's say, the year 2013. I followed the docs on filtering and I can filter by building group. This is what I am doing to get the example data from above: class BGHeat(ListAPIView): serializer_class = BGHeatSerializer def get_queryset(self): building_group_id = self.kwargs['building_group_id'] building_group_objects = BuildingGroup.objects.filter(id=building_group_id) ) return building_group_objects Fantastic I can filter by ID of the building group and get back the example data I posted above with this URL: path('test/<int:building_group_id>/', BGHeat.as_view(), name="") Now, I would like to filter by year that is nested, but I can't get it to work.... I tried this: URLs path('test/<int:building_group_id>/<int:year>/', BGHeat.as_view(), name="") Now I wanted to change my queryset to only contain the data I need: … -
DRF .to_internal_value() not adding field from serializer data
I'm trying to add the OrderLine ID back to the validated data by using .to_internal_value() but it's returning OrderedDict([..., ('id', <class 'rest_framework.fields.empty'>)]) instead. The data submitted is {'date_invoice': datetime.date(2019, 7, 17), 'lines': [{'id': 2, 'weight': 37}]} For some reason data argument doesn't include they key "id" so it's returning an empty value. How can I can I return the id? class InvoiceLineSerializer(serializers.ModelSerializer): class Meta: model = OrderLine fields = ( 'id', 'weight', ) read_only_fields = ( 'id', ) def to_internal_value(self, data): # data does not include key "id" ret = super().to_internal_value(data) ret['id'] = self.fields['id'].get_value(data) return ret class InvoiceSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ( 'date_invoice', 'lines', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['lines'] = InvoiceLineSerializer( context=self.context, many=True, write_only=True, ) -
How can I use an external api to authenticate login instead of Django's inbuilt authentication system?
I am new to Django and working as an intern for a company. I have been tasked with creating an internal software for them to use. The software needs to have a log in system for the employees. However, the company already has an auth api they use for other products. How can I make use of that api to log the users on? I have searched for an answer for a while and I couldn't find one. The auth api has an endpoint called '/token' which is used to validate the email and password. I'm guessing I need to remove the 'django.auth' stuff from settings, but I have no more insight into this than that. Any help would greatly be appreciate. Below is the swaggerhub documentation for an endpoint of the api: /token: post: summary: Generate a new token (aka login) operationId: createToken tags: - authentication description: Login using email and password, and retrieve a newly created bearer token to access our APIs. Alternatively, use a token to create another one. requestBody: -
Automatic intermediate model for ManyToMany relation with 'id' as BigAutoField
I need place for a lot of entries for some ManyToMany relationships. So i want the 'id' field of the intermediate models to be BigAutoField. I know that i could specify a custom intermediate model for those relationships, but i would prefer not to because despite of the id field's type i'm happy with the automatically generated model and would like to avoid a lot of code changes. So, is there any way to have (mostly) automatically generated intermediate models with a BigAutoField for the id I tried to use migrations to change the id field but it seems the automatically generated model is not available in migrations.AlterField. # models.py from django.db import models class Model1(models.Model): id = models.BigAutoField() name = models.CharField(max_length=255) class Model2(models.Model): id = models.BigAutoField() model1set = models.ManyToManyField(Model1) # migrations 0002 class Migration(migrations.Migration): # ... operations = [ migrations.AlterField( 'model2_model1set', 'id', models.BigAutoField() ), ] Running the migration gives: KeyError: ('main', 'model2_model1set') However, accessing the model by the same name from the apps object works: >>> from django.apps import apps >>> apps.get_model("main", "model2_model1set") main.models.Model2_model1set So is there any way to have a (mostly) automatically intermediate model with the id as BigAutoField?