Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django displaying the value of changed field
I am building my first Django website as a post office that can track items in a database. However, I am having problem displaying the location history of a tracked package. I tried using simple history but it does not look at a value of a field while fieldtracker only works on my local shell environment. Every time I restart my shell, the history is gone and it does not work on the whole database itself. My package model class Packages(models.Model): package_ID = models.IntegerField(primary_key=True) package_description = models.CharField(max_length=100,default="None") weight = models.DecimalField(max_digits=5,decimal_places=2) signature = models.BooleanField(default=False) delivery_status = models.BooleanField(default=False) order_date = models.DateField('Date Sent') sent_by = models.ForeignKey(Sender,on_delete=models.CASCADE) sent_to = models.ForeignKey(reciever,on_delete=models.CASCADE) tracker = FieldTracker() def __str(self): return self.package_ID My package_history model class package_history(models.Model): package_ID = models.ForeignKey(Packages,on_delete=models.CASCADE) current_location = models.ForeignKey(branches,on_delete=models.CASCADE) def __str(self): return self.package Please if anyone have any idea on how to tackle this it would be greatly appreciated. Thank you -
Chartjs and django - mutiple datasets issue
Having an issue with my chart whereby i can only render 1 dataset in my line chart. I think the issue is with my views because if i hardcode the values in my html directly, everything works. "views.py" def get(request, *args, **kwargs): return render(request, 'dashboard.html', {}) data1 = [28, 89, 50, 94, 45, 67, 78] data2 = [34, 100, 234, 79, 156, 123, 76] class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): label1 = ['0s', '10s', '20', '30s', '40s', '50s', '60s'] data = { "labels": label1, "default1": data1, "default2": data2, } return Response(data) "ursl.py" from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('data/', views.get, name='data'), path('snmp/', views.ChartData.as_view(), name='snmp'), ] "html code" <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <canvas id="myChart" width="500" height="500"></canvas> <script> var endpoint ='/snmp/' var defaultDatas = [] var defaultDatas1 = [] var labels1 = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ labels1 = data.labels1 defaultDatas = data.default1 dafaultDatas1 = data.default2 var ctx1 = document.getElementById('myChart1').getContext('2d'); var myChart1 = new Chart(ctx1, { type: 'line', data: { labels: labels1, datasets: [{ label: 'Egress', data: defaultDatas, backgroundColor: ["rgb(255, 99, 132)"] }, { label: 'Ingress', data: defaultDatas1, backgroundColor: ["rgb(177, 126, 253)"], … -
Django: DB-Query inside for a class in "models.py"
Good day, inside my "models.py" in Django I want to create a new class called "Coworker" with these attributes class Coworker(models.Model): roles = ( ('Role A', 'Role A'), ('Role B', 'Role B'), ) fullname = models.CharField(max_length=255, null=False) role = models.CharField(max_length=100, null=False, choices=roles) supervisor = models.CharField(...?) I also want to create a "supervisor", which should look into this class and show me all the "fullname" with - let's say - "Role A" as choices. So of course in the beginning this field will be emtpy. Is this possible? The function "db_column" doesn't seem to work. Or am I doing something wrong? Thank you all! -
Log response time in Django views
In my view, I am logging to a file using logger.info(message) The message is a string that must contain the HTTP status and how long it took to handle the request. i can't find request-response time in HttpResponse(). What suprises me is that django.server logs the time. How did they do that? -
Cannot import views from mysite.views in Django
mysite is the app name i created in my django project. below is the hierarchy of my app. mysite --- views.py --- tasks.py --- urls.py I have a normal function(there is no request parameter, hence no entry in urls.py as well) in views.py as shown below. def function1(param1,param2): return something I am trying to import this function1 in tasks.py by using from .views import function1 but its throwing an error saying Cannot import views from mysite.views Is there any way to get rid of this error. -
Django Admin - How to (automatically) adding data to related table that can then be used to filter results?
I have tables that share information in a single related table via foreign keys. The relationships work as expected, however, I'm trying to figure out how to automatically populate fields that are then used to filter the results. I hope the example below illustrates what I'm trying to do. In the Models: class UtilType(models.Model): name = models.CharField() description = models.CharField() # following boolean fields used to filter table is_address = models.BooleanField(default=False) is_phone = models.BooleanField(default=False) is_email = models.BooleanField(default=False) is_domain = models.BooleanField(default=False) class Address(models.Model): address_type = models.ForeignKey( UtilType, on_delete=models.SET_NULL, blank=True, null=True, related_name="addresses", limit_choices_to={'is_address': True} ) class PhoneType(models.Model): phone_type = models.ForeignKey( UtilType, on_delete=models.SET_NULL, blank=True, null=True, related_name="addresses", limit_choices_to={'is_phone': True} ) ... more models with similar schema In the Admin: class ContactPhoneNumberInline(admin.StackedInline): model = PhoneNumber min_num = 0 max_num = 5 extra = 0 exclude = ["company"] fields = ( ("phone_type", "country", "phone_number"), ) class ContactEmailAddressInline(admin.StackedInline): model = EmailAddress min_num = 0 max_num = 5 extra = 0 exclude = ["company"] fields = ( ("email_type", "email_address"), ) .... more inlines w/ similar structure @admin.register(Contact) class ContactAdmin(admin.ModelAdmin): fields = ( "company", ("name_first", "name_middle", "name_last",), ("name_salutation", "name_suffix", "title"), ) inlines = [ ContactPhoneNumberInline, ContactEmailAddressInline, ContactDomainInline, ContactAddressInline ] When editing a contact, the action is as expected. I … -
Django shopping cart and order history
My project is an eCommerce project. I face the problem when I wish to submit the shopping cart into a real order, I found that all the order under the same user are sharing the same order_item I am using a boolean expression to locate the shopping cart in order model and I'm not sure is that a good idea. I would also like to know how to clean the shopping cart and transfer it into an order I will be appreciated if you could tell me how to improve :) Models: class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" def get_total_item_price(self): return self.quantity * self.item.price class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) iscart = models.BooleanField(default=True) def __str__(self): return self.user.username def get_total(self): total = 0 for order_item in self.items.all(): total += order_item.get_total_item_price() return total Views: @login_required def add_to_cart(request, slug): item = get_object_or_404(Product, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 … -
Template only contains the last element of an array passed by context
I'm on Django 2.2 and I'm try to parse through an array in my HTML template. But for some reason, only the last element of the array is displayed. Here's mydata, we can that status is an array of str: QueryDict: {'managername': ['blabla'], 'plant': ['FR'], 'status': ['a', 'b', 'c']} This is stored in a variable that I pass through the context: context = { 'data': mydata } return HttpResponse(template.render(context, whatever)) In the HTML template, I do this : <label> {{ data.status }} </label> When I get to the HTML, here's what displayed c Is there some trick I'm missing to have the whole array and not just the last element ? -
unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' when ever I calculate for OT hours and total hours
I'm trying to compute and calculate total_hours into my model. I create a method to calculate it however I'm getting an error when I do it. The error is called: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' I just need some assistance on what to do on this one. Thanks in advance. Here is the code in question: def convert_timedelta_to_hrs(td): return decimal(td.total_seconds() / (60 * 60)) class DPRLog(models.Model): STATUS_CHOICES = ( ('PENDING', 'PENDING'), ('CANCELLED', 'CANCELLED'), ('COMPLETED', 'COMPLETED'), ) TASKS_CHOICES = ( ('TESTS EXECUTION', 'TESTS EXECUTION'), ('TESTS DESIGN', 'TESTS DESIGN'), ('MOBILE TESTING WORKSHOP', 'MOBILE TESTING WORKSHOP'), ('BENCH ACTIVITY', 'BENCH ACTIVITY'), ('DEFECT ANALYSIS','DEFECT ANALYSIS'), ) testuser = models.ForeignKey(User,on_delete = models.CASCADE,unique_for_date= 'reportDate') status = models.CharField(max_length=30, choices=STATUS_CHOICES,null=True) reportDate = models.DateField(blank=False, null=False) login = models.TimeField(blank=False, null=False) logout = models.TimeField(blank=False, null=False) total_hours = models.DecimalField(max_digits=4,decimal_places=2,null=True,blank=True) ot_hours = models.DecimalField(max_digits=4,decimal_places=2,null=True,blank=True) mainTasks = models.CharField(max_length=50, blank=False, choices=TASKS_CHOICES, null=True) remarks = models.CharField(max_length=30,null=True,blank=True,) def __str__(self): return f'{self.testuser.full_name} DPR Log' def calculate_hours(self): total_hours = self.logout - self.login - datetime.timedelta(hours=1) total_hours = convert_timedelta_to_hrs(total_hours) ot_hours=None if total_hours > 8.00: ot_hours = self.total_hours - datetime.timedelta(hours=8) ot_hours = convert_timedelta_to_hrs(ot_hours) total_hours = 8.00 return total_hours, ot_hours def save(self,*args,**kwargs): self.total_hours, self.ot_hours = self.calculate_hours() super().save(*args, **kwargs) -
Django taggit: why annotate(same_tags=Count('tags')) counts the number of common tags instead of the total number of tags?
I am following tutorials on Django 2 by Example. I don't understand step (2): Why is Count('tags') not counting the total number of tags possessed by that post? I have tried searching on Taggit's API reference but that seems not relevant. Can anyone explain it for me please? The following code: (1) searches similar posts by looking at their common tags. (2) uses Count aggregation function to generate a calculated field same_tags. (3) orders the result by the number of shared tags in descending order etc... # List of similar posts post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids)\ .exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags'))\ .order_by('-same_tags','-publish')[:4] -
Updating a user model in Django when they fill out a form on a different model
I am struggling to work out how to achieve something and would appreciate someone suggesting the correct Django way to do it. I have a custom user model which is fairly basic but includes a BooleanField which says whether they have filled out a voluntary equality and diversity form. There is a very basic model which holds the equality and diversity form data without any reference to the users which filled out each response. What I want is this, when a user fills out a valid equality and diversity form it puts True in the user model box to say they have filled out the form. I would be massively appreciative if anyone knows the correct way to do this as I am tying myself up in knots and have got myself quite confused. Here is a simplified version of the code: users/models.py class CustomUser(AbstractUser): # Has the user completed the EDI form? edi = models.BooleanField(default=False) def get_absolute_url(self): return reverse('profile', args=[str(self.username)]) equality_diversity/models.py class EqualityDiversity(models.Model): age = models.CharField(max_length=8, choices=AGE_CHOICES) ethnicity = models.CharField(max_length=64, blank=True, null=True) ... (etc) equality_diversity/views.py class EqualityDiversityView(LoginRequiredMixin, CreateView): model = EqualityDiversity template_name = 'equality_diversity.html' form_class = EqualityDiversityForm login_url = 'login' success_url = '/' def form_valid(self, form): return super().form_valid(form) -
Implement LiteSync on Django
I've tried to write sync sqlite database between 2 different Server but same app and DB. But when i turn on litesync.io in console, it doesnt synchronize the Django project with Django project in another server. I know it's wrong because i must configure it first in django project, but i've tried to change NAME of DATABASES into URI and it not work. I've tried it in console to execute query, it works, but not in Django Project. So, how to implement litesync on Django project? How to save data into Sqlite DB by URI? -
getting error : Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: [u'polls/<int:question_id>/'] in django
I am newbie here in django, when i run my app, I am getting this error Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: [u'polls/<int:question_id>/'] here i have uploaded my code for index.html and urls.py can you please check my code and help me to resolve this issue ? index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} {% if question.id %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% else %} {% endif %} {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} urls.py from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ url('', views.index, name='index'), # ex: /polls/5/ url('<int:question_id>/', views.detail, name='detail'), # ex: /polls/5/results/ url('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ url('<int:question_id>/vote/', views.vote, name='vote'), ] -
Can we set min max restriction on form field in views. Django
Form's Integer field quantity = forms.IntegerField() I want to set the min_value and max_value on this field in views such as form.fields['quantity'].min_value = 0 It's possible to set the initial value using form.fields['quantity'].initial = 12 But the min value is not working. Can anyone help me with that. -
Where to put customized views that inherits from django-allauth?
I have a Django project that has one app (survey), so in my project's urls.py, I have: urlpatterns = [ ... path('accounts/', include('allauth.urls')), path('survey/',include(('survey.urls','survey'), namespace='survey')), ...] I am using django-allauth to provide the authentication mechanism. However, I inherited the SignupView that is in Django-Allauth like so: class MySignupView(SignupView): def form_valid(self.request): self.user = form.save(self.request) assignmentAttendance=AssignmentAttendance.objects.create(user=user, assignment=Assignment.objects.get(id=1), status=False) assignmentAttendance.save() assignmentAttendance = AssignmentAttendance.objects.create(user=user, assignment=Assignment.objects.get(id=2), status=False) assignmentAttendance.save() try: return complete_signup( self.request, self.user, app_settings.EMAIL_VERIFICATION, self.get_success_url()) except ImmediateHttpResponse as e: return e.response The additional process (in the override the form_valid) is to create data for another model in the survey app. I do not know the best place to put the class MySignupView, so I put it in the project's urls.py and then add its view to the urlpatterns: urlpatterns = [ ... path('accounts/', include('allauth.urls')), path('survey/',include(('survey.urls','survey'), namespace='survey')), path('accounts/signup', MySignupView.as_view(), name="account_signup"), ...] Doing this works, since my MySignupView is what is called when a user wants to signup instead of the SignupView from Django-allauth. Is there a better configuration for where to writing custom views and where to put them. If so, how should it be done? I am aware that Django-allauth has a default way for adding custom form by setting the ACCOUNT_FORMS in the settings.py. … -
how can i substract time dates in django to gate the age of a post?
i want to display the age of video like "this video uploaded 2 days ago", "3 weeks and so on" i have tried this but not working #this is not working !! from django.db import models from datetime import datetime class Video(models.Model): video_upload = models.FileField(upload_to='media') video_detail = models.TextField(blank=True) video_title = models.CharField(max_length=100) pub_date = models.DateTimeField(auto_now=True) def age_of_video(self): return datetime.now() - self.pub_date def __str__(self): return self.title in template {% for video in all_videos %} {{ video.age_of_videos}} {% endfor %} -
Display images in Django using http links
I am a beginner in Django so please help me with this problem of mine. I am getting http links of images from a google api that i am calling. I want to show those images on my website but the photos are not showing up. My views.py file def hotel1(request): api_key = 'myAPIkey' url = "https://maps.googleapis.com/maps/api/place/textsearch/json?" if request.method == 'POST': city = request.POST['city'] query = str(city) r = requests.get(url + 'query=' + 'hotels in '+ query + '&key=' + api_key) x = r.json() y = x['results'] name = [] photo_reference = [] for i in range(len(y)): name.insert(i, y[i]['name']) photo_reference.insert(i, y[i]['photos'][0]['photo_reference']) a = list(zip(name,photo_reference)) url2 = "https://maps.googleapis.com/maps/api/place/photo?" photo_url = {} for i in range(len(y)): r = requests.get(url2 + 'maxwidth='+'400' + '&photoreference='+a[i][1]+ '&key=' + api_key) if r.status_code == 200: with open('D:/Travel app/travelX/mysite/static/mysite/images/hotels/' + query + a[i][0] + '.jpg', 'wb') as f: for chunk in r: f.write(chunk) photo_url[i] = r.url #get url of images return render(request, 'mysite/test.html', photo_url ) And my Html file is <form method="post" class="post-form" action="test.html"> {% csrf_token %} <div class="fields"> <div class="form-group"> <input type="text" class="form-control" placeholder="Destination City" name="city"> </div> <div class="form-group"> <input type="submit" value="Search" class="btn btn-primary py-3 px-5"> {% for value in photo_url.values %} <img src="{{value}}"/> {% endfor %} … -
Insert data in model from json in django
My Model: class Post_Data(models.Model): id = models.AutoField(primary_key=True) data = models.CharField(max_length=200) I need to insert the json data inside the model which will be passed in the form of "file" in postman. I tried: def post(self, request): json_file = request.FILES['json_file'] with open(json_file) as f: json_data = json.loads(f) a = Post_data(data=json_data) a.save() But it's not working. -
How can i use django templates in Vue JS?
So i am building an e-commerce website. The login and registration of users is handled in django templates. All the other part of the frontend is in VueJS. Is there a way that when i click on the login button on any page in my website, it takes me to the django login template? -
Allowing users to select which flow to roll back to django-viewflow
Hey all i have been using viewflow as the workflow engine in my django project. I wanted to know if it was possible to allow users to 'select' which flow they wish to roll back to if lets say an approval was rejected. Here , the director chooses 'Reject' , however it doesn't make sense to end the flow here , instead it should be a be a selectable 'roll back' , so that the the people down the line do not need to restart the entire process again. Here's what i have done so far : flows.py #director will approve or dont approve approve_by_director = flow.View( UpdateProcessView, form_class=DirectorApproveForm, task_title="Approval By Director" ).Permission("cash.director" ).Next(this.check_director) check_director = flow.If( cond=lambda act: act.process.director, task_title="Processing" ).Then(this.send).Else(this.justification) #justifications for the roll back. justification = flow.View( JustificationView, task_title="Justifications for Roll Back" ).Assign(lambda act: self.request.user ).Permission(auto_create=True ).Next(this.roll_back) roll_back = flow.Handler(this.roll_back_call).Next(this.approve_by_preparer) ##<---- here , i am just sending it back to the 'preparer' , however it would be great if this could be dynamic! end = flow.End() def roll_back_call(self, activation): esig = ESignatures.objects.filter(paymentVoucherProcess = activation.process).filter(voided = False) docu = Attachment.objects.filter(paymentVoucherProcess = activation.process).filter(voided = False) if len(esig) > 0 : for sig in esig: sig.voided = True sig.save() if … -
In django rest api An attempt was made to access a socket in a way forbidden by its access permissions
I was trying to do a "POST" request but getting this WinError 10013 Socket issue in my django api. I can do the "GET" request successfully but why i am getting this error on post request. OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions "POST /api/v5/users/email/ HTTP/1.1" 500 177849 -
Search filtering from other paragraph models django
My search form works when typing words that are pulled from the description models.py, but I want to add another separated description called "the space" and display the text searched same as the in the description, I've tried several combinations code. This is my current code. In my views.py: # Keywords description if 'keywords' in request.GET: keywords = request.GET['keywords'] if keywords: queryset_list = queryset_list.filter(description__icontains=keywords) # space description if 'keywords' in request.GET: keywords = request.GET['keywords'] if keywords: queryset_list = queryset_list.filter(the_space__icontains=keywords) In models.py: description = models.TextField(blank=True) the_space = models.TextField(blank=True) context = { 'values': request.GET } In my html: <input type="text" name="keywords" class="form-control" placeholder="Keyword (search words)"> -
Как правильно реализовать ajax рендер модели в Django? [closed]
Есть страница с мероприятиями и некоторое количество фильтров, хочется сделать фильтрацию без перезагрузки страницы. Только учусь и задумался над тем правильно ли я собираюсь делать реализацию AJAX в CMS Wagtail а Django. Как я понял рендер делается не силами шаблона а уже javascript. Мой план 1. Делаю view возвращающую json 2. Обрабатываю JSON и генерирую HTML 3. Profit Вопрос в том что мне кажется что можно рендер сделать силами шаблона django. Просьба описать правильный workflow в этом случае и на что обратить внимание -
Django - upload_to dynamic path from different models
I'm trying to use ImageField upload_to to save the image in organize manner, but I cannot figure out if this is possible or how to. I'm trying to have this folder hierarchy inside media: Book-title Chapter 1 img1 img2 Chapter 2 img1 Models: class Book(models.Model): title = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) author = models.ManyToManyField(Author) chapter = models.ManyToManyField(Chapter, related_name='books') def image_dir_path(instance, filename): chapter = instance.slug return os.path.join(chapter, filename) class Chapter(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=130, unique=True) slug = models.SlugField(max_length=150, unique=True, blank=True) picture = models.ImageField(upload_to=image_dir_path) created_at = models.DateField(auto_now_add=True) I'd like to have something like this, so I can use the book title to build the path: def image_dir_path(instance, filename): book = instance.book.slug chapter = instance.slug return os.path.join(book, chapter, filename) This do not work, instance it's only related to the class where you call image_dir_path. It's something similar possible? -
Django rest framework, serializer serializer method field doesn't save changes to db?
I have a DRF API which contains a field that's being set in the serializer: class KnownLocation(models.Model): latitude = models.FloatField(name="Latitude", verbose_name='Latitude', unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", ) longitude = models.FloatField(name="Longitude", verbose_name="Longitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", ) elevation = models.FloatField(name="elevation", help_text="Enter the location's ~Sea Level~ elevation, or Leave empty for auto-fill " "by me :). ", verbose_name="Elevation in meters", blank=True, default=DEFAULT_VALUE ) And the serializer: class KnownLocationSerializer(HyperlinkedModelSerializer): date_added = DateTimeField(format="%d-%m-%Y", required=False, read_only=True) elevation = SerializerMethodField() def validate_elevation(self, value): """ Validate that elevation of location has been updated already. """ if value is None or 1: raise APIException.elevation.throw() return value def get_elevation(self, obj): """ This method, which is connected to SerializerMethodField, checks if the object's elevation value exists, if not, it fetches it. """ elevation = obj.elevation if elevation is None or 1: elevation = get_elevation(lat=obj.Latitude, lon=obj.Longitude) elevation = round(elevation) return elevation pass The method works and fetches the elevation, yet, it doesn't save it to the DB. did I miss that part in the docs? so, how can I save it to the DB, using save didn't work for me: def save(self, **kwargs): latitude, …