Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update datetimefiled of all related models when model is updated
I have two models (Post and Display). Both have Datetime-auto fields. My problem is that i want to update all display objects related to a post, once a post is updated. I have read here that you could override one models save method, but all the examples are About updating the model with the foreign key in it and then call the save method of the other model. In my case it's the other way arround. How can i do this ? class Post(models.Model): title = models.CharField(max_length=40) content = models.TextField(max_length=300) date_posted = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) rooms = models.ManyToManyField(Room, related_name='roomposts', through='Display') def __str__(self): return self.title def get_absolute_url(self): return "/post/{}/".format(self.pk) class Display(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) isdisplayed = models.BooleanField(default=0) date_posted = models.DateTimeField(auto_now=True) def __str__(self): return str(self.isdisplayed) i want to update the date_posted of all related Display-objects once their related post is changed. I do not know if overriding the save-method works here. -
how do link to function in view into html form
I am beginner about Django, I don't know get data from HTML form. How can I fix? Help me, please! <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Exmaple Form</title> </head> <body> <form method="post" action="{% %}"> {% csrf_token %} <p>First Name: <input type="text" name="firstname"></p> <p>Last Name: <input type="text" name="lastname"></p> <p><input type="submit" value="submit"></p> </form> <p>{{ first_name }}</p> <p>{{ last_name }}</p> </body> </html> Function get data HTML form def index(request): return render(request, 'form.html') context = {} first = request.POST.get['firstname'] last = request.POST.get['lastname'] context = { 'first_name': first, 'last_name': last } return render(request, 'form.html', context) -
django-tables2 max total results
I want to limit the max total results. I only want 1 page with max 20 results. How can I do that? Adding [:20] to the query gives an error Cannot update a query once a slice has been taken My SearchTestView Class: def get_context_data(self, **kwargs): context = super(SearchTestView, self).get_context_data(**kwargs) title_result = Title.objects.filter( Q(categories__steam_id=36) | Q(categories__steam_id=20) | Q(categories__steam_id=1) | Q(genres__steam_id=29) ).filter(release_date__lte=datetime.date.today()).distinct().order_by('- release_date') table = TitleTable(title_result) RequestConfig(self.request, paginate=False).configure(table) context['table'] = table return context -
How can I write Bulk Data(25 Lakhs) on an Excel Sheet using Python,Django,MYsql,Dataframe?
Actully I am new to Python.I am using Python with Django and MYsql. I have written a code to fetch bulk data(25 Lakhs) from MYsql database and split it into three variables and then write them on an Excel sheet which contains 3 sub sheets...Here is my view.py file.... all_dataobj=fetchdata.objects.all() pserializer=fetchdataSerializers(all_dataobj,many=True) res = [item for item in pserializer.data if 1 <= item.get('id') <= 1000000] res1 = [item for item in pserializer.data if 1 <= item.get('id') > 1000000 and item.get('id') <= 2000000 ] res2 = [item for item in pserializer.data if 1 <= item.get('id') > 2000000] df = pd.DataFrame([]) df1 = pd.DataFrame([]) df2 = pd.DataFrame([]) df = df.append(res) df1 = df1.append(res1) df2 = df2.append(res2) writer = ExcelWriter('fetchdata_sheet12.xlsx') df.to_excel(writer,'Sheet1',index=False) df1.to_excel(writer,'Sheet2',index=False) df2.to_excel(writer,'Sheet3',index=False) writer.save() But this code works totally fine with less data.As I am running it for 25 Lakhs data, the browser keeps on running and no excel sheet gets generated. I am stuck here for long time.Can anyone please help me out??????? -
I want to add tags like structure to my website
I have a field in my model where user enters it's skill. I want to show it like tags(as we do in stack overflow while posting questions) I tried searching for it but couldn't find it, may be because I am not quering the correct thing. -
django-tables2 How to set Verbose name for _set
I have a value ccu_set.all.first.player_count Which works perfectly, but I want to change the verbose name so that in the table it doesnt say "ccu_set.all.first.player_count". However when I do ccu_set.all.first.player_count = tables.Column(verbose_name= 'CCU', default='') It gives an error: ccu_set.all.first.player_count = tables.Column(verbose_name= 'CCU', default='') NameError: name 'ccu_set' is not defined -
Django - InheritanceManager is not working
I have the following simple models.py file: from django.db import models from model_utils.managers import InheritanceManager class Clique(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, blank=False) class Post(models.Model): created = models.DateTimeField(auto_now_add=True) headline = models.TextField() clique = models.ForeignKey(Clique, on_delete=models.CASCADE, blank=True, null=True) objects = InheritanceManager() def __str__(self): return self.headline class VideoPost(Post): video = models.BooleanField(default=True) class ImagePost(Post): image = models.BooleanField(default=True) So, there is a Clique model which can contain multiple Post instances. The Post instances can be ImagePost or VideoPost. Therefore, ImagePost and VideoPost both inherit Post. Now, let's say I want to retrieve the ImagePost subclass instances. So, I have the following view in my views.py file: class PostList(generics.ListAPIView): serializer_class = PostSerializer def get_queryset(self): return Post.objects.select_subclasses(ImagePost) When I pass the endpoint posts/ in the url, then this view will be triggered and it should give me only the ImagePost instances, right ? But I also get the VideoPost instances from the database: [ { "clique": "http://127.0.0.1:8000/cliques/1/", "comment_set": [], "created": "2019-06-18T09:52:47.929623Z", "headline": "FirstImagePost", "id": 1, "url": "http://127.0.0.1:8000/posts/1/" }, { "clique": "http://127.0.0.1:8000/cliques/1/", "comment_set": [], "created": "2019-06-18T09:53:20.266653Z", "headline": "FirstVideoPost", "id": 2, "url": "http://127.0.0.1:8000/posts/2/" } ] Why is this happening ? I walked through the official doc here . Can somebody help Just for the sake of completeness, … -
How can I loop a generator in this situation?
Here's the question. I want to use django's bulk_create to save more datas at once. But the original result I get from API is a generator with amount data in it. So I want to loop this generator and bulk save data. My trial was as below: # a generator with amount data l = ( item for item in range(1,100230, 1) ) # base model table class ModelDemo(models.Model): ... # main logic code limit = 2000 while l: bulk_list = [] for index, item in enumerate(l): bulk_list.append( ModelDemo( ... ) ) if index == limit: ModelDemo.objects.bulk_create(bulk_list) break It's obviously I would lose last 230 data, but I couldn't find the solution by now. Any commentary is very welcome. great thanks. -
Creating a clickable view for my template
I am trying to create a view template for my project. My app has 5 fields which include site_id(char),annotation(int),person_class(int),vehicle_class(int) and time(char). All entries in the table belong to one of the site_id (site_1, site_2 ....site_5). I want to create a view which displays the 5 site_ids on the webpage and clicking on them should open up a table of its corresponding data. I am new to django and currently facing problems understanding this implementation. Could someone point me to what I need to do? -
Allow API requests with X-CSRF headers from Laravel to Django Backend
I have Laravel framework with VueJS serving as the frontend. This frontend is hosted on xampp's localserver on ports 80,443 with the configured url "http://test.net". I send API requests from VueJS app using axios to a Django backend, where I have installed a working Rest framework (Accessible through Postman). The backend server is http://127.0.0.1:8000. Because the servers are different, I have installed django-cors-headers package and configured the settings.py file to include this package, and also include the middleware, as shown in the documentation. This is the axios request from Vue: let url = "http://localhost:8000/leadmanager/api/lead/"; axios.get(url) .then(res => console.log(res.data)) .catch(error => console.log(error)); Initially I got this error: Access to XMLHttpRequest at 'http://localhost:8000/leadmanager/api/lead/' from origin 'http://localhost:80' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. So I checked the documentation and installed django-cors-headers and included the Laravel website's url inside CORS_ORIGIN_WHITELIST. CORS_ORIGIN_WHITELIST = [ "http://test.net" ] After doing this, I get a different error. I suspected this would be because Laravel by default attaches x-csrf-token headers to the packets being sent out. Access to XMLHttpRequest at 'http://localhost:8000/leadmanager/api/lead/' from origin 'http://hawiya.net' has been blocked by CORS policy: Request … -
Django with Pandas accessing ForeignKey
I do not know Pandas so this may be trivial. I have this line of code: admin_data = pd.DataFrame.from_records(administrations.values()).rename(columns = {'id':'administration_id', 'study_id': 'study_name', 'url_hash': 'link'}) which is getting data from the administration model (administrations is a recordset) and using it. Rather than using study_id I would like to get the study name. With Djano ORM I would use study__name but I cannot do that here. How can I get the study.name instead of study.id into admin_data? models class administration(models.Model): study = models.ForeignKey("study") # Study name ... class study(models.Model): name = models.CharField(max_length = 51) # Study name ... -
Can not login with 'requests'
I'm trying to login and get a response. But i can not do it because of password encryption algorithm of django Is it possible in other ways? payload = {'username': self.request.user.username, 'password': self.request.user.password} response = requests.post('http://localhost:8000/api/login/',data=payload) Error: No active account found with the given credentials -
I can not get alll the data from the database with one query
I have to two tables in the postgresql database. In first one I have all descriptions of a vulnerabilities and in the second one I have all the product that are affected. Tables are conected via primary key. My problem is that I do not know how to get one description with all vulnerabilities in one query. I have tried with django-orm and raw postgresql queries without success. Here are my models: class Description(models.Model): description = models.TextField() file =models.CharField(max_length=50) date = models.DateTimeField(default=timezone.now) severity = models.CharField(max_length=10) exp_score = models.DecimalField(null=True, max_digits=5, decimal_places=1) impact_score = models.DecimalField(null=True, max_digits=5, decimal_places=1) cvss_score = models.DecimalField(null=True, max_digits=5, decimal_places=1) published_date = models.IntegerField() last_modified = models.IntegerField() cve = models.CharField(max_length=30) cve_url = models.CharField(max_length=1000) def __str__(self): return self.file class Meta: verbose_name_plural = 'Ranljivosti' class AffectedProductVersion(models.Model): data = models.ForeignKey(Description, on_delete=models.CASCADE) vendor_name = models.CharField(max_length=100) product_name = models.CharField(max_length=100) version = models.CharField(max_length=150) class Meta: indexes = [ models.Index(fields=['vendor_name', 'product_name', 'version']), ] def __str__(self): return self.vendor_name + '-' + self.product_name Is it possible to achieve this in one queryset? Query can be written in django-orm or raw postgresql. I will appreciate any suggestion to solve my problem. -
Setting Academic or Financial Years in Django
This may seem rather insignificant, but how do you set a financial or academic year, say 2018/19 or 2017/2018 in a Django model and reference the current financial year for querying, in this case 2019/20 -
Want to create separate page for each blog post in django?But dont know how to proceeed?
I am trying to create a blog app with django.I have a home page in my app where all blog posts will be displayed.If anyone clicks on a blog post it should be displayed on a separate page.But dont know how to proceed? I know that i cant create separate html page for each post.I created a common layout html page for displaying each post.But dont know know how to add that content to it. <!---------layout.html----> {% load static %} <html> <head> <title>Self Learn</title> <link rel="stylesheet" type="text/css" href="{% static ' styles/main.css' %}" /> </head> <body> <div class="header"> <h1 class="logo">Blog</h1> <ul class="menu"> <a href="/">Home</a> <a href="#">About Us</a> {% if user.is_authenticated %} <a>Hi,{{user.username}}</a> <a href="logout">Logout</a> {% else %} <a href="login">Login</a> <a href='register'>Register</a> {% endif %} </ul> </div> <a href="newpost"> <img src="{% static 'images\12.PNG' %}" class="logo1"/> </a> <!----Post------> {% for blog in blog %} <div class="list"> <div class="con"> <h3 style="color:DodgerBlue;">{{blog.author}}</h3> <h6 style="font-family: montserrat,sans-serif;"> {{blog.date}} </h6> </div> <div class="line"></div> <div class="con"> <a href='indpost'><h1><b>{{blog.title}}</b></h1></a> </div> <div class="con"> <p>{{blog.desc}}</p> </div> </div> {% endfor %} {% block content %} {% endblock %} </body> </html> -
I am completely new to using ajax with django. How do I write the function for ajax for changing the value of model field?
I am using CBVs and I need to change the value of a field on button click. I have tried some code but it doesn't seem to work. What is wrong in this code and what can be modified? script $("#ajax_button").on('click', function () { $.ajax({ url: 'NewApp/ajax/change_status/{{userprofile.id}}', data: { 'verified': False , }, dataType: 'json', beforeSend:function(){ return confirm("Are you sure?"); success: function (data) { if (data.success) { alert("ajax call success."); // here you update the HTML to change the active to innactive }else{ alert("ajax call not success."); } } }); }); views.py def ajax_change_status(request,pk): userpr = UserProfile.objects.get(pk=pk) try: userpr.verified = True userpr.save() return JsonResponse({"success": True}) except Exception as e: return JsonResponse({"success": False}) return JsonResponse(data) urls.py url(r'^ajax/change_status/(?P<pk>\d+)/$', views.ajax_change_status, name='ajax_verified') -
Change label of a form field Django
I'm sure, there is an aswer on Google but after 30 minuts of search, I don't find my solution. So, I've my model in model.py and I generate a modelform in inventory_form.py. A field is named "watercourse" in my model so, the form field has "Watercourse" as label. model.py class Inventory(models.Model): watercourse = models.CharField(max_length=255, null=False) inventory_form.py class InventoryModelForm(forms.ModelForm): class Meta: model = Inventory fields = ['watercourse',] widgets = { 'watercourse': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'lorem ipsum', }), } If i want to change the label for "Insert a watercourse", where do I change this setting? Thanks! -
Graphene Django to Query Elasticsearch
My data is stored in elasticsearch and it is very big. So I want to use graphql to query it properly. I am using django graphene package to query it. For database models it is working fine. My json schema of elasticsearch https://pastebin.com/EQBnnCBU below is my Type definition and query code https://pastebin.com/fsr9V1Rf Problem is that I am not able to understand how to write the query schema for the elastic json schema. need only initial help or any explanation that can help me I have checked the answer here django-graphene without model But is of not help My current ElasticType schema class ElasticType(graphene.ObjectType): id = graphene.ID() index = graphene.String() found = graphene.String() properties = graphene.String() -
How to use django infinite scroll with custom overflow / custom scroll bar?
I want to implement django waypoint infinite scroll for web page & have successfully implemented too with default scroll bar. But, when I apply it to custom scroll bar, it loads all pages one by one of infinite scroll. It doesn't wait for scrolling to load next page. Django Waypoint plugings used: <script src="{% static 'js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'js/infinite.min.js' %}"></script> Code overview: <div class="panel panel-height panel-flat"> <div class="panel panel-info" style=""> <div class="panel-body"> <ul class="media-list dropdown-content-body" style="padding:1% 27%;"> <div class="infinite-container" style="overflow: auto;height:70%"> <div class='infinite-item'> <span>...some content..</span> </div> </div> </ul> </div> </div> </div> -
Make 2 versions of template cache for page with and without message
Question is about using {% cache %} tag in Django templates. For example I have a “user_profile” page with “change user data” sub-page. When user wants to change his personal data, he would visit this sub-page and on completion redirected to the “user_profile” page again with message created by messaging framework like “ Dear username, you data has changed, etc” . Problem is that page would be cached with this message included and each and every time user visits “user_profile” page , message “ Dear username, you data has changed, etc” would be displayed again, that is cache freezes page condition on first visit. My cache tag is like following: {% cache "60*60*24*30"|multiplier correct_user_info request.user.change_date request.user.pk %} Page, used the view extends base.html where <div class="messages" id="message_container"> {% bootstrap_messages %} </div> is not cached at all I could move {% bootstrap_messages %} block to each individual page outside the cache tags but its kind of fishy option imo… Question is - is it any sign I could use in {%cache%} tag as a unique indicator to separate 2 situations: a) where user just changed his data , redirected to the “user_profile” and message should be displayed b)where user just visits … -
display django form.errors beside the field
When I get some error after submitting a form implemented in django it is displayed in top of the page where I have form.errors. Here I want that error to be displayed beside the field due to which the error is occurring like in django user creation form. How to do it?? template {% if form.errors %} <div class="alert alert-danger"> {{ form.errors }} </div> {% endif %} -
How to extend django UserCreationForm properly
Here i am trying to add profile model fields along with user model fields.But it not working it doesn't add the profile models data.But after adding when i do update the user i can update both model user and profile together.But while registering the user i am not being able to add profile models data .Is it possible to add profile model data along with user model at a time ? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100,blank=True,null=True) last_name = models.CharField(max_length=100,blank=True, null=True) location = models.CharField(max_length=100,blank=True, null=True) phone = models.CharField(max_length=20,blank=True,null=True) image = models.ImageField(upload_to='user image',default='default.jpg') @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=100, required=False) last_name = forms.CharField(max_length=100, required=False) location = forms.CharField(max_length=100, required=False) phone = forms.CharField(max_length=20, required=False) image = forms.FileField(required=False, initial='default.jpg') def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise ValidationError('Email Already Exists') return email class Meta: model = User fields = ['username', "email", "password1", "password2",'first_name','last_name','location','phone','image','is_superuser', 'is_staff', 'is_active'] views.py def add_user(request): if request.method == "POST": form = RegisterForm(request.POST or None,request.FILES or None) if form.is_valid(): user = form.save(commit=False) user.save() messages.success(request, 'user created with username {}'.format(user.username)) return redirect('list_user') else: form = RegisterForm() return render(request, 'add_user.html', {'form': form}) def … -
Django Test Login
I created a test for create user and login. In my settings I have defined the password with min_length = 8. But the test passes with a password of 3 chars. Here my settings: AUTH_PASSWORD_VALIDATORS = [ {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': {'min_length': 8}}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },] My test looks like this: from django.test import TestCase from django.contrib.auth import get_user_model class UsersManagersTests(TestCase): def test_create_user(self): custom_user = get_user_model() user = custom_user.objects.create_user(email='normal@user.com', password='foo') self.assertEqual(user.email, 'normal@user.com') self.assertTrue(user.is_active) self.assertFalse(user.is_staff) self.assertFalse(user.is_superuser) try: # username is None for the AbstractUser option # username does not exist for the AbstractBaseUser option self.assertEqual(user.username, '') # password will be encrypted with bcrypt self.assertNotEqual(user.password, 'foo') except AttributeError: pass with self.assertRaises(TypeError): custom_user.objects.create_user() with self.assertRaises(TypeError): custom_user.objects.create_user(username='') with self.assertRaises(TypeError): custom_user.objects.create_user(username='', password="foo") def test_create_superuser(self): custom_user = get_user_model() admin_user = custom_user.objects.create_superuser(email='super@user.com', password='bla') self.assertEqual(admin_user.email, 'super@user.com') self.assertTrue(admin_user.is_active) self.assertTrue(admin_user.is_staff) self.assertTrue(admin_user.is_superuser) try: # username is None for the AbstractUser option # username does not exist for the AbstractBaseUser option self.assertEqual(admin_user.username, '') except AttributeError: pass with self.assertRaises(ValueError): custom_user.objects.create_superuser( email='super@user.com', password='bla', is_superuser=False) def test_login_user(self): # Create an instance of a POST request. self.client.login(email="normal@user.com", password="foo") data = {'username': 'test name'} res = self.client.post('/accounts/login/', data) self.assertEqual(res.status_code, 200) What am I missing ? Or aren't the settings not considered during … -
Readonly for a Fields in form
I have a calendar form for my page and I would like to make a columns to be read-only. Here is the code forms.py class EventForm(ModelForm): class Meta: model = Event # datetime-local is a HTML5 input type, format to make date time show on fields widgets = { 'start_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), 'end_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), } fields = '__all__' def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) # input_formats parses HTML5 datetime-local input to datetime field self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',) self.fields['end_time'].input_formats = ('%Y-%m-%dT%H:%M',) models.py class Event(models.Model): title = models.CharField(max_length=200) description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() @property def get_html_url(self): url = reverse('cal:event_edit', args=(self.id,)) return f'<a href="{url}"> {self.title} </a>' -
django.db.utils.DataError: value too long for type character varying(100)
I have not set max_length and min_length for TextField: text = models.TextField(_("Full story"), null=True, blank=False) But it still gives me this error: django.db.utils.DataError: value too long for type character varying(100) Could someone help please?.