Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Building an AJAX pagination
I am building an AJAX pagination for my Django Project. Couldn't find any decent tutorial so I started on my own, step after step, debugging with the console. But I am not an expert in JQuery but love how AJAX bring any app to the next level. I want to display a list of users favorites products and I want the user to navigate through it with AJAX. Pagination is set to five. Here is my code o far: views.py: def nav(request): data = {'saved_list': 0} if request.method=='POST': user_id = request.user sub_list = SavedProduct.objects.filter(username=user_id) paginator = Paginator(sub_list, 5) page = request.POST.get('page') saved_list = paginator.get_page(page) data['saved_list']= saved_list return JsonResponse(data) urls.py: app_name = 'register' urlpatterns = [ path('nav/', views.nav, name='nav') ] My AJAX: $(".nav_button_2").on("click", function(event) { event.preventDefault(); var page = $(this).val(); var url = '/register/nav/'; $.ajax({ url: url, type: "POST", data:{ 'page': page, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(data) { if (data['saved_list']) console.log('working so far'); } }); }); My AJAX is not complete because I debug it after each new step. Now when I run my code, I have this error: TypeError: Object of type Page is not JSON serializable. What I understand is that I can't send data['saved_list'] back to AJAX. … -
Tools required for creating a website to verify authenticity of social media posts
I'm working on a project where users can report social media posts they feel are spreading fake information on a website. I have no experience with web development and even for machine learning, I've only completed Andrew Ng's course on Coursera. I've learnt some basic html/css and some very basic django. This project is actually more of a research-oriented one and I'm not expected to actually create a working website. But I really want to create one even if it is barely functional. I have come up with what I believe is a concrete work plan, and I am looking for the tools that could help me realize the plan in about 10 days. What I intend to do: The user will be asked to put up the link to the post they feel is fake, along with some additional information such as the place, time etc mentioned in the post, and a single line summary of the post(not exceeding a certain number of characters). So for eg. if the post is about "Extension of Lockdown till Aug 1st in India", they would post the link along with the "place and time period mentioned" as "India" and "Aug 1st", "Summary": … -
Inline Editing of Textarea with jquery.inline-edit.js – Get the id and save
I am looking for a simple way to implement inline editing in a table (with Django). I did not test stuff like Django-Front or django-inlineedit so far. I already found out, that not all simple solutions work for me. jqInlineEdit and inline-edit.jquery.js do work only with unique selectors, as I described here. With jQuery.editable (jquery.inline-edit.js), I do not have these problems, but I do not know how to get the id and save the data. <div id="remark4" class="remark">Test #4</div> <div id="remark5" class="remark">Test #5</div> <div id="remark6" class="remark">Test #6</div> <script src="file:jquery.inline-edit.js"></script> <script> $('.remark').inlineEdit('click', { // use textarea instead of input field type: 'textarea', // attributes for input field or textarea attributes: { id: 'remark14755', class: 'input-class-1 input-class-2 input-class-3', style: 'background:#ffe;' } }); </script> How can I get const c_id = $(this).attr("data-cid"); and let's say alert(c_id + content) running after the content in the form has changed? I did not found a documentation or an example for that and trial and error was not successful so far. -
Local -> Github working | Github -> Heroku not working
I have a Django application which is present in my local system. As I want to ignore db.sqlite3 files while transferring the repository, I have put the following in .gitignore db.sqlite3 I push it to Github using: git push origin master When I do this, the updated db.sqlite3 from local system is NOT transferred to git. As the next step, I need to transfer the files from local system to Heroku using: git push heroku master However, it seems that the file from Github is copied to heroku, which is weird. Perhaps my understanding of the git push heroku master is incorrect. Deployment method is using heroku cli To check this weird way of working : I added couple of entries in db.sqlite3 in my local system I made a small change to the code in my local system I made new entries in the Django application which is deployed to heroku I pushed the application to Github using git push origin master and checked the timestamp on db.sqlite3 in git and it wasn't changed - I downloaded the db.sqlite3 from git and checked, the new entries that I made to the local system weren't there. This is good. I … -
django email authentication with mysqll
my code it not working it never log me but runs without errors i am using mysql database i tried alot to solve it but i wasnt able to solve it as i am new to python web programming please help. views.py from django.shortcuts import render from django.contrib.auth import authenticate from Play.models import user from django.contrib.auth.models import User from django.contrib.auth.models import auth from django.shortcuts import redirect from django.shortcuts import HttpResponse from django.contrib.auth.hashers import make_password def JoinRequest(request): if request.method == 'POST': fullname = request.POST['fullname'] email = request.POST['email'] phone = request.POST['phone'] password = request.POST['password'] cpassword = request.POST['cpassword'] #encpass = make_password(password) def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') return ip if password != cpassword: return HttpResponse('Password Not Matching To Confirm Password Value..') else: senddata = user(fullname=fullname, email=email, phone=phone, password=password , ipaddress=get_client_ip(request)) senddata.save() return HttpResponse('') def Join_View(request): return render(request, 'Join.html', {}) def login_view(request): return render(request, 'Login.html', {}) def LoginREQUEST(request): if request.method == 'POST': username = request.POST['email'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponse('DONE') else: return HttpResponse("NONE") EmailAuthentication.py from django.contrib.auth import get_user_model from django.http import HttpResponse from django.contrib.auth.backends import ModelBackend as _ModelBackend User = get_user_model() class EmailOrUsernameModelBackend(_ModelBackend): """ Authenticate … -
Facing Multi Dict Key Error while integrating facebook api endpoint
I'm trying to include facebook messenger in my project. My requirements is just to send message to the facebook page when ever any user submit a form. But before that, i want to just test facebook api endpoint. But unfortunately I'm facing error. views.py class YoMamaBotView(generic.View): def get(self, request, *args, **kwargs): if self.request.GET['hub.verify_token'] == '2318934571': return HttpResponse(self.request.GET['hub.challenge']) else: return HttpResponse('Error, invalid token') and here is callback settings -
Django: create a database that allow user to create character templates and then to create characters based on those
I am currently re-learning computer programming, 5 years after completing my University related courses, and I lost almost all of my knowledge and I am back to a beginner's level. I am trying to learn how to do a website using Python (3.8.3) and Django (2, 2, 13, 'final', 0), with the default SQLite database. My long term goal would be to create a personnel Website with multiple apps (e.g. Forum, Blog about multiple theme...) and my priority is focused towards creating a Roleplay management app, but I'm having trouble understanding how to create my database or what to use. I want the following requirements : A table containing Users personnals information Each User can create « Worlds » where they are gamemasters ; They can create multiple worlds A gamemaster is able to create a character template, which allows to define min, max, default and distributable stats, spells format, inventory size and objects A gamemaster will be able to create items that aren't in any inventories and to give them later When creating a new World, the gamemaster can link multiple character templates to the world ; Those stats can be separated into groups (e.g. main stats and secondary … -
Django redirect doesn't work in class based view
I have a class based view which i am checking some conditions and redirecting to another page, i see the GET request to that page in the terminal and it returns 200, but it doesn't redirect to the page: class CheckoutFinalView(CartOrderMixin, View): def post(self, request, *args, **kwargs): return redirect("carts:success") I tried return HttpResponseRedirect(reverse('carts:success')) , too. But it doesn't work, too. -
Django user settings model
would it be wise to create a custom user model if I wish for settings to be tied to the user (AbstractUser would be used)? the other seemingly simpler option would be to create a Settings model in my main app and tie it to the user with a foreign key. some examples would be private profile, hidden in search, profile pictures -
Error:Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name
I am having a problem with the password reset . Its works perfectly if i delete the namespace app_name = 'crm' . But when i include app_name = 'crm' i get the error, Error: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. But I want it to work without removing the namespace. My urls.py from django.urls import path from . import views from django.contrib.auth import views as auth_views app_name = 'crm' urlpatterns = [ path('', views.home, name='dashboard'), path('login/', views.loginPage, name='login'), path('register/', views.registerPage, name='register'), path('logout/', views.logoutUser, name='logout'), path('reset_password/', auth_views.PasswordResetView.as_view(), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), ] -
Render celery task staus in Django
I am currently using Django for my Project. In which I am saving DB backups. Db Backups are large in size so I am handling this activity with Celery as an async mechanism with Redis broker. Task works perfectly. Now I want to get the status of my task which was with celery for operation. I am currently looking to render the progress bar on the Html page so that the user can see the status of the task initiated in the celery. -
Django: TypeError at / context must be a dict rather than tuple
I keep getting an error message when executing this views settings: from django.shortcuts import render # Create your views here. def home_screen_view(request): print(request.headers) return render(request, 'base.html', ()) so I need your help -
int() argument must be string, a bytes-like object, not 'ObjectId'
I am following this tutorial for using MongoDB and Django with djongo. I am having an error creating the items of this model, but I am following the tutorial closely and I don´t really know what´s the problem. I show here the code from the models, the views and the serializer: class Piso(models.Model): nombre = models.CharField(max_length=30,blank=False,default=''); habitantes = models.CharField(max_length=202,blank=False,default=''); class PisoSerializer(serializers.ModelSerializer): class Meta: model = Piso fields = ('id','nombre','habitantes') And the view method: @api_view(['POST','GET']) def piso_list(request): # GET list of tutorials, POST a new tutorial, DELETE all tutorials if request.method == 'POST': piso_serializer = PisoSerializer(data=request.data) if piso_serializer.is_valid(): piso_serializer.save();#This is the object I fill return JsonResponse(piso_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(piso_serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'GET': pisos = Piso.objects.all() name = request.GET.get('name', None) if name is not None: pisos = pisos.filter(nombre__icontains=name) pisos_serializer = PisoSerializer(pisos, many=True) return JsonResponse(pisos_serializer.data[0], safe=False) # 'safe=False' for objects serialization The problem is that the object does not save the id column of my object in the database, which is created automatically. This is the object the MongoDB saves: { "_id": { "$oid": "5edd1014b9ca43bdef186d38" }, "nombre": "iddyo", "habitantes": "yeto" } It´s probably a stupid error but I can´t get my head around it. Thanks a lot! -
Django: save an empty parent object via formset (using inlineformset_factory)
I thought I've got how forms and formsets work, but finally stuck. - How to save empty object as placeholder parent for a child object? - Do I correctly use inline formsets with form passing all of them to template? - Isn't it easier to just use forms? I have chain of models: - Theme (with title field), which can have - Description (with optional text field), which can have - Url (with name and URL fields) # models.py class Theme(models.Model): title = models.CharField(max_length=256) class Description(models.Model): description = models.TextField( blank=True ) theme = models.OneToOneField( Theme, null = True, blank = True, on_delete = models.CASCADE, ) class Url(models.Model): name = models.CharField(max_length=32) url = models.URLField() description = models.ForeignKey( Description, null = True, blank = True, on_delete = models.CASCADE, ) (My goal is that) Description can be empty, but have a URL (later several Url objects). (1) I use inline formsets via inlineformset_factory (and not sure if I do it any correctly): # forms.py class ThemeForm(forms.ModelForm): class Meta: model = Theme fields = ['title'] class DescriptionForm(forms.ModelForm): class Meta: model = Description fields = ['description'] class UrlForm(forms.ModelForm): class Meta: model = Url fields = ['name', 'url'] DescriptionFormSet = forms.inlineformset_factory( Theme, Description, form=DescriptionForm, exclude=[], can_delete=False … -
Code from Celery in __init__.py breaks Django
I was following this guide: First steps with django and it tells you to add this to your __init__.py: __init__.py from consumer.celery import app as celery_app __all__ = ['celery_app'] however, when I do that my django app wont start anymore stating: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. searching for this I dound the following answer on stackoverflow. In the accepted answer the OP states that they had some code in their __init__.py and that moving it fixed their problem. It also does for me. I find this really odd since it is a guide is from the official celery documentation and I also dicovered this only fails if I try to import a django model in my tasks.py file: tasks.py from celery import shared_task from .models import myModel # this import breaks my app @shared_task def filter_task(message): result = myModel.objects.filter(id=message['id']) print(result.length) # I haven't been able to test this line yet due to the error Note that with the code in __init__.py both pyhton manage.py runserver and celery -A myworker worker -l info fail. But when I make __init__.py emty, only the latter fails with the following error message: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either … -
UpdateView not saving changes
my UpdateView is not saving the new changes and showing no errors models.py class Service(models.Model): type_ch = [('credit','credit'),('game','game')] currency_ch = [('€','€'),('$','$'),('DZD','DZD'),('Unit','Unit')] distributor = models.ForeignKey(Distributor,on_delete=models.SET_NULL,null=True,blank=False) model = models.CharField(choices=type_ch,max_length=20,null=True,blank=False) name = models.CharField(max_length=200,null=True,blank=False) price = models.FloatField(default=0.00) currency = models.CharField(choices=currency_ch,max_length=20,null=True,blank=False) available = models.FloatField(null=True,blank=False) note = models.TextField(null=True,blank=True) image = models.ImageField(default='defser.png') def __str__(self): return self.name forms.py class ServiceForm(forms.ModelForm): class Meta(): model = Service fields = ['distributor','model','name','price','currency','available','note','image'] def __init__(self, *args, **kwargs): super(ServiceForm, self).__init__(*args, **kwargs) self.fields['model'].widget.attrs['class'] = 'form-control-account' self.fields['name'].widget.attrs['class'] = 'form-control-account' self.fields['distributor'].widget.attrs['class'] = 'form-control-account' self.fields['price'].widget.attrs['class'] = 'form-control-account' self.fields['currency'].widget.attrs['class'] = 'form-control-account' self.fields['available'].widget.attrs['class'] = 'form-control-account' self.fields['note'].widget.attrs['class'] = 'form-control-account' views.py class ServiceUpdateView(UpdateView): model = Service template = "app/service_form" form_class = ServiceForm service_form.html <form class="needs-validation" action="." method="POST" enctype='multipart/form-data'> {% csrf_token %} <div class="form-group"> <label>Distributor: <small class="text-muted"> (select your own distributor accountt)</small></label> {{ form.distributor}} </div> <div class="form-group"> <label>Type:</label> {{form.model}} </div> <div class="form-group"> <label>Service Name:</label> {{form.name}} </div> <div class="form-group"> <label>Service Currency:</label> {{form.currency}} </div> <div class="form-group"> <label>Amount Available:</label> {{form.available}} </div> <div class="form-group"> <label>Price For Unit: DZD</label> {{form.price}} </div> <div class="form-group"> <label>Note:</label> {{form.note}} </div> <div class="form-group"> <label for="exampleFormControlFile1">Service Image</label> {{form.image}} </div> <hr> <button type="submit" class="btn btn-primary">Submit</button> </form> i'm trying to allow the user to be able to change all the values of the saved service but when i press the submit button it redirects me back … -
Can't find django-html in “Select Language Mode” in VS Code
I have tried to set django-html as the language for my django template files by adding this to settings.json: "files.associations": { ".html": "html", "/templates//.html": "django-html" but instead, the language sets as a plain text. -
Is it good to keep cart items in local or cookie storage before confirming the order by user?
I'm building the E-commerce website using Django. When a user select items with quantity, the list is formed and total price is calculated on every addition of item. Objective: to keep the order (cart items) details saved even if the user leaves the browser window before confirmation and checkout process. Now for this purpose, there are two options (that i know): to save all the cart items in database even before user confirms it, (but this would be unnecessary records in database because he doesn't confirms the order) to use localStorage / webStorage / Cookie storage. (but there would be a risk that someone changes the cookie , or local storage variables which contains item ids, quantities etc) you can tell me the best methods you know for this purpose. Thanks in advance. -
command 'gcc' failed with exit status 1 when building wheel for pdftotext
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-vu13x6kn/pdftotext/setup.py'"'"'; __file__='"'"'/tmp/pip-install-vu13x6kn/pdftotext/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-quoxq88r remote: cwd: /tmp/pip-install-vu13x6kn/pdftotext/ remote: Complete output (14 lines): remote: /app/.heroku/python/lib/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'long_description_content_type' remote: warnings.warn(msg) remote: running bdist_wheel remote: running build remote: running build_ext remote: building 'pdftotext' extension remote: creating build remote: creating build/temp.linux-x86_64-3.6 remote: gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DPOPPLER_CPP_AT_LEAST_0_30_0=0 -I/app/.heroku/python/include/python3.6m -c pdftotext.cpp -o build/temp.linux-x86_64-3.6/pdftotext.o -Wall remote: pdftotext.cpp:3:10: fatal error: poppler/cpp/poppler-document.h: No such file or directory remote: #include <poppler/cpp/poppler-document.h> remote: ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ remote: compilation terminated. remote: error: command 'gcc' failed with exit status 1 remote: ---------------------------------------- remote: ERROR: Failed building wheel for pdftotext I am using Python 3.7.0, Django 3.0.4, and trying to host in Heroku. Every time I tried to push into the master of Heroku, it occurs the following error. Could anyone please help me out? -
Django - How to shape and group data to send into serializer (DRF)
I am working on data visualisation, and hence my data has to be shaped in a specific format, but for now, I am using for loops and assigning to dictionaries and lists before passing the final data into a serializer (which is extremely messy) and I was wondering if there is any better way to do it using Django. Here is my models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.ForeignKey('SalesDepartment', related_name='users', blank=True) class SalesDepartment(models.Model): department_id = models.AutoField(primary_key=True) department_name = models.CharField(max_length=100) class CustomerInformation(models.Model): status = ( ('lead', 'Lead'), ('client', 'Client'), ) customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=100) status = models.CharField(max_length=100, choices=status, default='lead') creator = models.ForeignKey('UserProfile', related_name='customers', on_delete=models.CASCADE, null=True, blank=True) created_date = models.DateField(default=timezone.localdate) Basically I want my data to look something like this { department: DepartmentA, department_data: [ { date: 010620, formatted_date: 'June 2020', lead_count: 20, client_count: 12 }, { date: 010520, formatted_date: 'May 2020', lead_count: 34, client_count: 19 } ], users: [ { user: UserA, user_data: [ { date: 010620, formatted_date: 'June 2020', lead_count: 5, client_count: 2 }, { date: 010520, formatted_date: 'May 2020', lead_count: 8, client_count: 3 } ] }, { user: UserB, user_data: [ { date: 010620, formatted_date: 'June 2020', lead_count: 10, client_count: 2 }, { date: … -
importing django-tables2 issue
I download 'django-tables2' inside venv, and i when I add django_tables2 to my INSTALLED_APPS INSTALLED_APPS = [ ...... #'search_listview', #'django_filters', 'django_tables2', #'sweetify' ] TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ .... 'django.template.context_processors.request', ], }, }, ] i receive this and i tried also 'django-tables2', i still receive this error -
TypeError at /addreview Field 'id' expected a number but got <built-in function id>
Recently I'm working to make an e-commerce website using django, my problem is the views are stuck on an error says that the rproduct_id requires id, but whenever i assign id to that field, it shows me this type of error.I am stucked at this point for hours. Here is my code, models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.conf import settings from django import forms class Category(models.Model): Categories = [ ("Pens & Stationary", "Pens & Stationary"), ("Arts & Crafts", "Arts & Crafts"), ("Notebooks & Fullscapes", "Notebooks & Fullscapes"), ("Files & Folders", "Files & Folders"), ("Others", "Others") ] cname = models.CharField(max_length=50, choices=Categories) cicon = models.CharField(max_length=50,default="fa fa-lg") cslug = models.SlugField(max_length=200, db_index=True, unique=True) def __str__(self): return self.cname def get_absolute_url(self): return reverse('store:product_list_by_category',args = [self.cslug]) # Create your models here.""" class Product(models.Model): pimg = models.ImageField(upload_to='pics',null = True, blank=True) pname = models.CharField(max_length=100) pslug = models.SlugField(max_length=50, db_index=True, unique=False) pprice = models.DecimalField(max_digits=10, decimal_places=2) pstock = models.BooleanField(default=True) pcats = models.ForeignKey(Category, on_delete=models.CASCADE) pdesc = models.TextField() def __str__(self): return self.pname def get_absolute_url(self): return reverse('store:product_details',args = [self.id,self.pslug]) class ExploreItems(models.Model): eitname = models.CharField(max_length=50) eitimg = models.ImageField(upload_to='pics') eitdesc = models.CharField(max_length=200) def __str__(self): return self.eitname class Review(models.Model): rsummary = models.CharField(max_length=500) mreview = models.TextField() rproduct = models.ForeignKey(Product,on_delete=models.CASCADE) ruser … -
Python virtual environment doesn't work the second time
Yesterday I started to study Django. I created a virtual environment and it worked. Today I ran the activate script, the env name appears on terminal, but when I try to execute "django-admin --version" I got this: Fatal error in launcher: Unable to create process using '"d:\documentos\dev\python\ecommerce-example\django-tutorial\venv\scripts\python.exe" "D:\Documentos\dev\python\django-tutorial\venv\Scripts\django-admin.exe"> --version' I've already search, but I didn't found anything about activate venv for the second time. Can someone help me? -
Showing python console on webpage with django
I am have a function like this: def myfunc(x): # Loop over the imagePaths for i in range(N): # do somthing print("[INFO] processing {}/{}".format(i + 1, N)) print(name) print(total, " things I have done.") the user will fill a form on my webpage and then I will run this function. Running it would take a bit of time, so I want to show the progress (the prints in the myfunc). I saw some answers in How do I redirect my Python console's output to a web page in Django? and How can you display the results of a script in real-time for a Django 1.4 website?. But honestly I'm not that good at Django nor JavaScript to know what I should do with the information above. I also understand that many version of this question has been asked but I couldn't figure out how to use their answer. -
Django migrations not persisting
My django app is containerized along side postgresql. The problem is that migrations do not seem to be persisting in the directory. Whenever I run docker exec -it <container_id> python manage.py makemigrations forum, the same migrations are detected. If I spin down the stack and spin it back up the and run makemigrations again, I see the same migrations detected. Changes to the fields, adding models, deleting models, none ever get detected. These migrations that do appear seem to be getting written to the database, as when I try to migrate, I get an error that there are existing fields already. But if I look at my migrations folder, only the init.py folder is present. All the migrate commands add no changes to the migrations folder. I also tried unregistered the post model from the admin and spinning up the stack, yet I still see it present in the admin. Same things with changes to the templates. No change I make sticks from inside docker seems to stick. *Note this problem started after I switched to wsl 2 and enabled it in docker desktop (windows)