Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrap 4 Popover not working for django Infinite Scroll
I am using bootstrap popover to show some data, in my django site. I have use infinite scroll to show list of products. We django iterate its pagination bootstrap popover don't works. page size : 3 total record : 12 For 1st 3 record popover works but for next record it won't template : <div class="row infinite-container"> {% for i in task %} <div class="col-lg-3 col-md-6 wow infinite-item"> <a href="#0" data-toggle="popover" title="Popover title" data-content="data {{forloop.counter}}" class="grid_item"> {{i.name}} </a> </div> {% endfor %} <div class="loading loader" style="display:none"></div> {% if page_obj.has_next %} <a class="infinite-more-link" style="display:none" href="?page={{ page_obj.next_page_number }}">More</a> {% endif %} </div> </div> Js code : // for infinite scroll var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); -
Saving django model formsets
I have one ModelForm and one modelformset and I want to save them in one click. My ModelForm is getting saved but modelformset. So I want to know to handle these in views.py. So please help with the modelformset. form: class someform(forms.ModelForm): name=forms.CharField(max_length=200,widget=forms.TextInput(attrs= {'class': 'form-control'})) class Meta: model=somemodel fields=['name'] formset: formset=modelformset_factory( somemodel1, fields=('desc',), extra=1, widget={ 'desc':forms.TextInput(attrs={'class': 'form-control'}), } ) These are forms and formsets. I want to know how to handle them in views.py. -
How would I print this field in Django?
So I am trying to print out a field in my models.py file to a HTML file. (I couldn't think of any other word besides print). I am able to do it for the username, but I am struggling for the description/bio in this case. I have tried things like self.user.bio, self.userprofileinfo.bio among other things models.py relevant class class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50,blank=True,null=True) last_name = models.CharField(max_length=50,blank=True,null=True) bio = models.CharField(max_length=150) image = models.ImageField(upload_to='profile_pics',default='default.png') joined_date = models.DateTimeField(blank=True,null=True,default=timezone.now) verified = models.BooleanField(default=False) def __str__(self): return self.user.username def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username','email','password') class UserProfileInfoForms(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('first_name','last_name','bio','image') user_posts.html {% extends 'mainapp/base.html' %} {% block content %} <div class="sidebar"> <p class="active" href="#">{{ view.kwargs.username }}</p> <p>{{ view.kwargs.bio }}</p> <p>Lorem</p> <p>Lorem</p> </div> {% for post in posts %} <div class="content"> <div class="post"> <h1 class='posttitle'>{{ post.title }}</h1> {% if post.published_date %} <!-- <div class="postdate"> <i class="fas fa-calendar-day"></i> &nbsp; <p>Posted {{ post.published_date|timesince }} ago</p> </div> --> <div class="posted-by"> <p>Posted by <strong>{{ post.author }}</strong> {{ post.published_date|timesince }} ago</p> </div> {% … -
Is it possible to access the Database Data inside Forms? Using QuerySet inside a Django Form (if possible)
I want to make a CheckboxSelectMultiple from the data present in DB. This data in DB is related to user using a ForeignKey. I think I can access the data of a particular user using data=user.ModelName_set.all() How can I make a CheckBoxSelectMultiple Form from this Data and save the result in different Model by connecting it to the same User? -
Django model field validators: coding style
Could you have a look at the code example below: from datetime import date from rest_framework import serializers def validate_age(date_of_birth): today = date.today() age = today.year - date_of_birth.year - ((today.month, today.day) < (date_of_birth.month, date_of_birth.day)) if (not(20 < age < 30)): raise serializers.ValidationError("You are no eligible for the job") return dob class EligibilitySerializer(serializers.Serializer): email = serializers.EmailField() name = serializers.CharField(max_length=200) date_of_birth = serializers.DateField(validators=[validate_age]) Suppose, this validate_age will not be used anywhere else. In this case a reasonable choice would be to incapsulate it inside the class as a private method. Is it possible in django somehow? If it is not possible, maybe a notation should be used? Something like this: _validate_age(date_of_birth). So that programmers should know that this function definitely is not for reusing, not for importing. -
In Django, how do I restrict certain information in a view to being viewed by the super user?
I want to have a page where anyone who is a superuser can get access to the information on a page but nobody else can do it. if (not request.user. [however I tell that someone is a superuser]): return HttpResponse('You cannot access that') with open("test.csv") as csvfile: csv_reader = csv.reader(csvfile, delimiter=',') Basically what do I need to do that sends everyone away except superusers and gives them access to the data in the csv? -
Python Django in how to daily data to weekly conversation in error in ValueError at /filter 'DATE' is not in list
I have daily data that data convert in weekly data. That in problem in error is ValueError at /filter 'DATE' is not in list view.py def filter(request): date_min = request.POST.get('date_min') date_max = request.POST.get('date_max') qs = weather_data.pdobjects.filter(DATE__range=(date_min,date_max)) df = pd.DataFrame(qs) logic = {'ET':'sum','EP':'sum','BSS':'sum','RF':'sum','WS':'sum','DT1':'sum','WT1':'sum','DT2':'sum','WT2':'sum','MAXT':'sum','MINT':'sum','RH11':'sum','RH22':'sum','VP11':'sum','VP11':'sum','CLOUDM':'sum','CLOUDE':'sum','SOIL1':'sum','SOIL2':'sum','SOIL3':'sum','SOIL4':'sum','SOIL5':'sum','SOIL6':'sum','MinTtest':'sum','MaxTtest1':'sum','MaxTtest2':'sum'} offset = pd.offsets.timedelta(days=-6) df = pd.read_clipboard(parse_dates=['DATE'], index_col=['DATE']) df = df.resample('W', loffset=offset).apply(logic) df.head() return render(request,"reports.html",locals()) ValueError at /filter 'DATE' is not in list Request Method: GET Request URL: http://localhost:8000/filter Django Version: 2.2.3 Exception Type: ValueError Exception Value: 'DATE' is not in list Exception Location: C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py in _set, line 2290 Python Executable: C:\Users\student\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.3 Python Path: ['E:\sem-7_Rupesh\Project\prectis', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32', 'C:\Users\student\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages', 'c:\users\student\src\django-import-export', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\odf', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\odf', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\odf', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\odf', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\odf', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\odf', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\odf'] Server time: Wed, 11 Sep 2019 17:52:53 +0000 -
How to modify django manytomany relationship default input selection form to Multiple Search Selection?
django manytomany relationship default input selection form default multiple selection form Multiple Search Selection dowpdown Multiple Search Selection Using default django class based Viewsto create form is not userfriendly in case of manytomany realtionship model from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) -
django concurrent bulk_create not inserting all values to database
i'm using django's bulk_create to store large amount of data to postgresql database. This is happening inside a celery task. Many instance of this tasks are invoked at once based on different parameter values. There are 4 different workers which run each task instance in parallel. When only one task instance is run, all values are getting added to database but when multiple instances are running together via different workers, only some values are getting inserted while creating a list of model objects for bulk_create, i added a print to cross check if the value was getting inserted in the list. i found that the value is always added to the list but after bulk_create, the same values don't reflect in db. I had partially solved this issue by adding time.sleep to add latency and batch_size parameter in bulk_create. But this solution is not ideal and doesn't solve the issue anymore since the data has increased. i cannot post exact code, but it is something like this: * celery task: def some_function(): param_lst=[1,3,..]#many values all_task=[] for i in param_lst: all_task.append(some_task1.si(i)) #some_task1 and some_task2 are using majorly similar only some data processing changes. both use bulk_create to store values all_task.append(some_task2.si(i)) ch … -
POST with None data in Request Factory in Django
I'm moving my django application from 1.x to 2.2, When running unit tests, I get a error about posting None as data. Is it allowed to post None in previous versions? Is there any way to post None via RequestFactory? I don't want to give a empty string, since the field needs to be validated r = RequestFactory() rr = r.post("some-url",{"name":"sri", "kd_ratio":None}) -
is it possible to apply join on tables which do not have foreign key, by specifying the id name?
I have a pre-made database in which there is no foreign key constraint. I was wondering if we can apply join in django ORM without foreign keys (I know its not the best practice but since its pre-made schema, I cant change it). I looked it up but I didn't find a solution which matches my requirements. I tried the following, https://books.agiliq.com/projects/django-orm-cookbook/en/latest/join.html Join over django models https://www.caktusgroup.com/blog/2009/09/28/custom-joins-with-djangos-queryjoin/ https://www.quora.com/How-do-I-join-tables-in-Django I have table1 TId = models.BigIntegerField(primary_key=True) field1 = models.FloatField(null=True, blank=True, default=None) field2 = models.CharField(max_length=10, default=None) field3 = models.CharField(max_length=10, default=None) field4 = models.CharField(max_length=10, default=None) and table2, SId = models.BigIntegerField(primary_key=True) field5 = models.FloatField(null=True, blank=True, default=None) field6 = models.CharField(max_length=10, default=None) field7 = models.CharField(max_length=10, default=None) field8 = models.CharField(max_length=10, default=None) I want the query to be, select t1.field1, t1.field2, t2.field5 from table1 t1 inner/outer/left/right join table2 t2 on t1.TId = t2.SId where t2.field7 = "value"; -
How to save CSV in database of Django?
I made a logic to download the CSV file but now I also want to save it in the database. I have tried to save that by the file name but that doesn't work def index(request): if request.method == "POST": url = request.POST.get('url', '') username = request.POST.get('username','') r = requests.get(url) soup = BeautifulSoup(r.content, features="lxml") p_name = soup.find_all("h2",attrs={"class": "a-size-mini"}) p_price = soup.find_all("span",attrs={"class": "a-price-whole"}) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="product_file.csv"' for name,price in zip(p_name,p_price): writer = csv.writer(response) writer.writerow([name.text, price.text]) return response csv_file = csv.writer(response) csv_save = csv_save(url=url,username=username,csv_file=csv_file) csv_save.save return render(request, 'index.html') -
Cross-database in django-import-export
I have a local table which needs to reference a view from remote database. Both models are defined in same app. Now, I want to use django-import-export to import datas from excel. But it keeps reading the wrong database. @@ My local database is sqlite and the remote one is MSSQL. Model used to access the view: class EmpView(models.Model): class Meta: db_table = 'View_Emp' managed = False indexes = [ models.Index(fields=['code',]), ] ... I set the router to let django read the remote database when the model is the view otherwise read from the default one: def db_for_read(self, model, **hints): if model.__name__ == 'EmpView': return 'emp' return 'default' when I try to import datas from excel, it shows the error: Traceback (most recent call last): File "E:\Projects\Envs\.as\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "E:\Projects\Envs\.as\lib\site-packages\django\db\backends\sqlite3\base.py", line 298, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: main.View_Emp You can tell it reads the local database, but it suppose to read the remote one. What should I do? -
Django: reverse OneToOneField matching without related_name
I have several models representing different type of user profiles, class User(models.Model): pass class ProfileA(models.Model): user = models.OneToOneField(User, related_name="%(app_label)s_%(class)s_related",) class ProfileB(models.Model): user = models.OneToOneField(User, related_name="%(app_label)s_%(class)s_related",) class ProfileC(models.Model): user = models.OneToOneField(User, related_name="%(app_label)s_%(class)s_related",) Now, let's say I get the user instance: how can I get the related profile object? All three profile models(in my code I've 6 different profile models extending BaseProfile model, which is abstract) have additional fields, and I basically need the whole profile object accessible from within User object instance. -
Deploy Django app on a server is giving me 404 with static files
I'm trying to deploy a Djagon app to a production server, but is not working, even if I seet DEBUGvariable to True. For what I understand, Heroku is collecting the static files, so should work. remote: -----> $ python manage.py collectstatic --noinput remote: 119 static files copied to '/tmp/build_80f75579ac26656d613f32473cdc0923/staticfiles', 12 unmodified. production.py from wall_web_interface.settings.common import * DEBUG = False ALLOWED_HOSTS = ['*'] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') settings = dynaconf.DjangoDynaconf(__name__) common.py """ Django settings for wall_web_interface project. Generated by 'Django-admin startproject' using Django 2.2.5. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import dynaconf # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "dkjdkjdkjdkdjkdjdi8383383j" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', 'sass_processor', 'images.apps.ImagesConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'wall_web_interface.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, … -
Django: template needs to return per-item result based on who you are
As my template loops through a list of Forum objects provided by the View, I need to present a value ("number of posts ...") that will depend on who the user is – and of course, if he is anonymous. So, I basically need to call a function, from the template, whose arguments are "the current Forum object" and "the current request – thus giving me access to the user." In order to return the appropriate integer as seen by this user. How do I do that, the Django way? -
How to stop django to automatically active users while using UserRegisterForm
views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) using RegisterForm for Registration form django automatically activate user.I want to add signup email confirmation before activating user. -
null value in column "ProjectName_id" violates not-null constraint
need help on null value in column "ProjectName_id" violates not-null constraint, im new to django i want my ProjectName_id (Foreignkey) is the same id that user choose in my majordetails = ProjectNameInviToBid.objects.get(id=sid) please help me... my model views class ProjectNameInviToBid(models.Model): ProjectName = models.CharField(max_length=255, verbose_name='Project Name', null=True) DateCreated = models.DateField(auto_now=True) class InviToBid(models.Model): today = date.today() ProjectName = models.ForeignKey('ProjectNameInviToBid', on_delete=models.CASCADE) NameOfFile = models.CharField(max_length=255, verbose_name='Name of File') my views.py def project_name_details(request, sid): majordetails = ProjectNameInviToBid.objects.get(id=sid) if request.method == 'POST': form = invitoBidForm(request.POST, request.FILES) if form.is_valid(): majordetails = InviToBid.ProjectName form.save() messages.success(request, 'File has been Uploaded') else: form = invitoBidForm() args = { 'majordetails': majordetails, 'form': form } return render(request,'content/invitoBid/bacadmininvitoBid.html', args) -
Django send_mail not working and returns 0 errors
My code executes fine from my localhost. However, when I try and run my django program from an ubuntu 16.04 server it doesn't work. I tried running the program in the shell and it doesn't return any errors. When I check my inbox I don't receive an email from the "from" address. I've tried sending the email to different addresses. I've also tried sending it using TLS instead of SSL. I also tried using smtplib to send the email instead of using django's send_mail. Here is my code I'm using to send the email send_mail('subject','my message','from_email@gmail.com',['to_email@xxxx.com'],fail_silently=False) Here is my settings.py file EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'from_email@gmail.com' EMAIL_HOST_PASSWORD = '*******' EMAIL_PORT = 465 -
A pythonic way to get a list filtered by a Django table
I need to filter a list like this: A = ['a','b','c','c','d','e'] and I have a Django model T that contains a field unique which I know if the element is the same or not. Lets say T(id, name_unique,...others_fields). Lets say T has id, name... (1, 'b',...) (2, 'c',...) (3, 'f',...) (4, 'g',...) and alot rows more I need a way (pythonic) to get a list A filtered by distinct and non repeated from name_unique, so the output should be A' = ['a', 'd', 'e'] -
Server Error (500) when logging into admin panel
After deploying my project I have my project in /svr and when i go to login to my admin panel I get Server Error (500) I'm guessing this is because the permissions on my database are not correct. I tried running chown www-data db.sqlite3 but I'm still getting this error. -
This problem "duplicate key value violates unique constraint" has been real pain on my ass for nearly a week
I am trying to create a video blog where users will be able to create their own account and profile. I have also added email verification with for registration. But the problem is when I try to register a new user from Django 2.2.5 development server I get this error ( "duplicate key value violates unique constraint" "account_profile_mobile_number_key" DETAIL: Key (mobile_number)=() already exists. ) repeatedly. I thought if I delete the database this might solve the problem. I deleted the database and create another one. Then I have been able to create a user but again that problem occurred. I delete the database again. This way I have tried so many times but couldn't able to solve the problem. I googled for the solution and got lot of answers but they are very tough for me to understand as I am just in the learning process. I am using Python 3.6, Django 2.2.5, Postgresql 11 on Ubuntu 18.04. Guys could you please see my codes and show me the easiest way to solve the problem? Thanks in advance! Here is the Traceback IntegrityError at /account/register/ duplicate key value violates unique constraint "account_profile_mobile_number_key" DETAIL: Key (mobile_number)=() already exists. Request Method: POST … -
Can django integration zerorpc?
I'm intending to use rpc in my django project.And I found zerorpc is a beautiful lib for rpc.So I want to intrgration django with zerorpc. What is the best practice? And how to start the zerorpc server in production?Thanks! -
Server TTFB takes too long on Chrome
It seems on some pages on the localserver, it takes upward of 40secs on the TTFB as shown by Chrome's Network > Timing. On other pages, it takes 8 seconds. I am running Django's localserver and preparing to lunch the site soon, so I'd like to know: 1) Is it something peculiar to Django's local server? 2) Why is there such a difference in loading time between different pages on the TTFB (Time spent waiting for the initial response, also known as the Time To First Byte) 3) Does this go away once it is lunched on a real server or should I dig for some serious problem in the code base? -
How to fix the "The requested URL was not found on this server" apache2 + django + ec2?
I'm doing the deploy of a website built with django and python2.7 on an EC2 instance and using apache2. I've being following some tutorials and none of them worked for me. I currently installed the apache, configured it to see the project and even configured the permissions. The project directory: | |-ubuntu | |- jendalma |--apps |--media |--promotions |--sellerlogin |--templates |--frobshop | |---frobshop | |---setting.py |---wsgi.py |---urls.py |---static 000-default.conf - apache <VirtualHost *:80> ServerAdmin <jendalma@gmail.com> WSGIScriptAlias / /home/ubuntu/jendalmaShop/frobshop/frobshop/wsgi.py Alias /static/ /home/ubuntu/jendalmaShop/frobshop/frobshop/static/ Alias /media/ /home/ubuntu/jendalmaShop/frobshop/media/ <Location "/static/"> Options -Indexes AllowOverride none Require all granted </Location> <Location "/media/"> AllowOverride none Require all granted </Location> <Location "/"> AllowOverride none Require all granted </Location> <Directory "/home/ubuntu/jendalmaShop/frobshop/frobshop/wsgi.py"> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> urls: js_info_dict = { 'packages': ('stores',), } admin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^i18n/', include('django.conf.urls.i18n')), # Stores extension url(r'^stores/', stores_app.urls), url(r'^dashboard/stores/', dashboard_app.urls), # PayPal extension url(r'^checkout/paypal/', include('paypal.express.urls')), # Datacash extension url(r'^dashboard/datacash/', datacash_app.urls), url(r'^dashboard/login/$', DashAccountAuthView.as_view(), name='login'), url(r'^dashboard/register/$', DashAccountRegistrationView.as_view(), name='register'), url(r'^dashboard/methods/shipping/$', methods), url(r'^dashboard/methods/shipping/change/$', change_method), url(r'^currencies/', include('currencies.urls')), url(r'^customer/', include('sellerlogin.urls')), url(r'', application.urls), ] if settings.DEBUG: import debug_toolbar urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] admin.site.site_header = "Jendalma Express Admin" admin.site.site_title = "Jendalma Express Admin" admin.site.index_title = "Welcome to Jendalma Express" The …