Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
'str' object has no attribute 'model'
@staff_member_required @never_cache def departures(request, fields=None): qs = Booking.objects.filter(status="PURCHASED").order_by=('departure_date') model = qs.model response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=%s.csv' % slugify(model.__name__) writer = csv.writer(response) # Write headers to CSV file if fields: headers = fields else: headers = [] for field in model._meta.fields: headers.append(field.name) writer.writerow(headers) # Write data to CSV file for obj in qs: row = [] for field in headers: if field in headers: val = getattr(obj, field) if callable(val): val = val() row.append(val) writer.writerow(row) return response line model = qs.model throws the error 'str' object has no attribute 'model' but I have other functions that have the same/similar code that does not throw an error like if form.cleaned_data.has_key('departure_date') and form.cleaned_data['departure_date'] != '' and form.cleaned_data['departure_date'] != None: qs=Booking.objects.filter(departure_date__travel_date__exact=form.cleaned_data['departure_date']).filter(status="PURCHASED") model = qs.model So I am surprised that an error is being thrown, any ideas please -
Django serializer for .count()
I'm trying to make server-side pagination and for this i've need object's count. So the problem is that i get error when trying to get this value because of serializer ('int' object is not iterable) i dont khow how to create serializer that returns this value. Below is the usual serializer for the model and of course it doesn't work properly. views.py class CountItem(ListAPIView): queryset = Item.objects.count() serializer_class = ItemSerializer Serializer.py class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' -
Django og graph tags issue
<meta property="og:url" content="{% block ogurl %}{% url 'post:Homepage' %}{% endblock %}" /> <meta property="og:image" content="{% block ogimage %}{% static 'img/brand/logo.png' %}{% endblock %}" /> Result; <meta property="og:url" content="/" /> <meta property="og:image" content="/static/img/brand/logo.png" /> What I want; <meta property="og:url" content="sitename.com" /> <meta property="og:image" content="sitename.com/static/img/brand/logo.png" /> Where i did mistake, can you help me -
How to change the class of a H element in Wagtail Draftail Editor
I would like to add custom classes to H1, H2, H3, etc. in the Draftail editor. I was looking at hooks but I am unsure if I'm looking at the right method, if you get what I mean? The result I would like to have is, for example: <h1 class="custom-h2"> Lorem ipsum dolor sit amet </h1> Thanks in advance! -
Chnage request.user in django middleware
I have a custom token for letting my user access api s the problem is here that I need to get current user for some part of code using request.user how can I write middleware to do this for me? -
Django 2.2 FilteredSelectMultiple outside Admin panel
I've setup urls.py to include the javasript-catalog, and my forms.py is defined like this: from django.contrib.admin.widgets import FilteredSelectMultiple class FooBarForm(forms.ModelForm): class Meta: model = Foo fields = ( '__all__' ) bar = forms.ModelMultipleChoiceField(queryset=FooBar.objects.all(), widget=FilteredSelectMultiple("verbose name", is_stacked=False)) class Media: css = {'all':('admin/css/base.css', 'admin/css/widgets.css', 'admin/css/forms.css', 'admin/css/responsive.css')} Inside my template.html is: {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {{ form.media }} </head> <body> <div class="container"> <div class="row"> {{ form }} </div> </div> <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script> </body> </html> That converts to this after rendering: <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="/static/admin/css/base.css" type="text/css" media="all" rel="stylesheet"> <link href="/static/admin/css/widgets.css" type="text/css" media="all" rel="stylesheet"> <link href="/static/admin/css/forms.css" type="text/css" media="all" rel="stylesheet"> <link href="/static/admin/css/responsive.css" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> <script type="text/javascript" src="/static/admin/js/core.js"></script> <script type="text/javascript" src="/static/admin/js/SelectBox.js"></script> <script type="text/javascript" src="/static/admin/js/SelectFilter2.js"></script> </head> <body> <div class="container"> <div class="row"> <select name="foo" required id="bar" multiple class="selectfilter" data-field-name="Concelhos" data-is-stacked="0"> <option value="1">....</option> </select> </div> </div> <script type="text/javascript" src="/jsi18n/"></script> </body> </html> The forms renders as it should, but doesn't work. The console error show as below: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined at findForm (VM59 SelectFilter2.js:11) at findForm (VM59 SelectFilter2.js:12) Any ideas … -
Testing on Django rest framework
I got stuck on testing small piece of code for 3 hours, every time I am receiving the same error. class DroneCategoryTests(APITestCase): def post_drone_category(self, name): url = reverse(views.DroneCategoryList.name) data = {'name': name} response = self.client.post(url, data, format='json') return response def test_post_and_get_drone_category(self): new_drone_category_name = 'Hexacopter' response = self.post_drone_category(new_drone_category_name) print("PK {0}".format(DroneCategory.objects.get().pk)) assert response.status_code == status.HTTP_201_CREATED assert DroneCategory.objects.count() == 1 assert DroneCategory.objects.get().name == new_drone_category_name here is the code when I type pytest it shows too long error that's why I cannot paste here but I can say the error is about database like self = <django.db.backends.utils.CursorWrapper object at 0x7f1d57a216d8> sql = 'SELECT "toys_toy"."id", "toys_toy"."created", "toys_toy"."name", "toys_toy"."description", "toys_toy"."toy_category", "toys_toy"."release_date", "toys_toy"."included_inhome" FROM "toys_toy" ORDER BY "toys_toy"."id" ASC' params = () ignored_wrapper_args = (False, {'connection': <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f1d5b68d0b8>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x7f1d57a216d8>}) here test is about Drone but I do not know why Toy models is appearing. How can I fix the problem? -
TypeError: expected string or bytes-like object while updating M2M
I am trying to update a ManyToMany field in django while doing this I am getting the following error : value = self.get_prep_value(value) File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1408, in get_prep_value value = super().get_prep_value(value) File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1268, in get_prep_value return self.to_python(value) File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1369, in to_python parsed = parse_datetime(value) File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/utils/dateparse.py", line 106, in parse_datetime match = datetime_re.match(value) TypeError: expected string or bytes-like object Here is my models.py class tag(models.Model): name = models.CharField(max_length=100) created_date = models.DateTimeField(default=timezone.now) description = models.TextField(blank=True) def __str__(self): return self.name class tutorial(models.Model): title = models.CharField(max_length=200) link = models.URLField() tags = models.ManyToManyField(tag) category = models.CharField(max_length=200, choices = TUTORIAL_CATEGORIES) created_date = models.DateTimeField(default=timezone.now) @cached_property def __str__(self): return self.title views.py I am actually generating title & tags from a custom script that's why the serialzer are incomplete. I am trying to send the following JSON data : { "link":"https://youtu.be/DHvMXvCVQVA", "category":"video" } @api_view(['GET', 'POST']) def tutorials(request): """ get: Returns all tutorials post: POST a tutorial """ if request.method == 'GET': tutorials = tutorial.objects.all() serializer = tutorialSerializer(tutorials, many=True) return JSONResponse(serializer.data) elif request.method == 'POST': postserializer = tutorialPOST(data = request.data) if postserializer.is_valid(): title, tags = generateTags(request.data['link']) print(title) print(tags) updateDB = tutorial.objects.create( title = title, link = request.data['link'], category = request.data['category'], created_date = timezone.now ) …