Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I quickly get a weighted random instance of a Django model instance based on a weight field on that model?
I'm using Postgres as the database backend but I don't think that will matter. Also, I'd like to still use sqlite3 as the local development database, so ideally any approach will work for both. By "weighted", I mean that some items in that database table are more likely to appear than others based on a heuristic value ranging from 0 to +inf where 0 is "never going to be picked", 1 is "as equal to be picked as any other instance, and 2 is "twice as likely to be picked than any other instance". I've read other SO posts about pulling random instances of models, but as far as I've seen there are no ways to do this quickly involving weights. My model: Has millions of instances. Has a weight DecimalField which can be updated at any time, even during runtime. Is not referenced anywhere except for using this random selection algorithm (so, for example, it can be deleted and recreated at any time with no problems). What I'm after is a fast way to do this that is faster than the solutions I've tried or an explanation to why one of my solutions that I've tried is the fastest … -
how to get the values from a nested queryset of list in python?
table structure: ------------------------------------- | id | keywords | ===================================== | 1 | animals,orange ball | |-----------|-------------------------| | 2 |animals,pet, dog,as usual| |-----------|-------------------------| | 3 |'anime, animations,superhero,cartoon'| |_____________________________________| views.py TagList = ImgDetails.objects.values_list('keywords').order_by('keywords') I'm getting value from database in a queryset: output: <QuerySet [('animals,orange ball',), ('animals,pet, dog,as usual',), ('animals',), ('animals',), ('animals, pet,dog',), ('animals, pet,dog',), ('animals, pet,dog',), ('animals,fore st,tiger,lion',), ('animals,forest,tiger,lion',), ('animation,sasuke,cartoon,anime',), ('anime, animations,superhero,cartoon',), ('anime, animations,superhero,cartoo n',), ('anime, animations,superhero,cartoon',), ('anime, animations,superhero,cartoon',), ('cat,deer',), ('cat,deer',), ('nature, forest, greenry',), ('nature, fores t, greenry',), ('nature, forest, greenry',)]> I want to fetch all the unique values or your can say string from the queryset in a list like this: ['animals','orange ball','anime','animations','superhero','cartoon','dog','tiger','forest','animation'] I can use nested for loop to get it done. But is there any simple way to get string from queryset in a list. -
Django open word/XL file in webpage on editable format and auto save
I am trying to create a simple program where it allows to open an uploaded file on a webpage in a editable format and auto save. -
manager_method() got multiple values for argument 'self' While making changes in Django in add profile manually
I got this error when i tried to edit the existing user data It also shows error in self and profile in vs code Self = Instance of 'OneToOneField' has no 'username' memberpylint(no-member) in def str Profile =Class 'Profile' has no 'objects' memberpylint(no-member) def __str__(self): return f"{self.user.username}-{self.created}" def save(self , *args , **kwargs): ex=False if self.first_name and self.last_name: to_slug = slugify(str(self.first_name) + " " + str(self.last_name)) ex = Profile.objects.filter(self=to_slug).exists() while ex: to_slug = slugify(to_slug + " " + str(get_random_code())) ex = Profile.objects.filter(self=to_slug).exists() else: to_slug = str(self.user) self.slug = to_slug super().save(*args,**kwargs) -
Form keeps submitting after refreshing the page in Django?
I have a comment section for my posts and when i submit a comment and then refresh the page after it keeps adding the same comment to the post. I think i kind of know that i should redirect the page, but i am confused where i should redirect. Here is my. code: def post_detail(request, year, month, day, post): #some code if request.method == 'POST': new_comment.save() return HttpResponseRedirect(reverse("blog:post_detail")) else: comment_form = CommentForm() return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, 'similar_posts': similar_posts, 'tags': tags }) I guess the problem is here-- blog:post_detail-- where should i redirected if this us a url when i submit a comment form: http://127.0.0.1:8000/2020/8/13/post1/ urlpatterns = [ # post views path('', views.post_list, name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail,name='post_detail'), path('<int:post_id>/share/',views.post_share, name='post_share'), path('tag/<slug:tag_slug>/',views.post_list, name='post_list_by_tag'), path('feed/', LatestPostsFeed(), name='post_feed'), path('search/', views.post_search, name='post_search'), path('about/', views.about, name='about_page'), path('contact/', views.contact, name='contact_page'), ] And my post is in detail.html template Any help will be appreciated. Thank you -
How do I access the value of the parent class in Django?
So I have two models here class ProductType(models.Model): product_type = models.CharField(max_length=50) def __str__(self): return self.product_type class Product(models.Model): product_name = models.CharField(max_length=50) product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE) product_image = models.ImageField(blank=False, null=False, upload_to="products") product_price = models.FloatField() product_description = models.TextField(default="Product Description") def __str__(self): return self.product_name And I have created an api using django-rest-framework to be consumed by the React frontend. However, when I try to get the product_type, it'd just give me a number instead of the name as shown below. So, how can I replace that when retrieving the data with Product.objects.all() in the view? -
Adding searchable modelchoice field to template Django
I tried to use django-autocomplete-light to create a searchable dropdown field, but I faced problem while trying to add it to the html template. How can I do this? Simple {{form.city}} doesn't work My view: class OrderAutoCompleteCity(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Warehouse.objects.distinct().values('address') if self.q: qs = qs.filter(address__istartswith=self.q) return qs Form: class OrderCreateForm(forms.ModelForm): city = ModelChoiceField(queryset=Warehouse.objects.distinct().values('address'), widget=autocomplete.ModelSelect2(url='orders:city_autocomplete')) post_office_address = ModelChoiceField(queryset=Warehouse.objects.filter(address=city)) class Meta: model = Order fields = ( 'first_name', 'last_name', 'patronymic', 'email', 'phone_number', 'address',) Urls: urlpatterns = [ path('create/', views.order_create, name='order_create'), url(r'^city-autocomplete/$', views.OrderAutoCompleteCity.as_view(), name='city_autocomplete'), ] Warehouse model: class Warehouse(models.Model): title = models.CharField(_('Title'), max_length=255, db_index=True) address = models.CharField(_('Address'), max_length=255, db_index=True) @property def full_name(self): return '{}, {}'.format(self.title, self.address) def __str__(self): return self.full_name class Meta: verbose_name = _('Warehouse') verbose_name_plural = _('Warehouses') -
How to apply a CheckConstraint on creation only
I have a model with a models.DateTimeField field and a CheckConstraint that prevents it from being in the past: from django.db.models.functions import Now class MyModel(models.Model) mydate = models.DateTimeField() class Meta: models.CheckConstraint( check=Q(mydate__gte=Now()), name='mydate_no_past' ), I want the constraint to apply only when the record is first created. In the above example, if a valid entry is created but then later the system datetime moves past the mydate value, when the record is updated the CheckConstraint fails. How do I avoid this? -
Not Found: /Media/Uploads/ Ckeditor Django
Hello, I have problem to showing image on the website page with Ckeditor. I think, I have done all I need to show a image but I still getting Not Found. Here is some pics of what I have already done. I can see it in the admin panel and in source page show it to me. beside that even make some space for a pic in the page but still show me nothing! I'm using Django 3 and Python 3.8 Thank you in advance for your helping. Admin Panel: Source Code: Settings: URL: Template: Model: -
How to connect deployed Heroku app to Django server
I have deployed heroku app that is based on Django, and React but whenever i want to login into the deployed app i'm getting an error POST http://localhost:8000/api/auth/jwt/create/ net::ERR_CONNECTION_REFUSED Initially i had my react login api as http://localhost:8000/api/auth/jwt/create/ then changed it to http://127.0.0.1:8000/api/auth/jwt/create/ but i keep getting the same error. login file in react // LOGIN export const login = (email, password) => async (dispatch) => { const body = JSON.stringify({ email, password }); await axios .post("http://127.0.0.1:8000/api/auth/jwt/create/", body) .then((res) => { try { dispatch({ type: LOGIN_SUCCESS, payload: res.data, }); dispatch(createMessage({ login: "Login Successful" })); } catch (error) { console.log(res, error); } }) .catch((err) => { console.log(err); dispatch({ type: LOGIN_FAIL, }); }); } -
how to add a field to User.groups.through in Django?
I want to add my field to the table user_user_group. I can add a field to table groups but I can not add a field to the many-to-many group field in the user model. I use a monkey solution for add field to groups model but it does not work for many-to-many group field in the user model. this code work: Group.add_to_class('type', models.IntegerField(choices=RoleType.choices, default=RoleType.ADMIN)) this code does not work: User.groups.through.add_to_class('organization', models.ForeignKey(Organization, on_delete=models.CASCADE, null=True)) are you have any solution? solve this solution or tell me other solution -
Error: Target WSGI script "my_app"/wsgi.py' cannot be loaded as Python module (Windows OS launch deploy to linux)
I am trying to deploy a django app on aws eb and am getting an error. I have been trying to resolve the issue for 3 days and have had no luck The aws server log outputed the following: /var/log/httpd/error_log [Sat Aug 15 05:54:03.377524 2020] [suexec:notice] [pid 3086] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Sat Aug 15 05:54:03.392927 2020] [http2:warn] [pid 3086] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm will just not do. This is an advisory warning. Your server will continue to work, but the HTTP/2 protocol will be inactive. [Sat Aug 15 05:54:03.392941 2020] [http2:warn] [pid 3086] AH02951: mod_ssl does not seem to be enabled [Sat Aug 15 05:54:03.393376 2020] [lbmethod_heartbeat:notice] [pid 3086] AH02282: No slotmem from mod_heartmonitor [Sat Aug 15 05:54:03.393447 2020] [:warn] [pid 3086] mod_wsgi: Compiled for Python/3.6.2. [Sat Aug 15 05:54:03.393453 2020] [:warn] [pid 3086] mod_wsgi: Runtime using Python/3.6.11. [Sat Aug 15 05:54:03.395279 2020] [mpm_prefork:notice] [pid 3086] AH00163: Apache/2.4.43 (Amazon) mod_wsgi/3.5 Python/3.6.11 configured -- resuming normal operations [Sat Aug 15 05:54:03.395293 2020] [core:notice] [pid 3086] AH00094: Command line: '/usr/sbin/httpd -D … -
register variants and attributes on admin
I am trying to explore more about django and also understand the ecommerce in detail. When I thought about ecommerce project on django, I came to know about saleor which I liked the most among other. Since, it uses reactjs as an admin I thought I should dive into creating admin on django itself. But i find some of the models of product app confusing when trying to register them to admin. It was specifically on BaseAssignedAttribute, AssignedProductAttribute, AssignedVariantAttribute, AttributeProduct and AttributeVariant. Mainly i got confused due to the use of BaseAssignedAttribute. When registering the admin, if i do admin.site.register() i can register all those models but that way it is not too clear when adding products. What is the other way to make those tables look clearer(so a non-tech can also create a product from admin) on django admin instead of dispersing just using admin.site.register()? Sorry, if i could not make clear explanation as English is not my native language. Here is what i have tried from django.contrib import admin from . import models class CategoryAdmin(admin.ModelAdmin): model = models.Category class ProductTypeAdmin(admin.ModelAdmin): model = models.ProductType class ProductVariantInlineAdmin(admin.TabularInline): model = models.ProductVariant class ProductImageInlineAdmin(admin.TabularInline): model = models.ProductImage class ProductAdmin(admin.ModelAdmin): inlines = [ProductVariantInlineAdmin, … -
How do i link an already existing domain to a Windows Server 2019 VPS
I have a Django project running with Nginx and Waitress on my Windows VPS, i want to make it accessible to the public with a domain name. I am completely clueless on how to go about it, although i have pointed my domain's A record to the Public IP address of the VPS. To be specific, i am running a Windows Server 2019 on the Gcloud platform. -
Django Multiple chartJs chats in a page
I am developing a Dashboard. I am having 3 html pages that have a chart in them like below. I am having 3 charts as i will be using the charts in other html pages throughout the django project. So i decided to have the charts in a different html pages and provide data from view. Barchart1.html <canvas id="myChart" width="400" height="400"></canvas> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); </script> Barchart2.html <canvas id="myChart" width="400" height="400"></canvas> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: … -
how to acess database shared with two sites
i have two website . First site is at example.com which is wordpress site and the next site is in example.com/feature which is a django website.i'm hosting it in the same domain using apache or nginx .accessing django site as an additional feature. user registraion is done in the wordpress site . i want to create the following model in django models.py class UserVideo(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) url = models.charfield(max_lenth=250) My question is how will i get the User for creating a table, if the name of the table created by wordpress is User...?? -
Validate to staff_user : Django Restframework
I want only staff_user can add product and can add maximum up to 10 products. I'm probably new to django. I have tried something like below, but i have no idea about how to validate to the staff_user that he can add up to 10 products maximum. It would be great if anybody could help me what i'm trying to solve is. thank you so much in advance. models.py class Cuboid(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=80) length = models.ForeignKey('FilterLength', on_delete=models.CASCADE) created_on= models.DateTimeField(default=datetime.now()) serializers.py class CuboidCreateSerializers(serializers.ModelSerializer): class Meta: model = Cuboid fields = "__all__" views.py class CuboidCreateAPIView(generics.CreateAPIView): model = Cuboid queryset = Cuboid.objects.all() serializer_class = CuboidCreateSerializers permission_classes = [IsStaff] -
Changing the default markup of the RadioSelect django widget
I am using python version 3.6.8 and django version 3.0.8. I have seen a lot of topics related to this in this forum but some are very old answers. Not sure which one to follow. I tried referring to the django official documentation which exactly talks about the markup that I want to customize from the default ul/li markup for a radio select to my own styling as per my css. Not sure what is it that I am missing. Can anyone help me as to how to go about achieving this in the django version that I am using. Thanks in advance. Django Official Documentation: https://docs.djangoproject.com/en/3.0/ref/forms/widgets/#radioselect When I try doing this I get the error : Error during template rendering 'ChoiceField' object is not iterable The forms.py code is the following: from django import forms class ContactUsForm(forms.Form): name = forms.CharField(label='Name', widget=forms.TextInput(attrs={'class' : 'form__input', 'placeholder' : 'Name'})) email = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'class' : 'form__input', 'placeholder' : 'Email'})) mobile = forms.CharField(label='Mobile', widget=forms.TextInput(attrs={'class' : 'form__input', 'placeholder' : 'Mobile', 'type' : 'tel'})) message = forms.CharField(label='Message', widget=forms.Textarea(attrs={'class' : 'form__input', 'placeholder' : 'Message', 'rows' : "4" , 'cols' : '50'})) CHOICES = [ ('1', 'New Projects'), ('2', 'Interiors'), ('3', 'Land Resale'), ('4', 'Joint Venture'), ('5', 'Renovation'), … -
How to update api details every 10 minute in django rest framework
Note: am using django rest framework. I have a location model and an apiview for it, I can create, put, and delete data from the views, now I want to update this data every 10 minutes from the front-end, what is the best approach for this. I have come across django channels but I dont know how to integrate both channels and django rest framework together, since am only updating information. -
Django giving error "The current path, item/14/add_to_cart1/, didn't match any of these."
I'm trying to add add-to-cart functionality in my django product.First I have list view of Items then I have detail view then I'm adding Items according to the Item-id to the cart.My urls.py is as follows: url('logout/', views.logout, name="logout"), url('^contact$', views.contact, name='contact'), url('^signup', views.signup, name="signup"), # url('^index$', views.index, name = 'index'), url('^about$', views.about, name='about'), url('^demo', views.demo, name='demo'), url('^payment', views.payment, name='payment'), url('logout', auth_views.LogoutView.as_view(), name='logout'), url(r'^accounts/', include('registration.backends.default.urls')), path('detail', views.detai, name='detai'), url('^$', views.home,name = 'home'), re_path('^item/(?P<pk>[0-9]+)/$', views.ItemDetail.as_view(), name='item'), path('^add/<int:id>', views.add_to_cart1, name="add_to_cart1"), this is my views.py def add_to_cart1(request, id): item = get_object_or_404(Item, id=id) order_item, created = CartItem.objects.get_or_create( item=item, user=request.user, ) order_qs = CartItem.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.items.filter(item = item).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "Item qty was updated.") return redirect("core:order-summary") else: order.items.add(order_item) messages.info(request, "Item was added to your cart.") return redirect("core:order-summary") else: order = CartItem.objects.create( user=request.user, ) order.items.add(order_item) messages.info(request, "Item was added to your cart.") return render(request,"index.html") this the error I'm getting: error -
TypeError: '>=' not supported between instances of 'datetime.datetime' and ' float'
import datetime from django.utils import timezone class Allcourses (models.Model): started_from=models.DateTimeField('Started from') def was_published_recently(self): return self.started_from >=(timezone.now()-datetime.timedelta(days=1)).timestamp() -
why am I getting network error for my Django website?
My django website was integrated with default SQLite DB. Yesterday, I tried migrating it to Postgres, however, due to some password issue, the migration failed. Then I tried to fall back to SQLite just by uncommenting the SQLite portion in settings.py. But it failed too. I guess I broke my Database. To fix the issue I used the below CLI command to delete everything in the SQLite: python manage.py migrate my-app-name zero Then I used makemigratons and then migrate. So, here everything seem to go smoothly. However, now I faced the connectivity issue with my website. Its not launching from web browser. I don't know if I have messed my entire environment itself. My website is hosted on AWS on Ubuntu server, it has gunicorn and nginx up and running. Initially I was receiving some below error: A communication error occurred: The Web Server may be down, too busy, or experiencing other problems preventing it from responding to requests I checked the journalctl logs, and I found something like below: nginx.service: Failed to read PID from file /run/nginx.pid: Invalid argument To try to fix the issue I followed the web link. But, it is not working. I am not sure … -
Creating a duration field using startdate and lastdate of DateField type in Django
All I need to do is calculating difference between two dates and store it as another field in database. class Experience(models.Model): startdate = models.DateField(default=date.today) lastdate = models.DateField(default=date.today) duration = models.DurationField((startdate-lastdate).days) Kindly let know what am I doing wrong here, and what should be done to correct. -
DJANGO - dynamic form fields creation using ajax
I'm new to django, and i'm having trouble adding form fields dynamically with a click of a button using ajax. This is what I tried so far using modelformset_factory. In my views.py I have a code like this which is called to add a new field of author from ajax: if request.is_ajax: AuthorFormset = modelformset_factory(Author, form=AuthorForm) author_form = AuthorFormset(request.POST) if author_form.is_valid: return JsonResponse({'data': str(author_form)}) basically, what I want to do with that code is return a new formset with an initial value of the POST request sent from ajax with one extra field. But this code only returns the fields from the POST request without the extra field. How can I make it do that? I appreciate any help, thanks in advance! -
how to solve bad request in django rest-frame-workd
I have created an api which accepts user email and password to login. When ever i tried accessing the api, i get bad request. I have been searching the need, looking at my code. but yet i cannot figure out what i am doing wrong. Please help Below my html form <form id="loginform"action="userlogin/" method="post" enctype="multipart/form-data"> <div class="errors-field"> </div> <div class="input-field"> <label > Email </label> <input placeholder="Email"type="email" name="email" value=""required> </div> <div class="input-field"> <label> Password </label> <input placeholder="Password"type="password" name="password" value=""required> </div> <button type="submit">Login</button> </form> My java script below const lgform = document.querySelector('#loginform') lgform.addEventListener('submit',loginForm) function loginForm(event){ event.preventDefault() const myform = event.target const myFormData = new FormData(myform) const url = myform.getAttribute("action") const method = myform.getAttribute("method") const csrftoken = getCookie('csrftoken') const xhr = new XMLHttpRequest() xhr.open(method,url) xhr.setRequestHeader("Content-Type","application/json") xhr.setRequestHeader("HTTP_X_REQUEST_WITH","XMLHttpRequest") xhr.setRequestHeader("X-Requested-with","XMLHttpRequest") xhr.setRequestHeader("X-CSRFToken",csrftoken) xhr.onload=function(){ const serverResponse = xhr.response const serverData = JSON.parse(serverResponse) console.log(serverData.email) if(xhr.status==200){ if(serverData.token){ cname = "user" cvalue = serverData.token exdays = 1 setCookie(cname, cvalue, exdays) } } } xhr.onerror=function(){ console.log('error') } xhr.send(myFormData) } my serilialozer class loginUserSerializer(serializers.Serializer): password = serializers.CharField(style={'input_type':'password'},write_only=True,required=True) email = serializers.EmailField(required=True) def validate_email(self,value): data = self.get_initial() pw = data.get('password') email= value user=authenticate(email=email,password=pw) if not user or not user.is_active: raise serializers.ValidationError('email or password not correct') return value My api view class loginUser(ObtainAuthToken): def post(self,request,*args,**kwargs): data …