Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want the code of previous version of my Django app. How can I get it? I tried git reset --hard but it's not working. It's showing email not found s
I deleted the requirements.txt file and again created a new requirements.txt file using pip freeze > requirements.txt And after deploying, it is showing an application error. So I rolled back to the previous version. But I am not able to get the code of that previous version. I tried with the "git reset --hard eeb02c91" command. But it's not working. It's showing "HEAD is now at eeb02c9 Email not registered error added". Someone, please help me to get the code of the previous version. -
Cannot Install python3-gdal in digitalocean app for django project
Digital ocean introduced apps, which is very fast and easy way to deploy projects. But i've encountered a problem and I wonder if you can help me with it. In my requirements i have added GDAL, but when i try to install it it says that gdal-config is not installed. I have added in my build commands ./manage.py migrate sudo apt-get install python3-gdal python-gdal libgdal-dev But the build commands wont execute before installing the requirements.txt I cannot access the console and I cant install it manually, Have you already encountered such a problem with the dependency libs and how can I solve it? -
Add multiple objects as a list to a model attribute in Django?
I am new to Django and I am working on a project. I want to create a classroom with multiple students which are objects with their own attributes. My classroom model class Classroom(models.Model): name = models.CharField(max_length=31) students = models.ForeignKey('Student',on_delete=models.CASCADE, null=True, related_name='students') def __str__(self): return self.name My student model class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) classroom = models.ForeignKey( Classroom, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Classroom") When I go to the specific URL I see only one student rather than all. Please help. Thanks in advance -
Link an html form to a django form
I created the following html form: <div class="contact-page-form"> {% csrf_token %} <!-- Contact Form --> <form method="get" id="formulaire"> {% csrf_token %} <div class="row clearfix"> <div class="form-group col-lg-12 col-md-12 col-sm-12"> <span class="icon flaticon-user-2"></span> <input type="text" name="username" placeholder="Votre nom" required> </div> <div class="form-group col-lg-12 col-md-12 col-sm-12"> <span class="icon flaticon-big-envelope"></span> <input type="email" name="email" placeholder="Email" required> </div> <div class="form-group col-lg-12 col-md-12 col-sm-12"> <span class="icon flaticon-user-2"></span> <input type="text" name="sujet" placeholder="Sujet" required> </div> <div class="form-group col-lg-12 col-md-12 col-sm-12"> <span class="icon flaticon-user-2"></span> <textarea id="msgtext" name="message" placeholder="Message"></textarea> </div> <div class="form-group col-lg-12 col-md-12 col-sm-12"> <button class="theme-btn submit-btn" name="submit-form">Envoyer <span class="arrow flaticon-right-arrow-1"></span></button> </div> </div> </form> <!-- Contact Form --> </div> I would like to know if it is possible to create a django form in a forms.py file and to link my existing html form to it. if so, how to do it? -
Is there a way to pass foreign key field to test database in django through fixtures
while executing the unit test cases in Django, I tried to load data to test database using fixtures. As the fixtures contains the foreign key field i am getting the column of relation does not exist error. So, can we load the table with foreign key with fixtures while testing the django code -
Integration of python script into django application
I developed an AI application (which includes a knowledge base, nested lists, etc.), written in python and currently using a python interpreter for that. On the other hand, I have a Django application, more like a frontend for the end-user. But now I'm stuck on how to integrate both applications together. -
Ajax Infinite scroll on fixed element does not work. Can I change the window reference to the element?
Let me tell you the problem. Picture 1 I need a fixed element as you can see in picture 1. The context flows there. I use django for backend. I want to use infinite scroll and if I don't use overflow-y: scroll everything works great. I think the problem is tha ajax cannot find height of scrollbar. When scrollbar of window change,as you can see picture2, ajax works great. picture2 How can I fix the problem ? Thank you -
How to generate random users in django template on button click with no refresh
I want a button, on which I can click so that it outputs a random user each time with no refresh. I am using a django user queryset, which should be randomized. So I have this variable which I have passed into my template from views.py in django. all_users {{ all_users }} <button>Generate</button> so now, when I click that generate, it should give a random user from the all users. Without refresh. I think this can be done in javascript, but I'm not sure. This is what I've done. <p id="de">&nbsp;</p> <button id="button" onclick="rndTx">Press</button> <script> function rndEl(){ return arr[~~(rnd()*arr.length)]; } function rndTx(){ var tx = rndEl(); var txt = document.createTextNode(tx); var sp = document.createElement('span'); sp.appendChild(txt); de.innerHTML = ''; de.appendChild(sp).style.color = tx; } rnd = Math.random; arr = {{ all_users }} // using queryset here. tElementById('de'); document.getElementById("button").addEventListener('click',rndTx,false); </script> please let me know how I could do this. Thanks! -
Is Python to preferred as a backend language over Java because it supports live/hot reload?
When developing Java applications I always have to stop and rebuild my application when implementing changes in the backend. If your application is not performance sensitive, should python be preferred as a backend language because not so much time is wasted restarting the application after every small change? -
Django/CKEditor/Javascript Issue including text in textarea
I'm working on a forum with Django that allows users to reply to each other (and quotes the original user). This works perfectly when I do a first reply (I'm using a one line javascript that updates the textarea via grabbing the id and updating the innerHTML with a django template from my view, see html template below) : Issue is, when I attempt to quote an already quoted message, nothing appears in the textarea field. Below are my views and templates: View @login_required def reply_to_post(request, pk, topic_id, post_pk): reply = get_object_or_404(Post, topic_id=topic_id, pk=post_pk) topic = get_object_or_404(Topic, board__pk=pk, pk=topic_id) if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.post = reply post.created_by = request.user post.topic = topic user = reply.created_by title = post.topic post.save() reply.last_update = timezone.now() reply.save() notify.send(request.user, recipient=user, actor=request.user, verb='replied to your post', target=title, nf_type='replied_by_one_user') reverse('home') topic_url = reverse('topic_posts', kwargs={'pk': pk, 'topic_pk': topic_id}) topic_post_url = '{url}?page={page}#{id}'.format( url = topic_url, id=post.pk, page=topic.get_page_count() ) return redirect(topic_post_url) else: form = PostForm return render(request, 'reply_post.html', {'topic': topic, 'form': form, 'reply': reply}) reply_form.html {% load form_tags widget_tweaks %} {% load static %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} <p {% if forloop.last … -
How to change queryset in forms.py django?
I have in my forms.py this code: def __init__(self, *args, **kwargs): super(CountryForm, self).__init__(*args, **kwargs) self.fields['area'].queryset = Geo.objects.filter(Q(category='O') | Q(category='K')) self.fields['district'].queryset = Geo.objects.none() self.fields['district'].widget.attrs['disabled'] = True self.fields['region'].queryset = Geo.objects.none() This none() in queryset don't give me to save my Country form. But I can't delete this 3 fields with none(), because this 2 fields on page gives me a lot of data(31 000) Ofcource it slow down the page. Any ideas how can I specify this queryset Geo.objects.none() but without none() - no data inside? -
(2021) How to login and get page content from Facebook using scrapper API
since Facebook has changed its policies, so now i cannot view or scrap Facebook page or anything without login. I was using scrapper API and everything was working fine but now it redirects me to the login page. Is there any way i can first login with scrapper api then get any page content within a single session? -
Why django is not detecting my table column?
I have a problem. I've created model called "Flower", everything works fine, i can create new "Flowers", i can get data from them etc. The problem is when I want to use column "owner_id" in SQL query I got an error that this column don't exist, despite I can use it to get data from objects (for example flower1.owner_id). I've deleted my sqlite database several times, made new migrations and used migrate but that still not worked.I also changed name of the column and re-created it, but that still doesn't helped. My models.py: from django.db import models from django.contrib.auth.models import User class Flower(models.Model): name = models.CharField(max_length=80) water_time = models.IntegerField() owner_id = models.ForeignKey(User, on_delete=models.CASCADE, default=1) def __str__(self): return self.name My views.py (view, where i want to use it): class workspaceView(generic.DetailView): template_name = 'floris/workspace.html' def get_object(self): with connection.cursor() as cursor: cursor.execute(f'SELECT id,name FROM floris_Flower WHERE owner_id = {self.request.user.id}') row = cursor.fetchall() object = row print(object) if self.request.user.id == object.id: return object else: print('Error') My urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index2, name='index2'), path('login/', views.loginView, name='login'), path('register/', views.register, name='register'), path('addflower/', views.AddPlantView, name='addflower'), path('index.html', views.logout_view, name='logout'), path('workspace/', views.workspaceView.as_view(), name='workspace'), path('profile/<str:username>/', views.ProfileView.as_view(), name='profile'), ] And my error code: … -
In-memory variables versus querying database
Part of my app is to render many charts whose data are updated at some predefined time interval. The conventional Django way is obvious: write new data to database; if the view of the charts is called, query the database for the desired records, and render them in the charts. Clearly, this results in a lot of database hits and data frame manipulation, which put latency of chart rendering. So I want to read the desired number of records into memory right when the Django server starts (for simplicity, read into a pandas data frame). That data frame's, df, size is fixed, say N x M. When new data arrives at the app, this df then pop and push accordingly to maintain the N x M size. And at the same time, update the charts. Writing the new data into database can be done separately. Specifically: #data_utils.py def read_db(): ... return df #views.py def all_charts(request): ... chart_components = show_charts(df) return render(request, 'charts/charts.html', chart_components) #urls.py app_name = 'charts' urlpatterns = [ path('', views.all_charts, name='all_charts'), ] For simplicity, assume that the function show_charts() returns appropriate stuff to render the charts (i.e. HTML and JavaScript, etc.) My question: is this approach recommended within … -
How can I convert raw join query into django orm query
I have three models and i want to get data related products throughout these models, there is Product Model,Product Review Model,Colour,Product Image model. I want to get model,review,colour,image of every product. Models.py class Product(models.Model): product_name=models.CharField(max_length=300,blank=True) product_description=models.CharField(max_length=5000,blank=True) sale_price=models.IntegerField(blank=True) review_count=models.IntegerField(default=3.9,blank=True,null=True) created_date=models.DateField(blank=True,null=True) category_name=models.CharField(max_length=50,null=True,blank=True) class Colour(models.Model): colour_name=models.CharField(max_length=20,blank=True) colour_product=models.ForeignKey(Product,on_delete=models.CASCADE) class ProductImages(models.Model): image=models.ImageField(upload_to='product_images',null=True,blank=True) image_product=models.ForeignKey(Product,on_delete=models.CASCADE) class ProductReviews(models.Model): product=models.ForeignKey(Product,on_delete=models.CASCADE,null=True,blank=True) stars=models.FloatField(null=True,blank=True) I have developed raw query, how can convert this query into ORM query, i have researched and checked out select_related, can someone guide how can i use this in most optimized way, below is my raw query: query = """ SELECT p.id, p.name, pi.image, r.review, c.color FROM Product as p, ProductImages as pi, ProductReviews as r, Colour as c WHERE p.id= pi.product_id AND p.id=r.product_id AND p.id=c.product_id; """ How can i use this in django ORM -
Unable to import file of another folder in Django Project
Screenshot of Error I'm unable to import class from file Views.py(location: another folder) in file urls.py It is showing error No module named VisitorAPI.views (seems like it is looking for file in same folder not in another folder) Tried various solutions but nothing is working out! -
Django Datatable View column sorting
I am using django-datatable-view from here https://django-datatable-view.readthedocs.io/en/latest/index.html. I am having some issues and the documentation doesn't seem to cover reasons as to why. My guess is that the data is not from the model itself but an annotated field added to queryset. I have a table with many field but the ones in question would be 'active' and 'get_set'. class RetailerStoresDatatable(Datatable): geo = columns.TextColumn( "Geo", sources=["geo_set"], processor="get_geo", sortable=True ) class Meta: model = StoreAddress page_length = 50 columns = [ ... "active", ] processors = { ..., "active": helpers.make_xeditable, } structure_template = "datatableview/bootstrap_structure.html" def get_geo(self, instance, *args, **kwargs): return render_to_string( "administrator/retailer_stores_columns.html", dict(column_key="get_geo", store=instance) ) class AdminRetailserStoresView(XEditableDatatableView): datatable_class = RetailerStoresDatatable def get_queryset(self): queryset = ( StoreAddress.objects.filter(...) .annotate( geo_set=Case( When(geo_lat__isnull=False, geo_lng__isnull=False, then=True), default=False, output_field=BooleanField(), ), ) ) return queryset I am filtering by active / not, and it works with below JS. Example for true. value = true $('.datatable').DataTable().columns({{ columns_map|get_dict_item:"active" }}).search(JSON.parse(value)).draw() I am trying the exact same with geo but it just ignores and returns all records that were already present. Set Geo column is True/False text. It i change "geo" to "active" just to test it filters active fine. So as above, i think it is to do with the fact … -
HttpResponseRedirect have extra path and fail
this is code views.py def monthly_challenges_by_number(request,month): months = list(monthly_challenges.keys()) redirect_month = months[month-1] return HttpResponseRedirect("challenges/" + redirect_month) def monthly_challenge(request,month): try: content_text = monthly_challenges[month] return HttpResponse(content_text) except: return HttpResponseNotFound("this is not supported!!") challenges/urls.py urlpatterns = [ path("<int:month>", views.monthly_challenges_by_number), path("<str:month>", views.monthly_challenge), ] monthly_challenges/urls.py urlpatterns = [ path('admin/', admin.site.urls), path("challenges/",include("challenges.urls")) ] error : Not Found: /challenges/challenges/february Using the URLconf defined in monthly_challenges.urls, Django tried these URL patterns, in this order: admin/ challenges/ <int:month> challenges/ <str:month> The current path, challenges/challenges/february, didn’t match any of these. i am following a django course and follow his code,but i don't know why HttpResponseRedirect is two challenges ? please help! thank you -
How to filter category wise products and display it on same all products page without creating extra category.html
I actuallu stuck on this problem that where i have an index.html page, it shows all stores and their category and if someone clicks on this category i want to filter out stores by that category and i want to show this stores on same index.html page without creating extra category.html so here my code View.py def index(request,stores_name=None): stores = stores_model.objects.all() context = {'stores': stores} return render(request,'Stores/index.html', context) def categories(request , cats): categoriesproduct = stores_model.objects.filter(scategory = cats) context = {'categoriesproduct':categoriesproduct} return render(request , 'Stores/categories.html') index.html {%for i in stores%} {{i.stores_name}} <a href={{i.get_absolute_url}}>{{i.category}}</a> {%endfor%} is any idea if someone click on category then same index.html should open and instead of all stores only stores of that category should show -
I am getting this error for deploying my app on heroku
ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-sfkqlnxn/h5py/setup.py'"'"'; file='"'"'/tmp/pip-install-sfkqlnxn/h5py/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /tmp/pip-record-rhckdime/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.9/h5py Check the logs for full command output. ! Push rejected, failed to compile Python app. ! Push failed -
Django no reverse match for view details
im stuck on show details for object, no matter i do (following all guides on internet ) still getting reverse not match error `views.py def val_details(request, id): val = Validator.objects.get(id=id) print(f'vali: {val}') context = dict(val=val) return render(request, 'users/val_details.html', context) print(f'vali: {val}') printing vali: Validator object (14) html <button class="btn btn-warning " href="{% url 'val-details' val.id %}">detals</button> urls.py path('validator/<int:id>/', user_views.val_details, name='val-details'), models.py class Validator(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=200, blank=True, null=True) address = models.CharField(max_length=200, blank=True, null=True) owner = models.CharField(max_length=250, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) def __int__(self): return self.id error django.urls.exceptions.NoReverseMatch: Reverse for 'val-details' with arguments '('',)' not found. 1 pattern(s) tried: ['users/validator/(?P<id>[0-9]+)/$'] -
TabularInline not syncing properly
I am a beginner in python-django coding. Currently, I am following a guide which is https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Admin_site. I am stuck on the last step where TabularInline is used to display all the identical books data under the same Genre. I have 2 books under the same genre 'Game'. But when I click on Books and 'Wild Rift Guide' (Book data under 'Game' genre). Another book which is also under the same genre doesnt show in tabularinline. It only shows the one I clicked. Appreciate it if anyone can help me. Thank you Codes: In admin.py from django.contrib import admin # Register your models here. from .models import Author, Genre, Book, BookInstance # admin.site.register(Book) # admin.site.register(Author) admin.site.register(Genre) # dmin.site.register(BookInstance) # Define the admin class class AuthorAdmin(admin.ModelAdmin): list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death') fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')] # Register the admin class with the associated model admin.site.register(Author, AuthorAdmin) class BooksInstanceInline(admin.TabularInline): model = BookInstance # Register the Admin classes for Book using the decorator @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'display_genre') inlines = [BooksInstanceInline] # Register the Admin classes for BookInstance using the decorator @admin.register(BookInstance) class BookInstanceAdmin(admin.ModelAdmin): list_filter = ('status', 'due_back') fieldsets = ( (None, { 'fields': ('book', 'imprint', 'id') }), … -
Django - Trying to return object.id to see item as id in list at the admin site but TypeError at /.../1/change/
I created a model and registered it for the admin site but when I enter the admin site it is shown like "intensivecare_forms_data object (1)" I just try to make it id number to see it in the list I wrote return code but when I try to click on it it gives error. class intensivecare_forms_data(models.Model): id = models.IntegerField(primary_key=True) data = models.JSONField() def __str__(self): return self.id This is the error. TypeError at /admin/DataCollector/intensivecare_forms_data/1/change/ __str__ returned non-string (type int) Request Method: GET Request URL: http://localhost:8000/admin/DataCollector/intensivecare_forms_data/1/change/ Django Version: 3.2.4 Exception Type: TypeError Exception Value: __str__ returned non-string (type int) Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/contrib/admin/options.py, line 1632, in _changeform_view Python Executable: /Library/Frameworks/Python.framework/Versions/3.9/bin/python3 Python Version: 3.9.6 -
How do I introduce a constraint in django table where 2 values of a column will be unique in a table and other rows can have duplicate pairs?
How do I introduce a constraint in django table where 2 values of a column will be unique in a table and other rows can have duplicate pairs? like a True a False a False a False but not a True a True a False a False a False -
Django admin tabular inline sorting
I am trying to implement the same way of sorting in tabular inline, like in list view. I have found and tried a couple of plugins(There is a django-admin-sortable2 enabled on the first screenshot), but none of them actually allow to click on the table head and sort by columns(See where my cursor is on screenshot). Is this even possible? Here how it is in tabular inline view Here hot it is in list view