Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set Field = To Variable Django
Im trying to set one of my fields equal to a variable. New to Django and Python, appreciate the help. The field in my models week_of i want set to a variable. I made a variable in my Views.py titled weeknumber. week_of = weeknumber Views.PY def K8Points (request): if request.method == 'POST': form = K8PointsForm(request.POST) weekNumber = date.today().isocalendar()[1] if form.is_valid(): points = form.save() Models.PY class K8Points(models.Model): date = models.DateField(default=timezone.now) teacher_class_id = models.ForeignKey(TeacherClass, on_delete = models.PROTECT, default = "") student_id = models.CharField(max_length=50, default = "") total = models.IntegerField() week_of = models.DateField() day = models.CharField(max_length= 10, choices= DAY_OF_THE_WEEK) -
Adding attributes to the Product field Django Ecommerce
I am creating an e-commerce web application on Django and now i just want to know which is the most suitable or the best way to add attributes to the Base Product field (without repeating the base product) and also adding a unique SKU code for each product to find item individually The attributes are "Color", "Size" etc.. This is my Base product field class Item(models.Model): title = models.CharField(max_length=130) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=2, blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True, blank=True, null=True) slug = models.SlugField() description = models.TextField() image = models.ImageField() -
Pagination Concept in Django & efficient way to implement over large objects
While learning Django Concepts, I Came across the pagination concept at: https://docs.djangoproject.com/en/2.2/topics/pagination/ I understand that pagination is used for rendering the object fields of the model into discrete pages. In the documentation, the Author provided the following snippet that : contact_list = Contacts.objects.all() paginator = Paginator(contact_list, 25) Which is basically loading all objects of model Contacts and putting them into pagination to limit the per page size to 25. My Question here is: Imagine we have thousands of objects under Contacts model with large TextField, doing Contacts.objects.all() will take some time, In this situation what would be the best efficient way to implement pagination such that pagination happens over Contacts.objects instead of loading all and then passing to Paginator. -
How can I update a field on a foreign key when creating a new object?
Im quite new to Django and im having a problem with a model. class RestaurantAvailability(models.Model): """RestaurantAvailability Model""" DayTime = models.DateTimeField() restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) availability = models.IntegerField(null=True) def __str__(self): """What to show when we output an object as a string.""" restaurant = self.restaurant.name time = self.DayTime return restaurant + " " + str(time) class Reservation(models.Model): """Reservation Model""" name=models.CharField(max_length=100) email=models.CharField(max_length=100) note=models.CharField(max_length=100) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) restaurantAvailability = models.ForeignKey(RestaurantAvailability, on_delete=models.CASCADE) def __str__(self): """What to show when we output an object as a string.""" person = self.name place = self.restaurant.name time = self.restaurantAvailability.DayTime return person + " " + place + " " + str(time) def save(self, *args, **kwargs): """decrement resturant avalability by 1 on create""" if not self.pk: print('|||||||||||||||||||||||||||||||||||||||||') print(self.restaurantAvailability.availability) print('|||||||||||||||||||||||||||||||||||||||||') self.restaurantAvailability.availability -= 1 # decrement resturant avalability by 1 on create print(self.restaurantAvailability.availability) super(Reservation, self).save(*args, **kwargs) When I create a new Reservation I want to decrement Resturant availability by 1. The save method is running because im successfully creating a new reservation, and I even print out the correct availability after decrement. But when I go to the admin panel to see RestaurantAvailability's I don't see any change in the availability. Its as if the availability is not being saved. My question … -
Setup Bitbucket Pipelines to test django app (need to clone in project & test app)
In Bitbucket, I have a 'project' repo that contains my django project level files, and each app for said project is in its own repo. project_repo app_repo other_app_repo I'm trying to configure Pipelines so I can run tests automatically when pushing up to an app repo to ensure tests pass, coverage is acceptable, etc. Currently, to test an app here are my steps: clone in the project cd into project directory virtualenv venv source venv/bin/activate clone in the app (git clone https://bitbucket.com/myapp) cd up one level (back to the project directory) pip install -r requirements.txt pytest myapp My main question: is something like that even possible with Pipelines? Secondly: What would a pipelines file look like to accomplish that? I can't seem to find any good examples online of even accomplishing this. From what I've been reading it seems like the repos all would have to be the full self-contained project & app to accomplish that. -
Is there a way to use search_fields in a compound field in django-admin?
I have a model whose representation is a junction of 4 fields, so its representation is something like MEDICINE - 1 period (2000/1), if I try to filter for example just for MEDICINE it works, but it does not work if my search I put the exact name in the case: MEDICINE - 1 period (2000/1), This my model: def __str__(self): return ( f'{self.term.course_offer.course} - {self.term} ({self.year}/{self.number})' And my admin: class TermYearAdmin(BaseModelAdmin): search_fields = ( 'term__name', 'year', 'term__course_offer__course__nome', ) def get_queryset(self, request): qs = super().get_queryset(request) return qs.select_related( 'term', 'term__course_offer', 'term__course_offer__course', ).order_by('term__course_offer__course__nome', 'year', 'number', 'term__name') -
Working On Projects With Teams. Hoq Do We Integrate Source Control? Bitbucket Or GitHub?
So, i would like to know if there is a way of programming say a website using a couple of libraries and languages but with different people(a team of 5 to be exact) each working on a specific task. How exactly do I achieve this such that at the end of the day, we can merge the contributions of each person to form one complete and error free project? I have used GitHub before with a team of classmates with whom we were working on a PHP class project but pull requests always disorganized the code. We were always lucky because we were always keen to duplicate the original directories of the code before pushing to GitHub. But merging the commits non GitHub always resulted in disorganized stuff. So, I would like some advice on this one. If I am to use GitHub, am i supposed to commit all our code to the master branch? or is everyone supposed to commit to their own branch... and we then pull everything to the master branch? Anyways, I just get so confused by the whole idea and always wonder how teams that code do it because i know large firms use source … -
Celery or urllib3 is redirecting me to https
I have a problem with making requests trough urllib3. So, I'm connecting through proxy and running script trough celery. urllib3 setup: self.http = urllib3.ProxyManager('http://127.0.0.1:24000') Urllib3 request: page = self.http.request('get', self.start_url, headers=self.headers) And after that I see in celery logs something like this: [2019-11-19 16:13:54,038: INFO/ForkPoolWorker-2] Redirecting http://www.olx.pl/nieruchomosci/mieszkania/wynajem/wroclaw/ -> https://www.olx.pl/nieruchomosci/mieszkania/wynajem/wroclaw/ How can I disable this redirect? -
How to set DateTimeField of Django to the value of form input type datetime-local?
So I have a form input datetime-local: <input type="datetime-local" name="dateTime" value="{{object.date_time_collection}}"> And these are fields of that object in the models.py: date_time_collection = models.DateTimeField() date_of_birth = models.DateField() To set the DateField of Django to the value of a form input date, I know you have to do this: <input type="date" name="dateOfBirth" value="{{object.date_of_birth |date:"Y-m-d"}}"> This is what a DateTimeField looks like pgAdmin4: 2018-12-31 10:56:00+08. So how do I convert that to the format of datetime-local? -
Iterate through a QuerySelectMultipleField Flask
I've been trying to use a QuerySelectMultipleField to serve as a checklist for attendance. But I'm not sure about how to extract the data from the form field into the Attendance model for each member present in routes.py. I was unable to iterate through the form field since it threw an error that it's unsubscriptable. Also, the query factory pulls data from a different model (club_user_query() is from "Club" model) than the model I'm trying to insert the form data into ("Attendance" model). Also, I'm not sure if I can label (get_label) from a different model using a many to many relationship (Club to User) in forms.py. form.py def create_club_minutes_form(club, purchase, fund): def club_user_query(): return club.members #Club to User relationship class ClubMinutesForm(FlaskForm): attendance = QuerySelectMultipleField( query_factory=lambda: club_user_query, get_label=lambda a: a.firstname + a.lastname, #pulls from User model widget=ListWidget(prefix_label=False), option_widget=CheckboxInput() ) **other fields omitted for brevity** submit = SubmitField('Submit') return ClubMinutesForm() models.py user_club_assoc_table = db.Table('user_club_assoc_table', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('club_id', db.Integer, db.ForeignKey('club.id'))) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) firstname = db.Column(db.String(20), nullable=False) lastname = db.Column(db.String(20), nullable=False) school = db.Column(db.String(30), nullable=False) schoolid = db.Column(db.String(60), unique=True, nullable=False) email = db.Column(db.String(60), unique=True, nullable=False) password = db.Column(db.String(60), nullable=False) role = db.Column(db.Integer(), nullable=False, default=ROLES['student']) clubs = db.relationship('Club', … -
Stuck while using django-select2 because of small documentation, better use "pure" select2?
A few days ago, I started using django-select2. So far I've had serveral problems (and spent lots of hours) to get sth. simple to work. Maybe because I am not the greatest programmer or maybe because (in my opinion) the documentation really sucks. Sry to the doc-author (I know you did it in your free time), but 2-3 pages more with good examples would have been great. Furthermore I found out that there is only a small community on stackoverflow using django-select2. Therefore I am wondering if I should invest more time on "pure" select2 (especially of its much better documentation). So my question is, where do I have to invest my time, django-select2 or select2? About me: Advanced in django 2x, Intermediate in Javascript -
Changing dango admin's change_list.html
I wanted to customize the django admin and therefore I copy pasted change_list.html from django admin to my project under templates/admin/section4/section4/change_list.html Now I have view and I have written another template : total_review_count.html where I have extended change_list.html In view: change_list_template = 'admin/section4/section4/total_review_count.html' Code : {% extends "admin/change_list.html" %} {% load i18n admin_urls %} {% block result_list %} <footer style="color:blue;"> <p >The total review upto date: {{ total_review_upto_date}}<br> </p> <p>The total review to be updated: {{ total_review_tobe_updated}}<br></p> <p>Total review to be added : {{ total_review_tobe_added }}</p> </footer> {% endblock %} But doing this I override all the other previous stuff and only getting the one in this template. Is this the correct way of overriding change_list.html? How do I get previous stuff ? -
How to avoid import errors in django within same app
I have a django app where I want MyModel instances to be saved using an Enum choice, which I process in the save() method, such as: # app/models.py from django.db import models from app.utils import translate_choice from enum import Enum class MyEnum(Enum): CHOICE_A = 'Choice A' CHOICE_B = 'Choice B' class MyModel(models.Model): ... choice = models.CharField( max_length=10, choices=[(tag.name, tag.value) for tag in MyEnum], ) ... def save(self, *args, **kwargs): self.choice = translate_choice(self.choice) super().save(*args, **kwargs) Whereas on the app/utils.py I have: from app.models import MyEnum def translate_choice(value): ... return MyEnum.CHOICE_A # For example I keep getting ImportError: cannot import name 'MyEnum' errors on the app/utils.py file when running the application. Is this due to a python circular import error, or am I missing something else? When moving the translate_choice() method to app/models.py it stops happening, but I would like to use this same method in other modules and it is kind of weird having a transforming feature within the models when used in another app. Thank you in advance -
Python Django - Pass initial value into bound form
I'm new to Python Django and I'm trying to set up a bound form with three fields where one field (which will be read only) takes an initial value and displays it on the form; the other two fields will be populated by the user when they completes the form. But when I try to submit the form, the form.is_valid returns false, and I'm not sure what I did wrong. Can anyone please help? Thanks Here's the code: views.py class AddKeyAccompView(TemplateView): template_name = 'AddKeyAccomp.html' def get(self, request, Program): username = request.user.username form = AddKeyAccompForm(request, Program=Program) return render(request, self.template_name, {'form': form ,'title':'Add New Key Accomplishment' ,'User': username }) def post(self, request, Program): username = request.user.username form = AddKeyAccompForm(request.POST, Program=Program) if form.is_valid(): Name = form.cleaned_data['Name'] Description = form.cleaned_data['Description'] form.save() form = AddKeyAccompForm(request, Program=Program) return HttpResponseRedirect(reverse('ModInit', args=[Program])) else: return HttpResponse('invalid form') args = {'form': form ,'title':'Add New Key Accomplishment' ,'User': username ,'Name': Name ,'Desc': Description ,'Program': Program } return render(request, self.template_name, args) forms.py class AddKeyAccompForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): self.program = kwargs.pop('Program') super(AddKeyAccompForm, self).__init__(*args, **kwargs) self.fields['Program'].initial = self.program class Meta: model = Key_Accomplishments fields = ('Name', 'Description', 'Program',) widgets = { 'Name': forms.TextInput(attrs={'required':True, 'class':'form-control'}) ,'Description': forms.Textarea(attrs={'required': True, 'class':'form-control'}) ,'Program': forms.TextInput(attrs={'readonly':'readonly', 'class':'form-control'}) } … -
Add Button To Add Student Django Admin
So below is my admin section, what im trying to do is create a button near my drop down list to add a student to a classroom.( Button in screenshot is where it should be placed) The dropdown list is populated from another table called students , however my field students in class will be a list of all the students in the class. Basically im making a roster. The goal is later when i query that classroom list i return all the students in that class. Right now the field students in class is just set to a charfield, not sure if that is correct. Appreciate the help. [ class TeacherClass(models.Model): teacher_class_id = models.CharField(primary_key = True , default = "", max_length = 50, unique = True) teacher_class_name = models.CharField(max_length = 50) teacher_id = models.ForeignKey(Teachers, on_delete = models.PROTECT, default = "") student_id = models.ForeignKey(Student, on_delete = models.PROTECT, default= "") students_in_class = models.CharField(max_length=500, default = "") class Meta: abstract = False verbose_name = "Teacher Class" def __str__(self): return self.teacher_class_name -
Django admin select all checkbox not working
I'm using Django 2.2.7 with python 3.8 in pipenv 2018.11.26. In my django admin i can't select all items checkbox (see pic below) in list of model objects and not see datepicker with actions "now" & "today". -
Confuse about django relationships
I'm developing a storage software and I got kind confuse with this relationship on Django. The project's model has two classes: Places: class Places(models.Model): tipo = models.CharField(max_length=15, null=True) cnpj = models.CharField(null=True, max_length=11) ie = models.CharField(null=True, max_length=13) cep = models.CharField(null=True, max_length=20) cidade = models.CharField(null=True, max_length=54) bairro = models.CharField(null=True, max_length=54) num = models.CharField(null=True, max_length=54) rua = models.CharField(null=True, max_length=254) maintelefone = models.CharField(null=True, max_length=10) sectelefone = models.CharField(null=True, max_length=10) contactperson = models.CharField(max_length=200, null=True) email = models.CharField(null=True, max_length=254) site = models.CharField(null=True, max_length=254) razaosocial = models.CharField(null=True, max_length=254) fantasia = models.CharField(null=True, max_length=254) created = models.DateTimeField(default=timezone.now, editable=False) last_updated = models.DateTimeField(default=timezone.now, editable=False) def __str__(self): return self.razaosocial And Movementacao: class Movimentacao(models.Model): date = models.DateField(default=timezone.now, null=True) produto = models.ForeignKey( 'Produto', on_delete=models.CASCADE, null=True) # Automatizar qtd = models.IntegerField(null=True, default=1) numero_serie = models.CharField(null=True, max_length=154) tipoMov = models.CharField(max_length=5, null=True) tipo = models.CharField(max_length=5, null=True) nf = models.CharField(null=True, max_length=154) date_nf = models.DateTimeField(default=timezone.now, null=True) origem = models.ForeignKey( 'Places', on_delete=models.CASCADE, related_name='origemovi', null=True) destino = models.ForeignKey( 'Places', on_delete=models.CASCADE, related_name='destinomovi', null=True) obs = models.CharField(max_length=254, null=True) created = models.DateTimeField(default=timezone.now, editable=False) def __str__(self): return self.tipoMov The logic is that a Place can have one or more Movimentacao, and Movimentacao can just have one Place ( Many-to-One, I supose) ,but I expect that the Place got the id of the Movimentacao too, not just … -
How to Apply Query Filtering for JSON list like structure in Django
Django has support for jsonfield using postgres. Below is the example for filtering results based on JSON key, value match. OBJ1 : m1 = Movies.objects.create(movie_name='inception',movies_json_data{"review": "Mind Blowing", "rating": 5} OBJ2 : m2 = Movies.objects.create(movie_name='joker',movies_json_data{"review": "horror", "rating": 4} >>> Movies.objects.filter(movies_json_data__rating=5) <QuerySet [<Movies: Inception>]> How do i perform filter query when data is in a list like JSON structure? movies_json_data=[{"review": "horror", "rating": 4},{"review":"horror-with-scify","rating":"4.5"}] -
Django signals.py not called
I know this has been asked several times. But going through everything I cannot see what I'm missing. What should happen: A django signal should be fired after some user logged in Setup settings.py from my_app.local_settings import * [...] PROJECT_NAME = 'my_app' if PROJECT_NAME not in INSTALLED_APPS: INSTALLED_APPS += (PROJECT_NAME,) my_app/__ init __.py import os default_app_config = "my_app.apps.AppConfig" my_app/apps.py from django.apps import AppConfig as BaseAppConfig class AppConfig(BaseAppConfig): name = "my_app" label = "my_app" def ready(self): super(AppConfig, self).ready() run_setup_hooks() import my_app.signals # here I register the signal my_app/signals.py from django.dispatch import receiver from django.contrib.auth.signals import user_logged_in @receiver(user_logged_in) def do_stuff(sender, user, request, **kwargs): with open('/tmp/log.txt', 'w+') as the_file: the_file.write('okay sir') What I've tested: from django.db.models.signals import * from django.contrib.auth.signals import user_logged_in for signal in [user_logged_in]: print signal.receivers [((4653976464, 140735896872616), <weakref at 0x1155bd310; to 'function' at 0x115660b90 (update_last_login)>), ((4688441544, 140735896872616), <weakref at 0x11777b998; to 'function' at 0x11773f0c8 (do_login)>)] It looks as the signals.py is not called at all. Strange as my setup with signals looked like this in other projects without problems. I think I'm missing something really obvious. Is there something I should take care of regarding app label / name in settings which could cause confusion? -
django-ckeditor upload fails in pythonanywhere with pillow backend(keyerror: "pillow")
I am using django-ckeditor in my django project. python 3.7 Django 2.2.6 django-ckeditor 5.8.0 Pillow 6.2.1 For ckeditor, I am using image2. Everything works in my local server. But when I deploy my project to pythonanywhere, I get following errors: in google developer tools-> network-> xhr Status Code: 500 Internal Server Error in error.log of pythonanywhere KeyError: 'pillow' If I comment out the following code in my settings.py, ckeditor works in pythonanywhere. CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_FORCE_JPEG_COMPRESSION = True Any idea why this is the case? Thanks! -
send X-Postmark-Server-Token in header postmark django
I'm facing Postmark API response 401 (Unauthorized): { "ErrorCode": 10, "Message": "The Server Token you provided in the X-Postmark-Server-Token request header was invalid. Please verify that you are using a valid token." } so how can I send token in header using anyemail esp_extra?, currently I'm doing something like this EMAIL_BACKEND = "anymail.backends.postmark.EmailBackend" ANYMAIL = { "POSTMARK_SERVER_TOKEN": "POSTMARK_TOKEN", "POSTMARK_SEND_DEFAULTS": { "X-Postmark-Server-Token": "TOKEN", "tags": ["app"] }, } but it's not working. -
Django on Synology NAS
Has anyone been successful with setting up a django site onto their synology NAS? I've recently installed python and django onto my nas, but because synology uses a default folder for populating websites it doesn't seem like the ideal setup to use django, I'm curious if anyone has found a way around it? -
I want to ask about error in code block in Django
This is code for a template which i am trying to inherit. This is not giving any error in programme but what these warning are trying to suggest -
What would be the best Django view to display Call Queue
Currently, I'm using a function-based view to display the person to call like an UpdateView, so the logged-in person can edit the data and save changes as well as having an option to set up a meeting with the client. Screenshot for show what I mean Screenshot of Page After the call has been made, the user changes the follow-up date and then when the page refreshes it no longer matches the query and it shows the next call. It's paginated by 1 so I can give a preview of the upcoming calls. Sorry for the long introduction but I just feel like it's a really janky way to get this functionality. Am I doing this in a good way or is there a better path forward that I might have missed? I spent a lot of time in the Django Documentation looking for alternative methods. The behaviour I'd like to get is for the user to just save the call note and then move forward to the next call, the way it's set up now, the Follow Up date has to be changed before the queue moves forward. View for Call Queue: def CallQueueView(request): FormSet = modelformset_factory(Client, form=ClientSheet, extra=0) … -
Show user posts in post list
The following method returns a queryset of posts of users that i follow. def get_queryset(self, *args, **kwargs): # returns the users that i follow following_users = self.request.user.profile.get_following() #gets posts of following users qs = Tweet.objects.filter(user__in=following_users).order_by("-timestamp") return qs I want to add my own posts too in this query set. How to add my own user in this queryset? Something like this: def get_queryset(self, *args, **kwargs): # returns the users that i follow following_users = self.request.user.profile.get_following() following_users.append(self.request.user) # This is not working #gets posts of following users qs = Tweet.objects.filter(user__in=following_users).order_by("-timestamp") return qs Something like this> How should i do that? Im begginer plz help.