Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deleting currently viewed data after button click returning positional argument error - Django
When the user clicks an html button, I call a django view function. This function should delete the data that the user is currently viewing and redirect them to a new page. I asked this question asking how to do that, and I got a response. This response uses a function that filters data based upon its pk. When I run my program, I get an error saying acceptdonation() missing 1 required positional argument: 'pk' I think this has something to do with me not passing a pk into my function, but I am not sure. Function that filters and deletes data: def acceptdonation(request, pk): deleteitem = DonationDetail.queryset().filter(id=pk) deleteitem.delete() return redirect('/dashboard/') return render(request, 'acceptdonation.html', ) Class Based View (Gets the data and renders it out): class DonationDetail(DetailView): model = Donation queryset = Donation.objects.all() template_name = 'acceptdonation.html URL: (To display each donation) path('donations/<int:pk>/', views.DonationDetail.as_view(), name='donation-detail'), -
Django add HTML form aste editable text
I managed to add model data from a form to the HTML Page, but I cant seem to add it as an editable text and seems to come up always as a label like in the bellow example: <h1>For QS</h1> <p> QS Login: {{data.qs_login}} </p> But what i get is this: Instead id like to show it like this: I looked everywhere for a reference point for different types of block content but couldnt find anything, maybe im not saying the right name. Could anyone help? and if anyone had a reference link. I hope this could help others with this doubt. Thanks!!! -
Django - How to register a single template tag for multiple templates?
Is it possible to register a @register.inclusion_tag for multiple templates? for example: @register.inclusion_tag('blog/components/tags_list.html', takes_context=True) def tags_list(context): tags = Tag.objects.all() return { 'request': context['request'], 'blog_page': context['blog_page'], 'tags': tags } I would like for tags_list to also be available for other templates? Yes I can just copy and paste the def tags_list(), edit the name and add the corresponding template via another `@register, but that's not what I'm looking for. -
Python Mysql call fails silently (MariaDB)
Trying to figure out what is happening during Mysql Insert statement. I have a utility I am writing and am attempting to open my database (Django database in Mysql) and add a record from another database into it. I think I am including all the fields it needs, and If I actually cut and paste the Insert statement that gets generated - it works. It however does not work programmatically. It doesn't seem to generate an error. The last insert row seems to indicate success, but the actual record never gets there (I think it is rolling it back for some reason). Just don't see what the problem is. I successfully use the same cursor to check something else in the same database right before this, so the cursor should be good. Below is the insert code in python. create_string = """Insert INTO trackx_site_program SET air_date = '%s', air_time = '%s', service = '%s', block_time = '%s', block_time_delta = %d, running_time = '%s', running_time_delta = %d, remaining_time = '%s', remaining_time_delta = %d, title = '%s', locked_flag = %d, deleted_flag = %d, library = '%s', mc = '%s', producer = '%s', editor = '%s', remarks = '%s', audit_time = '%s', audit_user … -
How to redirect to same page in Django?
When i am pressing the login button I am getting 404 error even though it is rendered to same page. The Error is :- Using the URLconf defined in AmazeKart.urls, Django tried these URL patterns, in this order: admin/ register/ [name='register'] login/ [name='login'] The current path, login/login, didn’t match any of these. Views.py:- def login(request): return render(request, 'login.html') URLS.py of app urlpatterns = [ path('register/', views.registerPage, name='register'), path('login/', views.login,name='login') ] URLS.py of project urlpatterns = [ path('admin/', admin.site.urls), path('', include('User.urls')) ] -
Filter by date in template
I have a table with some data, date included, and I implemented an order/filter bar so the user can filter information with the fields of that object model. It was successful with every field except the date, so I want to know what is wrong with my code so Django can't filter by date. Here is my model.py: fecha = models.DateTimeField(auto_now_add=True) My view.py: def lista_oficios(request, *args, **kwargs): data = Oficio.objects.all() myFilter = OrderFilter(request.GET, queryset=data) data = myFilter.qs context = { "data": data, "myFilter": myFilter } return render(request, "oficios.html", context) My filters.py: class OrderFilter(django_filters.FilterSet): class Meta: model = Oficio fields = ['folio', 'fecha', 'usuario', 'dependencia', 'turnado', 'asunto', 'estatus'] And here are is the part of the template that span the filter bar: <form method="GET"> {% for field in myFilter.form %} {% if field.label == 'Fecha' %} <span>{{ field.label_tag }} <input type="date" {{ field }} </span> {% else %} <span>{{ field.label_tag }} {{ field }}</span> {% endif %} {% endfor %} <button class="btn btn-primary btn-lg" type="submit"> Search </button> </form> And here is the part of the table that displays the date: {% language 'es' %} <td>{{oficio.fecha|date:"Y-m-d"}}</td> {% endlanguage %} Here you can see all the objects I currently have in DB: But … -
Django - Finding all related OneToOneField objects through the foreign object
Sorry if that title isn't clear, here's what I'm trying to accomplish: class Document(models.Model): processed = models.BooleanField(default=False) class ParentClass(models.Model) document = models.OneToOneField(Document, on_delete=models.SET_NULL, null=True) class Meta: abstract = True def do_something(): raise NotImplementedError() class SubclassOne(ParentClass): # Some fields. def do_something(self): # Something specific to this subclass class SubclassTwo(ParentClass): # Some other fields. def do_something(self): # Something specific to this subclass I would then like to get all Document.objects.filter(processed=False), loop through them, and execute the associated object's do_something() method. -
The joined is located outside of the base path component
Good Morning Everyone, I developed an app in Django (latest version). On local server it is working well. But for deployment when I run command for collect static then the error occurred The joined path (C:\Users\Galaxy\PycharmProjects\plugins\js_composer\assets\images\icons\address-book.png) is located outside of the base path component (C:\Users\Galaxy\PycharmProjects\medical_store\staticfiles). I'm using HTML and Bootstrap for front-end but this path error occurred. It's my terminal showing return safe_join(self.location, name) File "C:\Users\Galaxy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\_os.py", line 29, in safe_join raise SuspiciousFileOperation( django.core.exceptions.SuspiciousFileOperation: The joined path (C:\Users\Galaxy\PycharmProjects\plugins\js_composer\assets\images\icons\address-book.png) is located outside of the base path component (C:\Users\Galaxy\PycharmProjects\medical_store\staticfiles) I tried to replace the url that was first looking as {background-image:url(../../../plugins/js_composer/assets/images/icons/address-book.png)} then I replace it by {background-image:url(../../../medical_store/static/img/address-book.png)} But same error found. I don't know how to remove this error. Have you any idea what I have to do exactly? Here is my settings for staticfiles. STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' -
How to remove a content type in a migration in Django 1.11?
I have a model (let's name it Material) that was originally created in a monolithic app (let's call it A). In order to divide this monolith into separate apps according to the business domain logic, we created a model with the same name in a new app (B) and performed a data migration from A to B. We then removed the model from the app A. In one of our views, we use a filter of elements which relies on ContentTypes to list the names of models by apps, For this, we use ContentType.objects.get_for_models() with the list of classes (which contains B.Material, but not A.Material), but an error occurs: NoneType' object has no attribute '_meta This is because the class of A.Material is gone from the code, but is still present in the ContentType table. When calling get_for_models(), it seems to search for combinations of model and app_label instead of going with the list we provide. The filter() result in there would have A.Material and B.Material, and later on have the error because of A.Material. While I find the behavior of get_for_models() strange in that regards, I believe the issue is the stale ContentType. Is there a safe way to … -
Why does sorting by related_id not work on django admin change list page?
Please consider some arbitrary model with a foreignkey to another model (in Django 3.2): class SomeModel(models.Model): related = models.ForeignKey(to=OtherModel, ...) Now, we can show the related_id on the admin change list page, for example: class SomeModelAdmin(admin.ModelAdmin): list_display = ['related_id', ...] The problem is: this does not allow sorting by related_id. Now, there's at least one way around this, e.g. using admin.display ordering (or the good old admin_order_field): class SomeModelAdmin(admin.ModelAdmin): list_display = ['display_related_id', ...] @admin.display(description='related id', ordering='related_id') def display_related_id(self, obj): return obj.related_id Another alternative would be to use related instead of related_id (in list_display), then setting OtherModel.__str__ to return the id, but this may have side effects outside the admin. These workarounds do the job, but the question remains: Why can we not sort by related_id out-of-the-box? -
Module parse failed: Unexpected token (8:15), WebPack 5, React, Django
So Im a noob to all of this and have been following this tutorial https://www.youtube.com/watch?v=GieYIzvdt2U but for the life of me can not seem to get this to work. There are many related questions but despite my best efforts I have not been able to get past this error trying any of the existing solutions. When I run npm run dev I get the following Module parse failed: Unexpected token (8:15) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See http s://webpack.js.org/concepts#loaders | class App extends Component { | render() { > return <div>React APP</div> | } | } @ ./GeoAnalyticsSite/frontend/src/index.js 1:0-35 webpack 5.47.0 compiled with 1 error in 69 ms Here are all of my NPM dev dependencies and the scripts in my package json { ... "scripts": { "dev": "webpack --mode development ./GeoAnalyticsSite/frontend/src/index.js -o ./GeoAnalyticsSite/frontend/static/frontend/", "build": "webpack --mode production ./GeoAnalyticsSite/frontend/src/index.js -o ./GeoAnalyticsSite/frontend/static/frontend/," }, ... "devDependencies": { "@babel/core": "^7.14.8", "@babel/preset-env": "^7.14.8", "@babel/preset-react": "^7.14.5", "babel-loader": "^8.2.2", "babel-plugin-transform-class-properties": "^6.24.1", "webpack": "^5.47.0", "webpack-cli": "^4.7.2" }, ... } The error message makes it sound as if it is an issue with my webpack. Here are my babelrc { "presets": ["@babel/preset-env", "@babel/preset-react","env", … -
Inserting PDFS into xhtml2pdf
I hope my problem is not too unique. I am using the Django frame work and the xhtml2pdf library. {% for part_workorder in partsReceived %} {%if part_workorder.cert_document %} <div class="imgHolder"> <img src="{{part_workorder.cert_document.path }}" /> </div><img src="{{part_workorder.cert_document.path }}" /> Each of my 'Parts' are associated with a certification document which insert into a pdf using the xhtml2pdf library. This works perfect for jpegs and pngs. The problem comes in when I one of the certification documents is a pdf. The is page is left blank. Perhaps this is because the pdf(certification document) I am inserting into the generated pdf(created with xhtml2pdf) is more than one page. My solution: Use a template tag( passing the path as a parameter ) and break up the image into multiple jpegs, return an array of images. Incomplete solution: from pdf2image import convert_from_path register = template.Library() @register.filter def get64(path): images = convert_from_path(path) for i in range(len(images)): images[i].save('page' + str(i) + '.jpg', 'JPEG') print(images[i]) # Save pages as images in the pdf I know this is not the correct attempt... Any suggestions and help will be greatly appreciated! -
How do I inherit class functions into a Django Model?
I'm trying to inherit functions from a class into a Django model so I can call the class functions using an instance of the model. In the below example, I want to inherit the class DoStuff into the model MainModel so I would receive the following output: >>> m = MainModel(var1=3, var2=4) >>> m.do_stuff.add() 7 models.py: from django.db import models class DoStuff: def __init__(self, x, y): self.x = x self.y = y def add(self): return self.x + self.y class MainModel(models.Model): var1 = models.IntegerField() var2 = models.IntegerField() do_stuff = DoStuff(var1, var2) #How do I correctly do this? I know this problem may seem a bit trivial, but it's a simplification of a greater issue I'm trying to solve. Thank you for reviewing my question! -
How to display all characters such as \s, \t and \n written in a form
In a simple form, I want to display all the written characters such as \n, \t or \s character. That's sort of the feature you can find in text editors like Notepad++ that I'm looking for. By the way, I'm using Django as a framework but any lead in HTML or Javascript or whatever is welcome. -
webflow js and css not being loaded into django templates via static
I started to use webflow recently and getting the js and css files to load from _base.html has been a nightmare. Despite all the static images loading fine, using <script src="{% static 'js/webflow.js' %}" type="text/javascript"></script> inside _base.html to extend into other templates does not work. It is strange because the inspector shows that the js file exists. -
Django Rest Framework not validating all model's fields
I searched for this problem everywhere without being able to find an answer though it seems basic DRF usage, so I might be missing sth. I have a Customer model with certain required fields: from django.db import models from django.utils.translation import gettext_lazy as _ from applications.core.models.country import Country from applications.core.models.customer_states.customer_state import \ CustomerState class Customer(models.Model): class Meta: verbose_name = _('customer') verbose_name_plural = _('customers') user_email = models.EmailField(_('email'), max_length=100, unique=True, default=None) complete_name = models.CharField(_('complete name'), max_length=200, default=None) phone = models.CharField(_('phone'), max_length=50, default=None) country = models.ForeignKey(Country, models.PROTECT, verbose_name=_('country'), default=None) city = models.CharField(_('city'), max_length=100, default=None) city_state = models.CharField(_('city state'), max_length=100, default=None) address = models.CharField(_('address'), max_length=100) zip_code = models.CharField(_('zip code'), max_length=50, default=None) customer_state = models.OneToOneField(CustomerState, models.PROTECT) notes = models.TextField(_('notes'), max_length=200, blank=True, null=True) And I have this serializer: from rest_framework import serializers from applications.core.models.customer import Customer from applications.core.models.customer_states.implementations.pending_manual_validation_state import \ PendingManualValidationState class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' def to_internal_value(self, data): self.add_default_state_if_missing(data) return super(CustomerSerializer, self).to_internal_value(data) @staticmethod def add_default_state_if_missing(data): data['customer_state'] = PendingManualValidationState.objects.create().pk Though I have explicitly told DRF that it should use all model's fields it does not seem to check for the requirement of fields like 'address' and whenever I create the serializer with data missing 'address' and call serializer.is_valid() it returns True. … -
post_list() missing 1 required positional argument: 'request'
I Have View.py class mainView(View): template_name = "search.html" def error_page(self,request): return render(request, 'error_page.html') def getQuery(self,query,): posts_list = Galeria.objects.filter( Q(nazwa__icontains=query) | Q(opis__icontains=query) ).distinct() return(posts_list) def postPagination(self,paginator,page): try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return posts def post_list(self,request, category_slug=None, **kwargs): posts_list = Galeria.objects.all() query = request.GET.get('q') if query: posts_list = self.getQuery(query) ile = posts_list.count paginator = Paginator(posts_list, 10) # 10 posts per page page = request.GET.get('page') posts = self.postPagination(paginator, page) category = None categories = Category.objects.all() if category_slug: category = get_object_or_404(Category, slug=category_slug) categories_ile = Galeria.objects.values('category__name').annotate(count=Count('category__name')) context = { 'posts': posts, 'ile': ile, 'categories': categories, 'category': category, 'categories_ile': categories_ile} return render(request, "search.html", context) ... url.py urlpatterns = [ path('searchbar/', mainView.post_list, name="searchbar"), ... ] Why I get error "post_list() missing 1 required positional argument: 'request'"? I trying everything and I read documentation on this page https://docs.djangoproject.com/en/3.2/topics/class-based-views/intro/ and still nothing. -
Error in scheduled tasks: 'django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured.'
I deployed my Django app on pythonanuwhere and want to add one file to scheduled tasks. But it gives me an error: django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I tried this: os.environ.setdefault('DJANGO_SETTING_MODULE', 'smsreminder.settings') django.setup() Result the same, but error in the line with django.setup() Script in the file, which I want to execute: import datetime from django_common.auth_backends import User from reminder.models import Remind from twilio.base.exceptions import TwilioRestException from twilio.rest import Client def my_scheduled_job(): content = Remind.objects.all() account_sid = "--------------------------" auth_token = "--------------------------" for smscontent in content: if smscontent.remind_date == datetime.today().date(): tempusers = User.objects.filter(username=smscontent.author) for recipient in tempusers: try: client = Client(account_sid, auth_token) message = client.messages.create( body="I just want to remind, that you have some task for today {date}: {task}. {time} is the deadline!".format( date=str(smscontent.remind_date), task=str(smscontent.title), time=str(smscontent.remind_time)), to=str(recipient.username), from_="+18568889437") print(message.sid) except TwilioRestException: pass return Error: Traceback (most recent call last): File "/home/remindmy/sms-reminder/reminder/cron.py", line 3, in <module> from django_common.auth_backends import User File "/home/remindmy/.virtualenvs/remindervenv/lib/python3.9/site-packages/django_common/auth_backends.py", line 6, in <module> from django.contrib.auth.backends import ModelBackend File "/home/remindmy/.virtualenvs/remindervenv/lib/python3.9/site-packages/django/contrib/auth/backends.py", line 2, in <module> from django.contrib.auth.models import Permission File "/home/remindmy/.virtualenvs/remindervenv/lib/python3.9/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/remindmy/.virtualenvs/remindervenv/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line … -
Django Carton, changing the cart.add() function so that I can add options for products
I'm creating a website that will have product that people can order. I decided to go with Carton as a shopping cart. I can see that the cart.add() function only takes the product, price and quantity. The products I have on the page allow for choices in colour, quality and a variable price. I got the variables into the view, but when adding into the: cart.add(product, price, quantity) I cannot add anymore arguments for the options: cart.add(product, price, quantity, options) when I do, I get an error saying there can only be 2-4 arguments. anyone who worked with this before, found a way to do it? Thanks in advance! -
Django JSONField: I cannot query using lookup
I have a Django model that has a postgreSQL JSONField, like this: class MyClass(models.Model): identifiers = JSONField(null=True, default=dict, blank=True) If I create a field like this: MyClass.objects.create( identifiers={ 'my_identifier': '12345' } ) and then query it like so: my_instance = MyClass.objects.first() print my_instance.my_identifier # prints '12345' it's there. But if I query it using lookups, like this: my_identifier = MyClass.objects.get(identifiers__my_identifier='12345') I get this error: FieldError: Unsupported lookup 'my_identifier' for JSONField or join on the field not permitted. There are other parts of this codebase (it's Python 2, we're just reeeaaly behind on porting to py3) where this logic seems to work. I cannot figure out what's going wrong. -
Django: How to Add Meta Tags to Multiple Pages?
Here is a link for a similar question: Django: How can I add meta tags for social media? This question only addresses how to add meta tags if there is only child class, now if there's multiple children that contain the {% block extra_head_tags %} <meta .../> {% endblock %} how would I implement this? Here is a sample structure: - Base UI.html (contains {% block extra_head_tags %}{% endblock %} ) - Child1.html(contains {% block extra_head_tags %} <meta CONTENT1/> {% endblock %} - Child2.html (contains {% block extra_head_tags %} <meta CONTENT2/> {% endblock %} -
Django validation of number from query string
Im having this code to create and add students to database. I need to make validation of count which must be integer, only positive, equal or less 100. Please help. def generate_students(request): count = request.GET.get('count') studentslist = [] for student in range(0, int(count)): student = Student.objects.create(first_name = fake.first_name(), last_name = fake.last_name(), age = random.randint(18,100)) studentslist.append(student) output = ', '.join( [f"id = {student.id} {student.first_name} {student.last_name}, age = {student.age};" for student in studentslist] ) return HttpResponse(str(output)) -
i need a particular geo library for django
I would like to show a map with pre-recorded positions in Django , the user will be able to choose one of the postions (pins) and we will get the point (coordinates or whatever) through a formMapfield. I know we can do this with geodjango but it would be overkill. Wouldn't there be a faster lib to set up even without spatial databases? thanks in advance -
How to validate my form,It's not validating
Am trying to update my record from frond-end and when I tried this one, My form is not validating. What is the solution for this problem or is there any other way to edit my record from front end models.py: class graphinput(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) Month = models.CharField(max_length=30) Value1 = models.IntegerField(null=True,blank=True) Value2 = models.IntegerField() class Meta: db_table="WebApplication_graphinput" Views.py: def updatedisplay(request): userid = None if request.user.is_authenticated: userid = request.user.id print(userid) updatedisp=graphinput.objects.filter(user=userid).first() print(updatedisp) form=EditForms(request.POST,instance=updatedisp) if form.is_valid(): form.save() print('ADDED SUCCESFULLY') return render(request,"edit.html",{'displaymonthvalue':displaymonthvalue}) else: print("no such form") return redirect('display') forms.py: from django import forms from .models import graphinput class EditForms(forms.ModelForm): class Meta: model=graphinput fields= "__all__" -
Force DecimalField to convert a string into decimal - Django
I have this serializer: class Ticker24hSerializer(serializers.Serializer): change = serializers.DecimalField(max_digits=19, decimal_places=4) change_percent = serializers.FloatField() current = serializers.DecimalField(max_digits=19, decimal_places=4) high = serializers.DecimalField(max_digits=19, decimal_places=4) low = serializers.DecimalField(max_digits=19, decimal_places=4) def update(self, instance, validated_data): pass def create(self, validated_data): pass A dictionary contains decimal values like this: dict = { "change": "2128.5000", "change_percent": "5.632", "current": "39517.3141", "high": "40900.0000", "low": "37350.0000" } However, these values are stored as strings in the dictionary. When I serialize the dict: result = serializer(dict).data print(result) I get this: { "change": "2128.5000", "change_percent": 5.632, "current": "39517.3141", "high": "40900.0000", "low": "37350.0000" } DecimalFields are accepting strings, how can I make my serializer store decimals?