Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
check for presence in queryset in DTL django
I am creating a to do list. I want to display the tasks if the user has any. If not, then display something else. I kept the design simple. <h2>Here is the list of tasks! Start working!</h2> {% if obj in task %} <ul> {% for obj in task %} <li>{{ obj }}</li> {% endfor %} </ul> {% else %} <p>You dont have anything on this list yet!</p> {% endif %} The 'task' is the queryset and currently consists of 2 objects. But none of them are being displayed. Everything was working fine before I tried to apply the presence check. Now it just jumps to that else statement. views.py: def task(request): task = Task.objects.filter(user=request.user) queryset = task.order_by('-start_date') context = { 'task': queryset, } return render(request, 'task-list.html', context) -
get specific field data from another table using forignkey in django
i have a table in models.py with class name registration and another table profileimage with foreignkey relation with registration model now i want to get verify the email address by using profileimage table models.py class Registration(models.Model): YourName = models.CharField(max_length=30) Email = models.EmailField(max_length=254,verbose_name='email') password = models.CharField(max_length=254,verbose_name='password',null=True) PhoneNumber = models.IntegerField(null=True,verbose_name='email') CompanyName = models.CharField(max_length=30) WebSiteName = models.CharField(max_length=30) NumberOfEmplyes = models.IntegerField(null=True) YourRoleInCompany = models.CharField(max_length=100) SoftwareUsedBefore = models.CharField(max_length=30) Turnout2017 = models.IntegerField(null=True) Turnover2016 = models.IntegerField(null=True) Description = models.CharField(max_length=30) ClientArgument = models.CharField(max_length=2000,null=True) PaymentsPlan = models.CharField(max_length=100,null=True) class ProfileImages(models.Model): MemeberName = models.OneToOneField('Registration',on_delete=models.CASCADE,blank=True) profile_image = models.ImageField(upload_to='media/profile_image',default=True,null=True) def __str__(self): return "user profile image" now for example i have email adress which i get from sessions now e.g example@stack.com now i want to use this email to fillter record in this way. profile_image= ProfileImages.objects.filter(Registration__Email=email).select_related() let me know what is the exact way to perform this query -
django : Show only extra row in tabularinline
I'm using django tabular inline to add transactions related to the client. but I don't want to see the previous transactions, I just want an extra empty row. class TransactionInline(admin.TabularInline): model = Transaction extra = 1 #max_num = 1 but still it's showing the last inserted transaction. -
Using Swagger with Django Rest Framework, can I see POST parameters in different fields instead of one body
I'm actually create APIs on a Django Website using Django Rest Framework. I'm trying to document them using Swagger. I'm using Django 2.1, django-rest-swagger 2.2 and djangorestframework 3.11 Everything is nearly working as expected except something : Let me explain you : I have this model (models.py) class Technology(models.Model): """ This model defines the different technologies """ name = models.CharField(max_length=CHAR_SHORT) path = models.CharField(max_length=CHAR_SHORT, validators=[validate_tech_path], help_text='this is only used to construct the url') image = models.ImageField() mailer = models.EmailField(blank=True) external = models.BooleanField(default=False) internal = models.BooleanField(default=False) class Meta: verbose_name_plural = "technologies" ordering = ['name'] def __str__(self): return self.name Then I have the corresponding serializer class (serializer.py): class TechnologySerializer(serializers.ModelSerializer): """ This model defines the different technologies """ class Meta: model = Technology fields = ('id', 'name', 'path', 'image', 'mailer', 'external', 'internal') Finally I have my view with generated APIs (views.py): class TechnologyViewSet(viewsets.ModelViewSet): queryset = Technology.objects.all() serializer_class = TechnologySerializer http_method_names = ['get','post','delete','put'] Here's the result : Api description 1 Api description 2 As you see on the picture above, the parameters are une the json body. Is it possible to have something like this for all the parameters : API parameter wanted Thanks a lot. -
Python Django Display Nested Objects
Hi I'm new to django rest framework and I'm trying to serialize 3 nested models. The relationships are: hotel_social_media_type has a one to many relationship to hotel_social_media and hotel has one to many relationship to hotel_social_media. Right now I can only serialized hotel to hotel_social_media but I can't serialize hotel_social_media_type. Here's my serializers: class SocialMediaTypeSerializer(serializers.ModelSerializer): """Serializes social media type""" class Meta: model = models.SocialMediaType fields = ('name', 'icon', 'icon') class HotelSocialMediaSerializer(serializers.ModelSerializer): """Serializes media files""" hotel_social_media_type = SocialMediaTypeSerializer(many=False, read_only=True) class Meta: model = models.HotelSocialMedia fields = ('url', 'hotel_social_media_type') class HotelSerializer(serializers.ModelSerializer): """Serializes Restaurat, Bars, TouristInformation and Tourist Spots """ hotel_images = HotelImageSerializer(many=True, read_only=True) hotel_social_media = HotelSocialMediaSerializer(many=True, read_only=True) class Meta: model = models.Hotel fields = ('id', 'name', 'hotel_images', 'hotel_social_media') Current result is: { "id": 1, "name": "Alta Vista", "hotel_images": [ { "id": 1, "name": "Alta Vista", "path": "http://127.0.0.1:8000/media/images/hotel-1.jpg" } ], "hotel_social_media": [ { "url": "https://www.facebook.com/abscbnNEWS" } ] } What I want is: { "id": 1, "name": "Alta Vista", "hotel_images": [ { "id": 1, "name": "Alta Vista", "path": "http://127.0.0.1:8000/media/images/hotel-1.jpg" } ], "hotel_social_media": [ { "url": "https://www.facebook.com/abscbnNEWS", "hotel_social_media_type": { "name": "Facebook", "icon": "http://127.0.0.1:8000/media/images/fb-1.jpg" } } ] } hotel_social_media must also display hotel_social_media_type -
django use slug not pk
I'm trying to use slug in my url, I've done this fine on other sites but for some reason, I am unable to use slug in a url on this area of the site, only the primary key gets the desired result, what am i missing here? The only difference from the other sites I have done is that the slug will be used for filtering which is what I think is messing this up. Model: class Desk(models.Model): name = models.CharField(max_length=16, unique=True) slug = models.SlugField(max_length=16, unique=True) def __str__(self): return self.slug class Handover(models.Model): desk = models.ForeignKey( Desk, related_name="handover", on_delete=models.CASCADE ) published = models.DateTimeField(auto_now_add=True) user = models.CharField(max_length=45) ongoing = models.CharField(max_length=1024, null=True, blank=True) resolved = models.CharField(max_length=1024, null=True, blank=True) planned_work = models.CharField(max_length=1024, null=True, blank=True) heightened_awareness = models.CharField(max_length=1024, null=True, blank=True) In the views below, for some reason I can't use the word 'slug' in the filter, it just throws an error. The current setup works if I use the PK in the url in the browser, but not the slug which is what I want to use, (I'm not sure why this works either, I would expect this not to work because of using 'slug' in the url). Here is the view: class IndexView(ListView): template_name … -
Django, Materialize, Django-tables2: Expected table or queryset, not str
I have a form and one of the fields is a MultipleChoiceField. The form is rendered in a modal using Materialize. I had issues to render the choices in the form but found this answer I changed the field to: comp = forms.MultipleChoiceField(choices=COMP, widget=forms.Select(choices=COMP, attrs={'class': 'browser-default'})) which solved the rendering issue. Once I submit the form I expect to view the data in the django-tables2 table, which worked fine, but now I receive the following error: Exception Value: Expected table or queryset, not str If I remove the widget the form doesn’t render as I would like but I’m able to submit the form and see the data in the table. What am I missing? How can I resolve this? Please let me know if I should post additional code, thank you -
live countdown in django keith wood countdown timer
I am using keith wood countdown, How do i set the (14 days) countdown when after the user login, and the countdown will still be redundant even if the user logout or leave the page? <div id="defaultCountdown"></div> <script> $(function () { var days = 14 var austDay = new Date(); austDay = new Date(austDay.getDate() + 1, 1 - 1, 26); $('#defaultCountdown').countdown({until: austDay}); $('#year').text(austDay.getFullYear()); }); </script> this is my views.py def profile(request): if request.method != 'POST': raise Http404('Only POSTs are allowed') try: m = User.objects.get(username=request.POST['username']) if m.password == request.POST['password']: aa = request.POST['username'] request.session['member_id'] = m.id print(m.id) return render(request, 'profile.html') except User.DoesNotExist: messages.Warning(request, 'Incorrect Username or Password.') return render (request, "login.html") -
Django 3 - doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am learning Django 3 but having a problem. My app is called calc1. Code below: MODELS.PY from django.db import models # Create your models here. class Dreamreal(models.Model): website = models.CharField(max_length = 50) mail = models.CharField(max_length = 50) name = models.CharField(max_length = 50) phonenumber = models.IntegerField() class Meta: db_table = "dreamreal" VIEWS.PY from django.shortcuts import render from django.http import HttpResponse import datetime import time from .models import Dreamreal from django.http import HttpResponse # Create your views here. def home(request): today = datetime.datetime.now().date() return render(request, 'home.html',{'today' :today}) def crudops(request): dreamreal = Dreamreal( website = "www.vlcbt.org.uk", mail = "info@vlcbt.org.uk", name = "John", phonenumber = "08767655665" ) dreamreal.save() # read all entries and print objects = Dreamreal.objects.all() res ="printing all documents <br>" for elt in objects: res += elt.name +"<br>" return HttpResponse(res) When I try to migrate I get the following error message: File "C:\Users\john\Envs\lms\Scripts\projects\jkjlms\calc1\urls.py", line 3, in from . import views File "C:\Users\john\Envs\lms\Scripts\projects\jkjlms\calc1\views.py", line 5, in from .models import Dreamreal File "C:\Users\john\Envs\lms\Scripts\projects\jkjlms\calc1\models.py", line 5, in class Dreamreal(models.Model): File "C:\python\lib\site-packages\django\db\models\base.py", line 115, in new "INSTALLED_APPS." % (module, name) RuntimeError: Model class calc1.models.Dreamreal doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Thanks for your help in advance -
Django Send Request Like Postman
I want to get data from a web service. For this use the following URL on Postman: http://x.x.x.x:8090/api/jserv.ashx?action=ReportMethod // has a paramater And I have to add a raw like the following to verify user: { "user": { "userid": "xxxx", "username": "User", "status": "false", "mesaj": "null", "no": 0, "versiyon": "null" }, "start": "1900-01-01T00:00:00", "end": "2020-02-25T00:00:00" } When I use Postman I can get data. How to do this operation using Django? -
how can i get the user commented on a specific course from database? where as i have a relation with of courses to comments and user to comments
this is my code so i want to ask for your help... i'm using by default User model of django and having different courses having comments by different users so i want to get all the comments on specific course by all the users using just course_id. model.py class Course(models.Model): course_id = models.CharField(max_length=20 , auto_created= True) course_name = models.CharField(max_length=250) course_pic = models.ImageField(upload_to='images' , blank=True) course_author = models.CharField(max_length=15) released_date = models.DateTimeField( auto_now_add=True) course_rating = models.CharField(max_length=15) class Comments(models.Model): course = models.ForeignKey(Course,on_delete=models.CASCADE,related_name='comments') commented_by = models.ManyToManyField(User) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created_on'] def __str__(self): return self.body views.py def CourseDetail(request, id): course = Course.objects.get(course_id = id) comments = Comments.objects.filter(course_id = id) print(comments) if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.course = course new_comment.save() comment_form = CommentForm() else: comment_form = CommentForm() context ={ 'course': course, 'comments': comments, 'comment_form': comment_form } return render(request, 'pages/course_details.html', context) -
Django AutoComplete Light Filter Foreign Key Values
I am using the Django AutoComplete Light library to filter Form values based on a Primary key. I have two models as below: class Skill(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class SubSkill(models.Model): name = models.CharField(max_length=50) skill = models.ForeignKey(Skill, on_delete=models.CASCADE, null=True) def __str__(self): return self.name. However, these two field are used in another Employee model as I want to query base on this model. I had used Django Smart Selects to chain the models in the Employee model which works fine. However, I am trying to filter my subskills based on the skills using the Autocomplete library but getting all the subskills instead. My Django Autocomplete light view looks like this class SubskillsAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! # if not self.request.user.is_authenticated(): # return Country.objects.none() qs = SubSkill.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs and my model form looks like this: class EmployeeSkillForm(forms.ModelForm): class Meta: model = Employee fields = ('skills','sub_skills', 'experience','resume','certificates') widgets = { 'sub_skills': autocomplete.ModelSelect2Multiple(url='skills-autocomplete') } I cannot figure out why my subskills will not filter based on the skill instead of showing everything. -
Matching single column against multiple values without self-joining table in POSTGRES
I want to select a routing_id which has routing_id = 489. I use SQL subquery but it decreases the performance. Query:- select routing_id from ec.production_autoroutingtag where tag_type = 'mounting_type' AND tag_value='smd' and routing_id in (select routing_id from ec.production_autoroutingtag where tag_type = 'x_ray' AND tag_value='true' and routing_id in (select routing_id from ec.production_autoroutingtag where tag_type = 'depaneling' AND tag_value='false')) It working fine but what when numbers of rows are more so please give me the best solutions. Thanks in Advance. ![2]: https://i.stack.imgur.com/8plMV.png! -
How to disable 301 redirects in HAProxy
I have an internal load balancer (HAProxy 2.0.2) which proxy to my pool of application servers. When i directly access POST /hello on Application server it returns 404 since all my urls should end with trailing slash, But if i do the same with HAProxy POST /hello my requests are automatically routed and results of GET /hello/ are returned, but in haproxy access.log, status code 301 is logged. Note: I have to disable any auto redirect behaviours of HAProxy, ie HAProxy should server request on if that path exists, Else return 404. any config update update would be really helpful Valid URL's /hello/ Expected HAProxy Behaviour. Haproxy should return 404 if i hit /hello [without trailing slash] HAProxy Config global log /dev/log len 4096 local0 info log /dev/log len 4096 local1 notice chroot /var/lib/haproxy stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners stats socket ipv4@0.0.0.0:9999 level admin stats timeout 30s user haproxy group haproxy daemon defaults log global mode http option dontlognull option redispatch retries 3 timeout http-request 50s timeout connect 5s timeout check 5s timeout client 50s timeout server 50s frontend fe_web bind *:80 stats uri /haproxy?stats capture request header Host len 64 acl IS_V2 path_beg /api/v2 use_backend … -
Django - Managing messages strings by one single file
I'm currently experiencing that my application has become quite large and I'm handling a lot of diffrent messages at my views.py. I have to manually set every message string I return to my user at the specific view. Now my idea was to manage all potential messages my application returns to the user e.g. a error or a sucssess message by only one single file, so that i dont have to set the same message strings three or four times for basically the same thing ... Example - current state: if example.objects.filter(author=request.user, status='Magic').count() >= config.USER_MAX_MAGIC: messages.error(request, 'You have reached the maximum amount of Magic.') return redirect('magic') Example - Wanted state from app_messages import xyz # These containing the actual string that should get returned to the user if example.objects.filter(author=request.user, status='Magic').count() >= config.USER_MAX_MAGIC: messages.error(request, xyz) return redirect('magic') My question now is: How does xyz has to look like and is this in general a good idea to accomplish a management of error, success, info etc. messages like that? Thanks in advance -
What is the best way for Django microservices intercommunication?
I have a django microservice: M1 with admin page having fields: [link to field11] | [link to field 21] I have another django microservice: M2 with admin page having fields: field11 | field12 | field13 | field14 | field 15 I have another django microservice: M3 with admin page having fields: field21 | field22 | field23 | field24 | field 25 My requirement is to get all the fields of M2 and M3 into M1's admin page. What are the ways I can do this? I do not want to add more fields into M1's model. One way is to do interservice communication or do a GET call. What will be more feasible? -
About parametrizing base template page in Django
I have the following problem, there is a base template "base.html" which defines default header and body information, which will be used by other pages. base.html <!DOCTYPE html> <head> ... {% block head_stuff %} {% endblock %} ... </head> <body> ... <p>Parameter that depends on the request time in a non trivial way</p> ... {% block body_stuff %} {% endblock %} ... </body> </html> The pages that use it look like: a.html b.html c.html <!DOCTYPE html> {% extends "base.html" %} {% block head_stuff %} ... {% endblock %} {% block body_stuff %} ... {% endblock %} </html> What I'd like to do is to render a.html, b.html, c.html without passing informations about that parameter. In absence of inheritance, one would call render function by passing the parameter to a context, but in this case no views are used to construct the base.html. How can I approach this problem? -
mommy Recipe with OneToOne
I am using model_mommy with Django to create test objects. I want to implement Recipe functionality. I have a model "Teacher" and a model "TeacherSchedule": Teacher(models.Model): some fields ... TeacherSchedule(models.Model): teacher = models.OneToOneField( 'Teacher', on_delete=models.CASCADE, related_name='schedule', ) some fields... The Recipe I try to use then: schedule = Recipe( TeacherSchedule, ) teacher_with_schedule = Recipe( Teacher, schedule=foreign_key('schedule'), ) However, when I run my tests, it seems that the TeacherSchedule object is not created. Am I doing something wrong with the Recipe? -
i have added custom field to list_display but when add that field list_editable in django admin i get error:adminE121
i have a method on model admin class that get data of reverse relation field on list_display but when i add that field in list_editable as well i get an error <class 'app.admin.CustomerAdmin'>: (admin.E121) The value of 'list_editable[2]' refers to 'box_status', which is not an attribute of 'app.Customer'. these is model admin class @admin.register(Customer) class CustomerAdmin(AbstractModelAdmin): class Media: list_display = ['name', 'email', 'phone', 'stylist', 'box_schedule', 'drop_off_step', 'box_status', 'age''created_at', 'payment_status'] list_display_links = ('name', 'email') search_fields = ['name', 'email', 'id'] list_editable = ['stylist', 'payment_status', 'box_status'] below is my box_status method that is getting from related model field. def box_status(self, obj): det = list(obj.box.values_list('box_status', flat=True)) return det this works in list_display but system error in list_editable. -
django-modeltranslation - Django model get() SQL SELECT does not fetch translated fields
I use django-modeltranslation to translate some model fields to Dutch (nl) and French (fr). Now, all has been working fine except for one model: @register(Association) class AssociationTranslationOptions(TranslationOptions): fields = ( 'title', 'name', 'description', ) In the database, I can see the three fields with their translated equivalents: title, title_nl, title_fr, name, name_nl, name_fr, description, description_nl and description_fr. When I update these translated fields in django admin, or in the shell, they are saved correctly. The problem occurs when I fetch this data from the database. So if I fetch this data with Association.objects.all(), Association.objects.get(id=1), or just look at it in the django admin detail view, I see for each translated field the default data. When I inspect the SQL query that Django executed, I see this strange query: SELECT "member_association"."id", "member_association"."title", "member_association"."title", "member_association"."title", "member_association"."slug", "member_association"."name", "member_association"."name", "member_association"."name", "member_association"."description", "member_association"."description", "member_association"."description", "member_association"."mollie_api_key_test", "member_association"."mollie_api_key_live", "member_association"."mollie_profile_id", "member_association"."bank_account_number", "member_association"."created", "member_association"."last_modified" FROM "member_association" WHERE "member_association"."id" = '2' As you can see, there is three times title, three times name and three times description, without the language suffix. So for updating this model, django-modeltranslation works great but for fetching translated data from the database, it does not work for only one of my created models: # … -
How to pass variables from html file to any python file like file.py in Django?
I have a project in Django. And i have a form named report.html. This form has got fields that users enters date ranges. The form is shown below. This is a form that allows users to select date ranges So the project has got a model named sentiment.py this model takes sentiments from the database and analyses them the comments are filtered with date ranges . Below is the code of the file `# Main function def main(): print('Loading the Classifier, please wait....') classifier = joblib.load('svmClassifier.pkl') print('READY') context = { 'posts': Post.objects.filter(date_posted__gte=date(2020,1,1)).filter(date_posted__lte=date(2020,12,31)) } comment=str(context) print(predict(comment, classifier)) if __name__ == '__main__': main() ` instead of using static values like in the code, I need to input a variable that contains values that users punch on the report.html form. So i have tried taking the values from the views.py file shown below.. `def repos(request): wanted_dates = { "datemax" : request.POST.get('datemax',None), "datemin" : request.POST.get('datemin',None) , } return render(request, 'sentiment_analysis/report.html') ` so i have tried to call the variables datemax and datemin from sentiment.py after importing the views.py in sentiment.py Please help me guys on how i can achieve this -
Dajngo generate bar code and download via browser
I am able to generate the bar code and save the image file in the root folder using this library python-barcode. Now I am trying to generate the bar code image and download via browser as HttpResponse Here is my tryouts, import barcode from django.http import HttpResponse def download_bar_code(request): ean = barcode.get('upc', '123456789102', writer=ImageWriter()) ean.save('filename') image = ean.render() # Returns PIL image class # <PIL.Image.Image image mode=RGB size=523x280 at 0x7FAE2B471320> return HttpResponse(image, content_type="image/png") Here the image file is saving in the root folder, but not downloading via browser. I am not able to find the solution for this, I request you to please suggest me some solution to solve this, it will be very grateful for me. Thanks in advance. -
Having trouble with creating env variables that take affect while running my server
this is my first question here, so although I'll try my best to ask the question correctly, please have patience with me. I'm trying to run an OCR with Tesseract with Django on my server at some server (pythonanywhere, if it's important in any way), but I keep having this error: pytesseract.pytesseract.TesseractError: (1, 'Tesseract Open Source OCR Engine v3.04.01 with Leptonica Error opening data file /usr/share/tesseract-ocr/tessdata/heb.traineddata Please make sure the TESSDATA_PREFIX environment variable is set to the parent directory of your "tessdata" directory. Failed loading language \'heb\' Tesseract couldn\'t load any languages! Could not initialize tesseract.') So, at first, I thought I could just move the correct "tessdata" file (which exists on my server) into /usr/share/bin... but I couldn't do that without a root user. no matter what I tried in the Bash shell, I don't have access to the root user (although I was never asked to implement one). I cannot use the "sudo" command that I see so often, I guess it's because it's not a valid command in Bash shell (or Unix, I'm not sure how to refer to it). I guess I have a root user named "Orikle", but no matter what, I couldn't manage to … -
Django Model - ManyToManyField restrict select multiple items from same category
I want to restrict selecting two items from same category and to be able to limit the number of selected items. exemple models.py class Category(models.Model): item_categ = models.CharField() class Product(models.Model): item = models.CharField() item_categ = models.ForeignKey(Category) class CombineProducts(models.Model): combined = models.ManyToManyField(Product) I want User to not be able to select two items from with the same item_categ and limit to 3 products How i do that? Thanks -
What is the difference between Django-Q and Celery?
In the process of researching task queues for Django I encountered the problem - what is the difference between Django-Q and Celery? I know a bit that Django-Q is especially designed to work with Django and Celery is standard goto tool for big projects. I read comments of the Django-Q author but didn't find smth that is not present in both tools in one or other way. I want to know what is the main differences between these two.