Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
filtering a select input in a formset so as not to have the data chosen in the new form
Hi I have someone good at filtering formsets can you help me? I have this formset where there is a select I would like to choose a field in case I add another form the select would have all the fields except the one chosen by the first form. so that each form has a free select but it cannot be repeated with the same value. views from django.forms import formset_factory from .forms import GruppiForm def crea_gruppi(request): gruppiFormSet = formset_factory(GruppiForm, extra = 1) gruppi_formset = gruppiFormSet(prefix='gruppi') context = {'gruppi_formset': gruppi_formset} return render(request, 'crea_gruppi.html', context) form class GruppiForm(forms.ModelForm): giorni_settimana = forms.MultipleChoiceField( choices = models.DatiGruppi.giorni_settimana_scelta, widget = forms.SelectMultiple() ) class Meta: model = models.DatiGruppi exclude = ['gruppi_scheda'] html {% block content %} <section class="mt-5"> <div class="container"> <div class="d-flex align-items-center justify-content-between"> <h2 class="m-0 text-light">crea gruppi</h2> </div> <hr class="bg-light"> <form method="post" autocomplete="off"> {% csrf_token %} {{ gruppi_formset.management_form }} <div class="raccoglitore-gruppi"> {% for gruppo in gruppi_formset %} <div class="gruppo mb-3" style="border: 2px solid red; padding: 5px;"> <div style="color: #fff;"> {{ gruppo.dati_gruppo.label_tag }} {{ gruppo.dati_gruppo|add_class:'form-control mt-2'|append_attr:"placeholder: Gruppo" }} </div> </div> {% endfor %} </div> <div class="mt-3 text-end"> <a href="javascript:void(0)" class="btn btn-warning" id="addgrup">add</a> </div> </form> </div> </section> <div id="form-gruppo-vuoto" class="hidden"> <div class="gruppo mb-3" style="border: 2px solid red; … -
Django: Use makedirs in AWS S3
I have code that will automate CSVs and it will create a dir using makedirs with uuid dirname. The code is working on my local machine but not in S3. I am using an href to download the csv file by passing file_path in context. views.py def makedirs(path): try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise return path def .. tmp_name = str(uuid.uuid4()) file_path = 'static/tmp/'+tmp_name+'/' file_path = makedirs(file_path) reviews_df.to_csv(file_path+'file_processed.csv', index=False) Thanks a lot! -
How to use a ManyToMany field in JsonResponse?
I have this model in Django: class Post(models.Model): poster = models.ForeignKey('User', on_delete=models.CASCADE, related_name='posts') body = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) likers = models.ManyToManyField('User', blank=True, null=True, related_name='liked_posts') likes = models.IntegerField(default=0) def serialize(self): return { 'id': self.pk, 'poster': self.poster.username, 'body': self.body, 'timestamp': self.timestamp.strftime('%b %d %Y, %I:%M %p'), 'likes': self.likes } It works but when I try to add likers to it, I get an error which says I can't use manytomany fields. How can I do such thing? I fetch it in JavaScript like this: fetch('/posts') .then(response => response.json()) .then(data => { console.log(data); }); Using this view: def posts_view(request): posts = Post.objects.all() posts = posts.order_by('-timestamp').all() return JsonResponse([post.serialize() for post in posts], safe=False) -
URL issues with Django 4
I've been using Django since Django 1, and I've always used the same URL patterns (except when we switched from url to path). Now I'm having an issue with 404 errors. I'll give you my Project URLS, and App URLS, and you tell me what am I doing wrong: Project: urlpatterns = [ path('adm/', admin.site.urls), path('', include('core.urls')), path('b/', include('booking.urls')), ] Booking App: urlpatterns = [ path('book/<int:s>/<str:d>/', views.book, name="book"), path('fb/', views.finalize_booking, name="finalize_booking"), ] When I try to call {% url "finalize_booking" %}, it gives me a 404 error. I had the same problem with admin, when I visit xxxx/adm, it gives me a 404 error, it works when I add the slash at the end (xxxx/adm/). This issue was never the case before Django 4. -
Don't queue Dramatiq tasks until Django transaction is committed
I'm currently using Celery but I'm seriously considering migrating to Dramatiq (and django-dramatiq) because of how much simpler things could be. Celery just seems overly complicated (especially for my usecases) and not all that reliable. However, one feature of Celery I use is the option to add a base class for each task. I add a TransactionAwareTask as a base class for most tasks (inspired by this blog post). This base class holds the task (when calling apply_async) and only actually sends it to the queue when transaction.on_commit is reached, meaning that the surrounding transaction succeeded and the task can safely be queued. This way, I will (for instance) never send an email to a client when their action actually failed. And the task will never run before the transaction is committed (which technically could happen if somehow the process was slower than the task queue). Is there a way to do this with Dramatiq? It seems dramatiq middleware might be useful (and I could turn it off for testing where transactions are not committed at all) but I'm not quite sure. Has anyone done something like this? -
Websocket wss configurations in nginx, django, daphne
I have a Django server which uses websockets (Django channels). I have the following configurations of daphne and nginx. What the right way to configure ngnix for wss websockets? Here's what I have: /etc/nginx/sites-available/trading-backend server { server_name trading-backend-test.myserver.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/vagram/trading-backend/static_root/; } location /media/ { alias /home/vagram/trading-backend/media_root/; } location /ws/ { proxy_pass http://unix:/home/vagram/run/daphne.sock; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; } location / { include proxy_params; proxy_pass http://unix:/home/vagram/trading-backend.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/trading-backend-test.myserver.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/trading-backend-test.myserver.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = trading-backend-test.myserver.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name trading-backend-test.myserver.com; return 404; # managed by Certbot } /etc/systemd/system/daphne.socket [Unit] Description=daphne socket [Socket] ListenStream=/run/daphne.sock [Install] WantedBy=sockets.target /etc/systemd/system/daphne.service Description=WebSocket Daphne Service Requires=daphne.socket After=network.target [Service] Type=simple User=vagram WorkingDirectory=/home/vagram/trading-backend/src ExecStart=/home/vagram/trading-backend/env/bin/daphne -b 0.0.0.0 -p 8001 project.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target -
elasticsearch ApiError 406
i used Docker , elasticsearch 7.11.1 image and Django project , so when i run search with django , show me this error Please any hellp ! -
Django DRF group by parent of parent with one-to-one relationships
I'm new to Django, and the jump from SQL to the Django DRF/ORM has been fun but challenging. I'm struggling to understand how to get a sum of a field of a class while grouping by it's parent's parent: models.py : class Plan(models.Model): plan_id = models.BigAutoField(primary_key=True) date = models.DateField() quantity = models.DecimalField( max_digits=18, decimal_places=0, blank=True, null=True) plan_type = models.CharField(max_length=50) plan_line = models.ForeignKey('PlanLine', models.CASCADE) class PlanLine(models.Model): plan_line_id = models.BigAutoField(primary_key=True) year_period = models.CharField(max_length=50) line = models.ForeignKey('Line', models.CASCADE, blank=True, null=True) parent_assembly = models.ForeignKey( 'ParentAssembly', models.CASCADE, blank=True, null=True) class Line(models.Model): line_id = models.BigAutoField(primary_key=True) line_name = models.CharField(max_length=50) factory = models.ForeignKey( 'Factory', models.DO_NOTHING, blank=True, null=True) class Factory(models.Model): factory_id = models.BigAutoField(primary_key=True) factory_name = models.CharField(max_length=50) I'm trying to get Sum(Plan.quantity), group by Factory. I think I need to use the following, but don't understand how to get to Factory in this manor: Plan.objects.value(**Factory**).annotate(qty=Sum('quantity')) -
django abstractuser manytomanyfiled did not get anything
Info: I have create user abstract model in Django. the user has belong to multiple services. when i registered the user in datebase then the user has been register instead user_services. user_services are not stored in databse while we register the new user. models.py class UserAbstract(AbstractUser): user_services = models.ManyToManyField(UserServices, related_name='services', blank=True) is_expert = models.BooleanField(default=False) views.py def Register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') user = form.save() if user is not None: login(request, user) messages.success(request, f'{username} account has been registered!') return redirect('profile') else: messages.error(request, "Invalid username or password.") else: form = UserRegistrationForm() return render(request, 'user/register.html', {'form': form}) -
Django: Calculate and Group inside Django ORM with multiple columns
Good day, right now I'm trying to improve my knwoledge about djangos orm but struggling with the task below: But first, the database looks like this: class DeathsWorldwide(models.Model): causes_name = models.CharField(max_length=50, null=False, blank=False) death_numbers = models.PositiveIntegerField(default=0) country = models.CharField(max_length=50, null=True, blank=True) year = models.PositiveIntegerField(null=False, blank=False, validators=[MinValueValidator(1990), MaxValueValidator(2019)]) causes_name | death_numbers | country | year Alcohol dis. | 25430 | Germany | 1998 Poisoning | 4038 | Germany | 1998 ... Maternal dis. | 9452 | Germany | 1998 Alcohol dis. | 21980 | Germany | 1999 Poisoning | 5117 | Germany | 1999 ... Maternal dis. | 8339 | Germany | 1999 Always a block of all dieseases for each year, every country and so on...The range of years goes from 1990 to 2019. What I - or rather let's say the task - want to achieve, is a list of all countries with calculated numbers of deaths, like this... country | death_numbers France | 78012 Germany | 70510 Austria | 38025 ...but with one additional feature: the number of deaths for each country between 1990-1999 must be subtracted from those of 2000-2019. So a full list would actually look something like this: country | death_numbers | 19xx | 2xxx … -
Extract values form Django context proseccor
I'm looking for the solution for below problem. I have class Category and SubCategory. In SubCategory I take Category as ForeignKey. By contextprocessor I would like to get values of Category. ''' class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) sub_category_name = models.CharField(max_length=50, unique=True, null=True, blank=True) slug = models.SlugField(max_length=50, unique=True, null=True, blank=True) ''' By using contextprocessor I would like to extract ForeigKey value to use it later in for loop: ''' from .models import SubCategory # Create your views here. def sub_menu_links(request): sub_links=SubCategory.objects.all() print(dict(sub_links=sub_links)) return dict(sub_links=sub_links) ''' How can I do it? -
HTML/CSS : justify - center and align two icons in a cell of a table
His guys, I have this table with two icons in the last column. I would like that the icons are next to each, align and with a nice space in the cell. What are the parameters required for that ? I tried with justify-content and margin but it stays like that. Thank you Here is my result : How can I correct that ? Here is the code html : {% block content %} <link rel="stylesheet" href="{% static 'test15.css' %}"> <div class="upload-app"> <div class="upload-in"> <h2>Upload</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {% if url %} <p>Uploaded files : <a href="{{url}}">{{url}}</a></p> {% endif %} </div> <div class="listfiles"> <h2>Files Uploaded</h2> <table id="customers"> <tr> <th>Filename</th> <th>Date</th> <th>Size</th> <th>Actions</th> </tr> {% for file in files %} <tr> <td>{{ file.Filename }}</td> <td>{{ file.Uploaded_at | date:'d.m.Y H:i'}}</td> <td>{{ file.SizeFile | filesizeformat}}</td> <td> <a href="{% url 'download' file.Id %}"> <i class='bx bxs-download'></i> </a> <a href=""> <i class='bx bxs-file-pdf' ></i> </a> </td> </tr> {% endfor %} </table> </div> </div> {% endblock %} Here the css : .listfiles{ margin-top: 20px; border-radius: 12px; background-color: #11101d; color: #fff; transition: all 0.5s ease; width: 800px; height: 600px; } .listfiles h2{ display: flex; justify-content: center; font-size : … -
Updating Django profile returns not authorized error
I would like to update an existing Django profile but getting the error message: PUT http://127.0.0.1:8000/update_profile/ 401 (Unauthorized) The specific network error I am getting is: detail: "Authentication credentials were not provided." This is what the event listener triggered when my update profile button is clicked: const handleSubmit = e => { e.preventDefault(); console.log('handle submit',profileUser) const updatedProfileInfo = { username: profileUser.username, email: profileUser.email, first_name: profileUser.first_name, last_name: profileUser.last_name, city: profileUser.city, country: profileUser.country } console.log(updateProfile) updateProfile(updatedProfileInfo); } updateProfile is destructured from useContext here: let { user,logOutUser, updateProfile } = useContext(AuthContext) here is the updateProfile function: const updateProfile = (userData) => { axios .put('http://127.0.0.1:8000/update_profile/', { headers: { Authorization: "Bearer" + window.localStorage.getItem('authTokens').access, 'Accept' : 'application/json', 'Content-Type': 'application/json' }, body: userData }) .then(res => { console.log(res) }) } I pass updateProfile to my Profile through ContextData: let contextData = { user:user, loginUser:loginUser, logOutUser:logOutUser, updateToken: updateToken, updateProfile: updateProfile } ... return( <AuthContext.Provider value={contextData} > {children} </AuthContext.Provider> ) This is how my access token is stored in localStorage authTokens: {"access":****,"refresh":*****} -
Django Form field for selecting multiple options from a long list
In my user model I have a ManyToMany field to a languages table, which stores the languages a user speaks: spokenLanguages = models.ManyToManyField(Languages, through='LanguageKnowledge', blank=True) I would now like to create a form for the user to select multiple languages from those options. When using a ModelForm the default form field for a ManyToMany model field is a MultipleChoiceField which has SelectMultiple as its default widget. When working with a large number of choices however, this form field is not useful, as one has to browse a long list in order to find a desired choice. Also selecting multiple options is only possible trough shift-clicking the entries. Overall this makes for terrible UX; this is what it looks like: Instead I would like to have something like a CharField that opens a dropdown menu of Choices once focused. These options should then be refined depending on what the user types (e.g. if they type "Be" the dropdown should only show Belarusian and Bengali). Furthermore once the user chooses one of the options it should be added to a list of selected laguages that are visible to the user, from which the choices should also be able to be removed again. … -
JavaScript fetch likes not showing up in the social Post in Django
I am making social website in Django. I made a backend which works properly. The problem is with JavaScript (with which I'm less familiar than python, so sorry about that). When page is loaded, I fetch API which tells me if post is liked or not. Than I should add the corresponding picture (red or gray heart). Note: back end code works as intended. I can visit fetch link and data is correct. The code: js file document.addEventListener('DOMContentLoaded', function() { var allButtons = document.querySelector('#all').childElementCount; console.log(allButtons) var content = document.querySelectorAll('.name'); var button = document.querySelectorAll('#heart'); var edit = document.querySelectorAll('#edit'); var subedit = document.querySelectorAll('#subedit'); var editdiv = document.querySelectorAll('.editdiv'); var post = document.querySelectorAll('.post'); var textarea = document.querySelectorAll('.textarea'); var editbutton=document.querySelectorAll('input[name="edit"]') var csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; var likenum = document.querySelectorAll('#likenum') var page=document.querySelector("#page").innerHTML for (i = 0; i < allButtons; i++) { function listen(i) { var heart = new Image(); heart.id = "main"; var requestPOST = new Request( `/Post/${content[i].id}`, { method: 'POST', headers: {'X-CSRFToken': csrftoken}, mode: 'same-origin' } ); var requestGET = new Request( `/Post/${content[i].id}`, { method: 'GET', } ); edit[i].addEventListener('click', () => { editdiv[i].style.display = 'block'; editbutton[i].className="btn btn-info" post[i].style.display = 'none'; subedit[i].addEventListener('click', () => { fetch(`/edit/${content[i].id}`, { method: 'POST', headers: {'X-CSRFToken': csrftoken}, mode: 'same-origin', body: JSON.stringify({ post: … -
Websocket Send and Receive Image with Base64 bandwith problem
I coded a web socket using Django channels and now want to add the possibility to send images over the chat (obviously it is a chat application). What I did for now: The user picks an image (frontend) The user sends it to the backend (HTTP POST) I use Django signals (it is a listener for the database) to detect if there is a new message with an image appended I send the image back over the websocket Following is the problem: It is slow (not too noticeable but quite slow) Sometimes it causes weird misbehavior So now I thought about sending the image as a base64 and then sending it back directly so I never have any HTTP which can be helpful, because it is a little bit faster. BUT: Base64 images are 20-30 percent bigger and I need to extract all the exif data in the frontend. Is there any possibility to send the images as a file over the websocket to the backend or if not is there a way to get around the quite greater size (20-30 percent), which is a problem because I cannot use too much bandwidth :/ How do other chat application solve … -
AttributeError at /service 'Orderbook' object has no attribute 'save'. , save is a function fm.save()
got an attribute error showing function as an error or the attribute . i had try to solve it but it is not working I had delete all the migrated files and again run python manage.py makemigrations and migrate command but still showing me same error code in admin.py # Register your models here. from django.contrib import admin from .models import * # Register your models here. @admin.register(User) class UserAdmin(admin.ModelAdmin): list_display=('user_id','username','password','name','email_id','contact','address') @admin.register(Orders) class OrdersAdmin(admin.ModelAdmin): list_display=('oid','parcel_info','parcel_qty','parcel_weight','unit_mass','desti') code in views.py from django.shortcuts import redirect, render from django.contrib.auth import authenticate,login from user.forms import * from django.contrib import messages from user.models import * from user.models import Orders # Create your views here. def home(request): return render(request,'home.html') def login(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] userm=authenticate(user=username,passe=password) if userm is not None: login(request,userm) messages.success(request,"You have login successfully...") return redirect("home") else: messages.error(request,"Invalid Username or password...") return redirect("login") else: return render(request,'base.html') def register(request): if request.method=='POST': fm=Userregistration(request.POST) if fm.is_valid(): fm.save() else: fm=Userregistration() return render(request,'register.html',{'form':fm}) def Orderreg(request): if request.method=='POST': fm=Orderbook(request.POST) if fm.is_valid(): fm.save() fm=Orderbook() return redirect('service') else: fm=Orderbook() u=Orders.objects.all() return render(request,'service.html',{'form':fm,'us':u}) def contact(request): return render(request,'contact.html') def about(request): return render(request,'about.html') HTML code {% extends 'base.html' %} {% block body %} {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> … -
How to go from one page to another in django?
I am new in python programming and I created a project for learning. I have created three html pages when I click on the other page link it's show error page not found because url show previous page link with current page link (I don't know how to explain my problem) For Example I have two page index, home if I am on index page(url for index page is "http://127.0.0.1:8000/index/") and want to go to the home page when I click on home page link its show an error because the url for error page is "http://127.0.0.1:8000/index/home/" and I want home page url like this "http://127.0.0.1:8000/home/". Same thing happen when I want to go from home page to index page but when I write manually, page open correctly My code reference code for index.html and home.html links <a class="collapse-item" href="home">Home Page</a> <a class="collapse-item" href="index">Index Page</a> view.py from django.shortcuts import render from django.http import HttpResponse def index_view(request): return render(request, "index.html") def home_view(request): return render(request, "home.html") app/urls.py from django.urls import path from . import views urlpatterns= [ path('index/', views.index_view), path('home/', views.home_view), project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("app.urls")), ] -
Django - Display list of category belonging to each card
I have a Giftcard model, and Category model which holds all category, rate and term for each card. It has a foreign key back to Giftcard. I just want to be able to list category, rate and terms for each Giftcard. As the code is right now, it displays the displays same category, rate and terms for all Giftcard. model class Giftcard(models.Model): name = models.CharField(max_length=100, unique=True) card_image = models.ImageField(upload_to='Giftcard', blank=False) date = models.DateTimeField(auto_now_add=True) publish = models.BooleanField(default=False) class Category(models.Model): category = models.CharField(max_length=250) name = models.ForeignKey(Giftcard, on_delete=models.CASCADE, related_name="specs") rate = models.IntegerField() terms = models.TextField() Here is my views def giftcard(request): giftcards = Giftcard.objects.filter(publish=True) context = { 'giftcards': giftcards, } return render(request, 'dashboard/giftcard.html', context) Here is my template {% for giftcard in giftcards %} <!-- Card --> <div class="col-lg-4 gift__card col-6 p-0"> <a type="button" class="btn"> <img class="img-fluid gift__card-img" src="{{ giftcard.card_image.url }}"> </a> <div class="container d-flex align-items-center justify-content-center"> <div class="gift__card-modal-container py-5"> <div class="card__container"> <div class="gift__card-overlay"></div> <div class="container-fluid bg-light gift__card-modal shadow-lg"> <div class="pop p-5"> <div class="row d-flex align-items-center justify-content-between"> <div class="col-lg-5 col-12 p-0 m-0"> <img class="img-fluid" src="{{ giftcard.card_image.url }}"> <p class="text-muted">Select the card category and the amount.</p> </div> <div class="col-lg-6 col-sm-12 card-details"> <form class="card-form"> <div class="form-group py-2"> <label for="card-category">Card category</label> <input list="category" class="form-control" name="category" id="card_category" … -
how to make search box on the admin change list page make a search over phone_number field in User model
I want to do search over Users using their phone number, the search_list don't do that with fields of PhoneNumberField(): class User(AbstractUser, PermissionsMixin): phone_number = PhoneNumberField( unique=True) email = models.EmailField("Email address", unique=True, null=True, blank=True) first_name = models.CharField(_("first name"), max_length=150, blank=True) last_name = models.CharField(_("last name"), max_length=150, blank=True) I tried to use this field in the admin: class UserAdmin(admin.ModelAdmin): add_form = CustomUserCreationForm form = UserChangeForm search_fields = [ "first_name", "last_name", "email", "phone_number", ] but it didn't work. -
drf - output serializer.data with custom data with APIView
i want to output in my API not only models, but some custom data, before any objects models.py class Example_model(models.Model): example_model_name = models.CharField(max_length=100) serializer.py class Some_Serializer(serializers.ModelSerializer): class Meta: model = Example_model exclude = ["id"] views.py class My_Api(APIView): def get(self, request): all_example_objects = Example_model.objects.all() serializer_class = Some_Serializer(all_example_objects, many=True) #my custom data which i want to include in this serializer before every thing (on top of it) custom_data = {'new_york':777} return Response(serializer_class.data) i want somehow to include custom_data variable in the output (on top of it) so it would looks like this { "custom_data":777, "api_output": [ { "example_model_name":"hello world" }, { "example_model_name":"i love you" }, { "example_model_name":"my name is giovanni giorgio" }, ] } -
Django ModelManager causes DjangoModelFactory to return None
I have a django.Model object which needs to do some parameter processing when it get's initialized. So inside of it I made a ModelManager as the documentation suggests. class ScheduledCourse(models.Model): """Represents a scheduled course that is/was bound to be held.""" class ScheduledCourseManager(models.Manager): def create(self, *args, **kwargs): if not (template := kwargs.get("template")): raise ValueError("Template can not be empty") # If user did not specifiy values for these parameters, use the ones in the template for key in ["title", "description", "price"]: if not kwargs.get(key): kwargs.update({key: getattr(template, key)}) super().create(*args, **kwargs) This works fine, I've tested it and I can create objects with the ScheduledCourse(...) call. When I tried however to make a factory for this object to use in my tests, then the factory returns None, without any error. class ScheduledCourseFactory(factory.django.DjangoModelFactory): class Meta: model = ScheduledCourse template = factory.SubFactory(CourseTemplateFactory) title = "Test title" description = "Test description" price = 1234.0 start_date = datetime.today() end_date = datetime.today() + timedelta(days=1) signup_deadline = datetime.today() - timedelta(days=1) venue = "Test Venue" status = ScheduledCourse.Status.DRAFT What is the cause for my factory returning none? -
Django foreign key display values in detail view
I have a main DB table Radni_nalozi (Work Orders) to which I am attaching Stavke (items) by a foreign key. When I go to see details about a specific Work Order I also want to display all the items that are connected to that Work Order by a foreign key. I tried many different approaches and it seems that I just can't figure it out on my own. I am attaching the code below. In an HTML template, I can only fetch details about specific work orders but not the items. -
Is there a way to annotate this django object computer property?
I have an django Model named Payment that I want to filter by a computed property. class Payment(Model): ...other fields terms = PositiveIntegerField(help_text='days') issued_date = DateField() then I have this property to calcutate the payment_date @property def payment(self): return self.issued_date + datetime.timedelta(days=self.terms) I tried to annotate it with something like this: Payment.objects.annotate(due_date=ExpressionWrapper(F('issued_date') + F('terms'), output_field=DateField())) but unfortunately it's not working. Any help on this is greatly appreciated. -
Nested serilailzer and difficulties with subfactories in a django unit test
I am getting a failing test because (I think) I can't add a subfactory field. The issue is caused by my test: _expected_restuarant_response. It is expecting a response that includes an employee field. The problem is that I can't add this subfactory field to RestaurantFactory because RestaurantFactory is located above EmployeeFactory in the factories.py file (EmployeeFactory is not invoked at that point in the file). I also can't put EmployeeFactory higher than RestaurantFactory because it refers to RestaurantFactory. Could somebody point me in the right direction? Thank you. A simplified version of my files: models.py: class Restaurant(models.Model): name = models.CharField(max_length=20) class Employee(models.Model): badge_id = models.CharField(max_length=20) restaurant = models.ForeignKey(Restaurant) serializers.py: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = [ 'badge_id'] class RestaurantSerializer(serializers.ModelSerializer): employee = EmployeeSerializer(many=True, read_only=True) class Meta: model = Restaurant fields = [ 'name', 'employee'] factories.py: class RestaurantFactory(factory.django.DjangoModelFactory): name = factory.Faker('company') < ----------------------------------- do I need to add an Employee subfactory here? If so how? class EmployeeFactory(factory.django.DjangoModelFactory): badge_id = factory.Faker('id') restaurant = factory.SubFactory(RestaurantFactory) test.py: def _expected_restuarant_response(restaurant): return { restaurant.name, restaurant.employee_set.badge_id } assert response_json == [_expected_restaurant_response(RestaurantFactory())]