Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I tried Datatable adding to a form not working as POST method django
I want show my table as Datatable and also want to accept values from there, So I tried my form in a table but when I am trying to access the values the post method isn;t working. What can be cahnged here ? it works when I remove the script below but dosen't work when I add the script. HTML code <form class="form form-control" method="POST"> {% csrf_token %} <thead> <tr align="center"> <th> Item Code </th> <th> Name </th> <th> Check Number </th> <th> Submit </th> </tr> </thead> {% if bomlist %} <tbody> {% for bom in bomlist %} <tr align="center"> <td> {{ bom.code }} </td> <td> <input value="{{bom.code}}" name="bom" hidden/> {{bom.name}} </td> <td> <input class="text text-center form-sm" type="number" name="number" min="1"/> </td> <td> <button type="submit" class="btn btn-primary"> Submit </button></td> </tr> {% endfor %} </tbody> {% endif %} </form> </table> Jquery <script type="text/javascript"> $(document).ready(function () { $('#bomtable').DataTable(); }); </script> -
How can I use URL in my html page in django?
hi when I want to use URL in my action tag I get an error URL not found what should I do please help me! app_name = 'accounts' urlpatterns = [ path('signup',views.signup_view, name='signup'), path('login',views.login_view, name = 'login'), ] urlpatterns = [ path('admin/', admin.site.urls), path('about/',views.about), path('',views.home), path('articles/', include('articles.urls')), path('accounts/',include('accounts.urls')), ] <form class="site-form" action="{% urls'accounts:signup'%}" method="post"> -
Django Allauth Customized Login Template Not Working
I have customized the login template of allauth with bootstrap styles and widget_tweaks. When I try logging in with that template, It doesn't redirect me to the home page but remains in the same login.html template. However, when I log in with the original template from allauth in /account/login.html/ everything works well and it redirects me to my homepage. There is something that I'm not customizing right in my custom login.html template. Below is django-allauth login.html and my custom login.html django-allauth login.html {% extends "account/base.html" %} {% load i18n %} {% load account socialaccount %} {% block head_title %}{% trans "Sign In" %}{% endblock %} {% block content %} <h1>{% trans "Sign In" %}</h1> {% get_providers as socialaccount_providers %} {% if socialaccount_providers %} <p>{% blocktrans with site.name as site_name %}Please sign in with one of your existing third party accounts. Or, <a href="{{ signup_url }}">sign up</a> for a {{ site_name }} account and sign in below:{% endblocktrans %}</p> <div class="socialaccount_ballot"> <ul class="socialaccount_providers"> {% include "socialaccount/snippets/provider_list.html" with process="login" %} </ul> <div class="login-or">{% trans 'or' %}</div> </div> {% include "socialaccount/snippets/login_extra.html" %} {% else %} <p>{% blocktrans %}If you have not created an account yet, then please <a href="{{ signup_url }}">sign up</a> first.{% … -
Function' object has no attribute 'objects' in django
This is error image There is some problem with 15 line in views.py comment=blogcomment.objects.filter(post__in=post,parent=None) Please help me in solving this problem. Error Exception Type: AttributeError at /blog/1st-blog Exception Value: 'function' object has no attribute 'objects' -
Django dynamic filtering with Ajax
I want to dynamically filter my querySet using the value of my input field with Ajax. Right now I’m trying something like this: Template: <div class="card mt-3"> <div class="card-body"> <form action="" form="get"> <input data-url="{% url 'klantbeheer' %}" class="zoekklanten" name="q" type="text" placeholder="Zoek op contactnaam..."> </form> {% if object_list %} <div class="single-table"> <div class="table-responsive"> <table class="table text-center"> <thead class="text-uppercase bg-dark"> <tr class="text-white"> <th scope="col">Bedrijfsnaam</th> <th scope="col">Contactnaam</th> <th scope="col">Locatie</th> <th scope="col">Actie</th> </tr> </thead> <tbody> {% for user in object_list %} <tr> <td>{{ user.bedrijfsNaam }}</td> <td>{{ user.contactNaam }}</td> <td>{{ user.adres }}</td> <td> <a href="{% url 'klantupdaten' user.id %}"><i class="fas fa-edit"></i></a> <a href="#" data-url="{% url 'klantverwijderen' user.id %}" class="deletegebruiker" data-bs-toggle="modal" data-bs-target="#dynamic-modal"><i class="fas fa-trash-alt"></i></a> </td> </tr> {% endfor %} </tbody> </table> </div> </div> {% else %} <p>Geen gebruikers gevonden</p> <p> <a href="{% url 'klantaanmaken' user.id %}" class="btn btn-primary">Maak klant aan</a> </p> {% endif %} </div> </div> View: class ManageUserView(SuperUserRequired, ListView): model = User template_name = 'webapp/klant/beheerklant.html' #Query based upon contactName def get_queryset(self, query): #Contactnaam bevat QUERY EN superuser is vals. object_list = self.model.objects.filter(contactNaam__icontains=query).exclude(is_superuser=True) return object_list def post(self, request, *args, **kwargs): query = self.request.POST.get('query', '') print(query) self.get_queryset(query) Jquery: $('.zoekklanten').on('keyup', function(){ var url = $(this).data('url') var query = $(this).val(); $.ajax({ url:url, type:'POST', data:{ 'query':query }, dataType: 'json', beforeSend: … -
Django Messaging Framework in the save() function
I am checking if a model instance already exists and if does I want to send a message saying "Name already exists". As there is not request in def save(), is there any other way to send a message via Django message framework or something else?? def save(self, *args, **kwargs): self.name = self.name if Name.names.name_exists(self.name): message = "You already have this name!" # want to send this message print("not created") else: print("created") super(Name, self).save(*args, **kwargs) -
How to obtain a user instance in django application
I'm trying to obtain a user instance for the profile page in django app but I'm finding some difficulties implementing that functionality. I have the following blocks of code: models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE, default="") image = models.ImageField(upload_to="images/user_profile_pics/", default="images/default_profile_pics/default.jpg") firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) def __str__(self): return f'{self.lastname} profile' serializers.py class user_profile_serializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' views.py class user_profile(generics.GenericAPIView): serializer_class = user_profile_serializer def get(self, request, *args, **kwargs): user = request.user return Response(user.data, status=status.HTTP_200_OK) urls.py urlpatterns = [ path('profile/', user_profile.as_view(), name="user-profile"), ] When ever I assess the profile url, I get an error message 'AnonymousUser' object has no attribute 'data' I have tried a couple of approaches but none worked. Please, how do I obtain a specific user from the database? -
Django & GDAL - Could not find the GDAL library
I have a macbook with the M1 Chip and I'm trying to set up a django project. The project works with Geospatial libraries gdal. I installed gdal with homebrew on version 3.3.1_3 and inside my virtual env version 3.3.1 If I type python manage.py migrate I get an error: django.core.exceptions.ImproperlyConfigured: Cloud not find the GDAL library (tried "gdal", "GDAL", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0"). Is GDAL installed? If it is, try settings GDAL_LIBRARY_PATH in your settings. By pip list shows me GDAL at version 3.1.0. The Django Docs say version 3.3.x is not supported but I cant install a specific gdal version with homebrew. Is there a different solution to get the django project up and running? -
Database Error No exception message supplied in Django with MongoDB - Django
Im working on a Django project where i was using postgres and it was working fine. Now i want to use MongoDB but im getting "No exception message supplied" error most of times when querying on objects. please find the below codes for reference and help. Model class Order(models.Model): order_status = (('Pending', 'Pending'), ('Under Process', 'Under Process'), ('Dispatched', 'Dispatched'), ('Delivered', 'Delivered'), ('Cancelled', 'Cancelled'), ('Out for delivery', 'Out for delivery')) patient = models.ForeignKey(Patient, on_delete=models.SET_NULL, null=True, blank=True) shipping_address = models.ForeignKey(ShippingAddress, on_delete=models.DO_NOTHING, null=True, blank=True) order_created = models.DateTimeField(auto_now_add=True,null=True) date_ordered = models.DateTimeField(null=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) order_number = models.CharField(max_length=20, unique=True, null=True) status = models.CharField(choices=order_status, default='Pending', max_length=30) payment_status = models.CharField(choices=(('Received', 'Received'), ('Failed', 'Failed'), ('Pending', 'Pending')), default='Pending', max_length=30) ip_address = models.CharField(max_length=30, null=True) coupon_applied = models.BooleanField(null=True,blank=True) coupon = models.ForeignKey(ShoppingCoupon,on_delete=models.DO_NOTHING,null=True,blank=True) coupon_discount = models.DecimalField(max_digits=7,decimal_places=2, null=True,blank=True,default=0) # Payment details captured from payment gateway payment_order_id = models.CharField(max_length=100, null=True) # razorpay order id payment_id = models.CharField(max_length=100, null=True) # Razorpay payment id payment_signature = models.CharField(max_length=100, null=True) payment_method = models.CharField(max_length=100, null=True) ordered_medicine = models.JSONField(null=True,blank=True) Query def cartData(request): if request.user.is_authenticated and request.user.user_type == 'patient': patient = Patient.objects.select_related('user').get(user=request.user) order, created = Order.objects.get_or_create(patient=patient, complete=False) // Im getting error here items = order.cartitem_set.select_related('medicine').all() cartItems = order.get_cart_items im getting error on "order, created = Order.objects.get_or_create(patient=patient, complete=False)" -
Rounding a pyodbc variables
I currently have the following code which gives the below-mentioned outputs Code: Views.py creditTotal = ' Select SUM(Credit) FROM [Kyle].[dbo].[PostGL] WHERE Credit <> 0.0' cursor = cnxn.cursor(); cursor.execute(creditTotal); xCreditTotal = cursor.fetchone() return render(request , 'main/Kyletrb.html' , {"xAlls":xAll_l , 'xCreditTotal':xCreditTotal}) Html.html: {% for xCreditTotal in xCreditTotal %} <td><b>{{ xCreditTotal }}</b></td> {% endfor %} Output: Total 485940.85000000003 How would I be able to round this value to 2 decimal places (e.g. 485940.00)? -
Branching Workflows based on value of specified Page field
I have a DailyReflectionPage Model with a reflection_date field that forms the basis for the Page's slug, which is in the form YYYY-MM-DD. Here's an extract of my Page model: class DailyReflectionPage(Page): """ The Daily Reflection Model """ ... ... reflection_date = models.DateField("Reflection Date", max_length=254) ... ... @cached_property def date(self): """ Returns the Reflection's date as a string in %Y-%m-%d format """ fmt = "%Y-%m-%d" date_as_string = (self.reflection_date).strftime(fmt) return date_as_string ... ... def full_clean(self, *args, **kwargs): # first call the built-in cleanups (including default slug generation) super(DailyReflectionPage, self).full_clean(*args, **kwargs) # now make your additional modifications if self.slug is not self.date: self.slug = self.date ... ... These daily reflections are written by different authors, as part of a booklet that is published towards the end of the year, for use in the coming year. I would like to have a workflow where, for instance, the daily reflections from January to June are reviewed by one group, and those from July to December are reviewed by another group, as illustrated in the diagram below: How can this be achieved? -
Django file runs from shell but not run but on own
When trying to running a file inside my project, I get the error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. However, when running python3 manage.py shell and pasting the code into the shell it works fine. The file looks like this: from models import * products = Product.objects.all() iterable_form = [] for p in products: a = [] a.append(p.ID) a.append(p.title) a.append(p.official_path_name) a.append(p.quantity) a.append(p.language) a.append(p.book_type) a.append(p.authorID) a.append(p.editionID) iterable_form.append(a) print(iterable_form) -
Django error PermissionDenied has no attribute set_cookie
In my django application i have the below code if not exist: return PermissionDenied This line will returns following error type object 'PermissionDenied' has no attribute 'set_cookie' Can any one help me please -
How to make a POST request inside Django's Test.py with an authenticated user?
I'm trying to find a way to test a POST-request which need an authenticated user in Django. I'm using the login-option as described in the docs here: https://docs.djangoproject.com/en/3.2/topics/testing/tools/#django.test.Client.login And I'm using the client.post method as described here: https://docs.djangoproject.com/en/3.2/topics/testing/tools/#django.test.Client.post However, my response prints as "None" and I'm getting a 403, rather than a 200 as my view should return. It works fine when I'm trying it out with postman, so that's not where the problem lay. My test def test_post_new_task_authorized_user(self): self.client.login(username="xxx", password="password123") data = { "title": "A new post", "description": "Description of post", "responsible_username": "xxx", } response = self.client.post( reverse("CUDtasks"), data, content_type="application/json" ) print("REPONSE IS: %s" % response.context) self.assertEqual(response.status_code, 200) Test error code FAIL: test_post_new_task_authorized_user (todo.tests.TodoTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/xxxx/Documents/Programmering/xxxx/myproject/todo/tests.py", line 140, in test_post_new_task_authorized_user self.assertEqual(response.status_code, 200) AssertionError: 403 != 200 ---------------------------------------------------------------------- Ran 4 tests in 0.084s -
Django admin add entry to specific groups
Hej! I'm looking for a possibility to add entries by different users and groups. In my app there are different users and different groups where one user can belong to multiple groups. The goal is that some of the groups have sensitive data so I only want members of this group to be able to read the entries but some data should be available in multiple groups. It should also be possible to only see some information. (e.g. See the name but not the address) For now I have the decorator @login_required for all my views and @permission_required for a persons_view. Therefore you have to be a registered user to see anything, which is great but not quite enough. I also created groups (via the admin area) but can't filter the data for each model/view. The group either sees the data or they don't. The registration of users is connceted to an already existing ldap system (where those groups are pre-defined. Would be great to use those!) Is there a possibility to add entries only for a special group and view only some of the given information? Thanks for the help! -
Heroku Django Deployment PyGObject and PyICU cannot build wheels
This is the error I am getting I've had to cut off the error output due to the character limit but can provide it all if it would help remote: running build_ext remote: Package gobject-introspection-1.0 was not found in the pkg-config search path. remote: Perhaps you should add the directory containing `gobject-introspection-1.0.pc' remote: to the PKG_CONFIG_PATH environment variable remote: No package 'gobject-introspection-1.0' found remote: Command '('pkg-config', '--print-errors', '--exists', 'gobject-introspection-1.0 >= 1.46.0')' returned non-zero exit status 1. remote: remote: Try installing it with: 'sudo apt install libgirepository1.0-dev' remote: ---------------------------------------- remote: ERROR: Failed building wheel for PyGObject remote: Building wheel for PyICU (setup.py): started remote: Building wheel for PyICU (setup.py): finished with status 'error' remote: ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-4rw7_fyu/pyicu/setup.py'"'"'; __file__='"'"'/tmp/pip-install-4rw7_fyu/pyicu/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-qpd_ssyb remote: cwd: /tmp/pip-install-4rw7_fyu/pyicu/ remote: Complete output (90 lines): remote: (running 'icu-config --version') remote: (running 'pkg-config --modversion icu-i18n') remote: remote: Building PyICU 2.4.2 for ICU 66.1 remote: remote: (running 'icu-config --cxxflags --cppflags') remote: Could not configure CFLAGS with icu-config remote: (running 'pkg-config --cflags icu-i18n') remote: (running 'icu-config --ldflags') remote: Could not configure LFLAGS with icu-config remote: (running 'pkg-config --libs … -
Some Model with ID "xx" doesn't exist. Perhaps it was deleted?
I can't access the change page with an ID yet it exists in the DB, in a certain Django account, but I can do access it on the admin account. I checked all the permissions and they seem okay, only that am getting this error : But when I navigate this URL (same URL) on admin below it works very well: http://localhost:8000/en/admin/accounts/cooperationpartner/25/change/ So am wondering what causes this issue yet the Id exists in the DB. Model for CooperationEmployee : class CooperationEmployee(models.Model): cooperation_employee_id = models.CharField( _('Cooperation Employee ID'), max_length=64, blank=True, null=True) international_prefix = CountryField( _('International prefix'), null=True, blank=True) phone_number = models.CharField(_('Telephone Nr'), max_length=20) branch = models.CharField( _('Relevant branch'), max_length=50, blank=True, null=True) My DB shows this, the ID is available (Postgres) : The admin page for CooperationEmployee has this : def has_change_permission(self, request, obj=None): """Permissions to change account settings.""" if request.user.role == ROLE_COOPERATION_EMPLOYEE: return True return False The role ROLE_COOPERATION_EMPLOYEE is for the model above. -
Django restrict user to edit data which doesnt belongs to them
I have a url, localhost:8000/user/data/edit/1 In the above, 1 is the data's id which belongs to user=x ! Likewise i have 1000's of data Now when i log in as user=y and go the same link, it opens the edit page ! But data 1 is belongs to user=x - how to handle this ? How to restrict this ? Does django do this automatically or we need to do this manually ? -
How can i active or passive options Django Admin
I have a form option in my Django application. I want to be able to activate or deactivate some options from the admin panel. How can I go about this? <div class="form-group"> <label for="username">Username</label> <input type="text" placeholder='Username' class="form-control" name="username"> <br> <label for="type">Bonus Türü</label> <select name="bonuses" id="test" id='testvalue' class="form-control"> <option selected value="0">Please select</option> <option value="2">Taste </option> <option value="36206">Taste 1 </option> <option value="58013">Taste 2</option> <option value="55908">Taste 3</option> <option value="21310">Taste 4</option> </select> </div> For example, with a feature I added to the admin panel, I want to disable the 4th option and activate it whenever I want. This is my admin.py from django.contrib import admin from .models import Bonusrequest class adminPlus(admin.ModelAdmin): list_display = ("username","name","bonus","result","created","descrpt") admin.site.register(Bonusrequest,adminPlus) -
Create Django abstract child model refering to the table of the parent model
I have a model (Parent) that has a table in the database (table app1_parent) in a first app (app1). In another app (app2), I would like to add functionnality to this Parent model, but still refer to the existing Parent table (table app1_parent), which is part of the other app (app1). If I create in app2 the Child model that simply inherite from Parent, I end up with two different tables: app1_parent and app2_child I'd like to know if I can create an (abstract ?) child model (Child) that refers to the table of the Parent model, without adding additional field, but adding new methods and properties. (Basically I would want to do the contrary of what abstract tables have been built to do) class Parent(models.Model): my_field = models.CharField(max_length=255) class Child(Parent): def my_method(self): return 'done' class Meta: abstract = True Is there another way to achieve my result? PS: of course, the objective would be not to modify the app1.Parent model and app1.parent table -
can we plot dendrogram on frontend by using django backend
I am working on a clustering based project where I have to perform dendrogram operation on backend and to plot that chart on front-end using any javascript based framework (angular). So I know how to do it in python but on front-end how can I plot that because the data from python SciPy library is like nested lists which use line plots while in front-end libraries they accept data as parent child relation. In case I am not clear then do let me know. -
How to serialize two nested django tables?
Album is being generated, files are being associated with album table, but the question is how i'll serialize both tables to show response on post request. waiting for help. -
how can i get data of a variable or something in javascipt in veiws.py in django? [duplicate]
i was working on a shopping website . and in this case the products that i have in my cart is in the localstorge . i want to get them with localstorge.getitem commend and then i want to have access to them in the views.py to send them with a email . this is the views.py def cart(request ) : sent = False if request.method == "POST" : form = emaildtata(request.POST) if form.is_valid() : cd = form.cleaned_data name = cd["name"] add = cd["add"] num = cd["num"] num2 = cd["num2"] postcode = cd["postcode"] msg = "name : "+name+" | addres : "+add + " | number : "+num +"/"+num2 + "postcode : "+postcode send_mail("سفارش جدید" , msg , "kkmbcmbc@gmail.com" , ["alirezajavanpour789@gmail.com"]) sent = True return render(request , "site/cart.html" , {"form" : form , "sent" : sent}) food = realitems.objects.all() form = emaildtata() context = { "posts" : food, "form" : form } return render(request , "site/cart.html" , context) okay and its my forms.py class emaildtata(forms.Form) : name = forms.CharField(max_length=24 , label="نام و نام خانوادگی") add = forms.CharField(max_length=210 , label="ادرس تحویل" , widget=forms.Textarea) num = forms.CharField(max_length=13 , label="شماره تماس") num2 = forms.CharField(max_length=13 , label="شماره تماس 2" ,required=False) postcode = forms.CharField(max_length=10 , label="کد … -
How to paginate/search/filter objects simultaneously. Query parameters [Django]
I have 3 different forms in my html template: to filter, search and paginate results. I want there to be an option to do that simultaneously: shop/?filter_by=diary_products&paginate_by=6 shop/search/?q=milk&filter_by=diary_products&paginate_by=6 The problem is when form is been submitted. Query parameters does not append, so i cannot reach the above mentioned result. Search form <form action="{% url 'search_products' %}" method="GET"> {% csrf_token %} <button type="submit">Search</button> <input type="text" name="q" placeholder="Search"> </form> Select form to choose items per page (pagination) <form action="{% what should i put here? %}" method="GET"> <select name="paginate_by" onchange="this.form.submit()"> <option selected>1</option> <option>2</option> <option>3</option> </select> <noscript><input type="submit" value="Submit"></noscript> </form> Filter form <form action="{% what should i put here? %}" method="GET"> <select name="filter_by" onchange="this.form.submit()"> <option selected>diary_products</option> <option>by_price</option> <option>newest_first</option> </select> <noscript><input type="submit" value="Submit"></noscript> </form> urls.py from django.conf import settings from django.conf.urls.static import static from django.urls import path from . import views urlpatterns = [ path('', views.shop, name='shop'), path('search/', views.search_products, name='search_products'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Jquery plugin for fixed column with django formset
Did any one use any jquery plugin for fixed columns with Django formset. The django formset is normal table that have events to create or delete row. I have try with css sticky property but it doesn't work. The DataTables fixedColumn is not suitable for django formset table. You can look her for more inforamtion about the django formset blugin.