Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: multiple return from one class of models.py, but problems using it in another class
I would like to use the same class to pull two teams and display them in a django admin combobox when inserting records. When I extracted only one teams it worked fine, all ok, but now that I added two returns it doesn't work. How can I use the same Teams class to return the team_home and team_away that I will use in the New_Match class? (team_home and team_away will be two comboboxes). I tried writing Teams.team_home and Teams.team_away, but I got the error: TypeError: 'DeferredAttribute' object is not callable. I don't even know if this was a good idea models.py class Teams(models.Model): team_home = models.CharField(max_length=40) team_away = models.CharField(max_length=40) def __str__(self): return self.team_home, self.team_away class New_Match(models.Model): team_home = ChainedForeignKey( Teams, related_name='team_home', chained_field="championship", chained_model_field="championship", show_all=False, auto_choose=True, sort=True) team_away = ChainedForeignKey( Teams, related_name='team_away', chained_field="championship", chained_model_field="championship", show_all=False, auto_choose=True, sort=True) P.S: I'm using smart_selects -
NotImplementedError: This backend doesn't support absolute paths.(Django)
I am trying to upload my media files to AWS Bucket and I am completely able to upload them there on bucket using this code. model.py class Evidence(models.Model): """ Stores an individual evidence file, related to :model:`reporting.ReportFindingLink` and :model:`users.User`. """ def set_upload_destination(self, filename): """ Sets the `upload_to` destination to the evidence folder for the associated report ID. """ return os.path.join("evidence", str(self.finding.report.id), filename) document = models.FileField( upload_to=set_upload_destination, validators=[validate_evidence_extension], blank=True, ) finding = models.ForeignKey("ReportFindingLink", on_delete=models.CASCADE) views.py def form_valid(self, form, **kwargs): self.object = form.save(commit=False) self.object.uploaded_by = self.request.user self.object.finding = self.finding_instance try: self.object.save() messages.success(self.request,"Evidence uploaded successfully", extra_tags="alert-success") except: messages.error(self.request, "Evidence file failed to upload", extra_tags="alert-danger") return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): if "modal" in self.kwargs: return reverse("reporting:upload_evidence_modal_success") return reverse("reporting:report_detail", args=(self.object.finding.report.pk,)) All of this is working fine. But trouble occurs when I am trying to delete the file. Huh? Here is my code for deleting the file. I must tell you guys that there is relationship established between Evidence and ReportingLink table. class ReportFindingLinkDelete(LoginRequiredMixin, SingleObjectMixin, View): """ Delete an individual :model:`reporting.ReportFindingLink`. """ model = ReportFindingLink def post(self, *args, **kwargs): finding = self.get_object() finding.delete() data = { "result": "success", "message": "Successfully deleted {finding} and cleaned up evidence".format(finding=finding), } logger.info( "Deleted %s %s by request of %s", finding.__class__.__name__, finding.id, … -
How merge different table record and show on timeline with django?
I have different table for different medias (like video, audio, ebooks) extending one abstract mode. I want to show them by merging in some order. This is my abstract model: class Media(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(default='', max_length=128) thumbs = GenericRelation(Image) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(to=User, null=True, on_delete=models.SET_NULL) class Meta: abstract = True And this is my extended Audio model: class Audio(Series): duration = models.IntegerField(default=0) metadata = GenericRelation(Metadata, related_query_name='audio_metadata', null=True) # some other fields How do I create a ranking system on the basis of some values in my media tables? And my second question is should the data with rankings be stored in Relation database? (If I store the ranks in some relation database, I would have to create django Generic model I guess and then I can keep data in cache and show on timeline). Please suggest here. -
has anyone used milvus vector database with Django
I am planning on using Django to front end an application that uses one of the ML/AI platforms, and the milvus vector database looks like a good choice. The question is how to use milvus as the database for Django? I have found the python libraries but none that reference how to do it with Django. I am hoping to get some advice on how to hook up milvus vector database to Django. -
What is apps.py in django?
I read about this,And i cunfused The application server takes the INSTALLED_APPS and loads or generates an AppConfig object for each app. This collection of AppConfig objects are then stored in an instance of theApps class. Please someone explain with simple example. Thanks -
Large File Uploads with Amazon S3 + Django 400 Bad Request
i was following this course, i think i did everything right but it gives me POST https://fakebucket.s3-eu-north-1.amazonaws.com/ 400 (Bad Request) views.py class FilePolicyAPI(APIView): """ This view is to get the AWS Upload Policy for our s3 bucket. What we do here is first create a FileItem object instance in our Django backend. This is to include the FileItem instance in the path we will use within our bucket as you'll see below. """ permission_classes = [permissions.IsAuthenticated] authentication_classes = [authentication.SessionAuthentication] def post(self, request, *args, **kwargs): """ The initial post request includes the filename and auth credientails. In our case, we'll use Session Authentication but any auth should work. """ filename_req = request.data.get('filename') if not filename_req: return Response({"message": "A filename is required"}, status=status.HTTP_400_BAD_REQUEST) policy_expires = int(time.time()+5000) user = request.user username_str = str(request.user.username) """ Below we create the Django object. We'll use this in our upload path to AWS. Example: To-be-uploaded file's name: Some Random File.mp4 Eventual Path on S3: <bucket>/username/2312/2312.mp4 """ file_obj = Post.objects.create( author = request.user, title=filename_req ) file_obj_id = file_obj.id upload_start_path = "{username}/".format( username = username_str, file_obj_id=file_obj_id ) _, file_extension = os.path.splitext(filename_req) filename_final = "{file_obj_id}{file_extension}".format( file_obj_id= file_obj_id, file_extension=file_extension ) """ Eventual file_upload_path includes the renamed file to the Django-stored FileItem … -
Error while running python3 manage.py migrate_schemas --shared in Django multi-tenant application
from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Meta: swappable = 'AUTH_USER_MODEL' # Add related_name arguments to avoid clash with auth.User groups = models.ManyToManyField( 'auth.Group', related_name='user_custom_set', blank=True, verbose_name='groups', help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_query_name='user_custom', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='user_custom_set', blank=True, verbose_name='user permissions', help_text='Specific permissions for this user.', related_query_name='user_custom', ) `your text` SHARED_APPS = ( 'tenant_schemas', # mandatory, should always be before any django app 'tenant', 'django.contrib.contenttypes', # everything below here is optional 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', ) TENANT_APPS = ( 'django.contrib.contenttypes', "student", "teacher", "tenant", "account", ) INSTALLED_APPS = ( 'tenant_schemas', # mandatory, should always be before any django app 'tenant', 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', "student", "teacher", "account", ) python3 manage.py migrate_schemas --shared \[standard:public\] === Running migrate for schema public \[standard:public\] Operations to perform: \[standard:public\] Apply all migrations: account, admin, auth, contenttypes, sessions, sites, student, teacher, tenant \[standard:public\] Running migrations: \[standard:public\] Applying contenttypes.0001_initial... \[standard:public\] OK \[standard:public\] Applying contenttypes.0002_remove_content_type_name... \[standard:public\] OK \[standard:public\] Applying auth.0001_initial... \[standard:public\] OK \[standard:public\] Applying auth.0002_alter_permission_name_max_length... \[standard:public\] OK \[standard:public\] Applying auth.0003_alter_user_email_max_length... \[standard:public\] OK \[standard:public\] Applying auth.0004_alter_user_username_opts... \[standard:public\] OK \[standard:public\] Applying auth.0005_alter_user_last_login_null... \[standard:public\] OK … -
Django form and Inline form with crispy forms layout
I have a form with a custom layout from "crispy forms" and an inline form manually in HTML. If I don't use custom layouts, I can save both with no problem, however I'll need to make a button to submit the forms together using layouts. This is my HTML: <form id="registro-form" class="main-form" action="?" method="POST"> <!-- Main Form --> {% csrf_token %} {% crispy form %} <hr> <!-- Inline Formset --> {{ itens_formset.management_form }} {% for formset_form in itens_formset %} <div class="inline-formset-item"> <!-- Render inline formset fields manually --> <div class="row no-gutters"> <!-- Render formset fields here --> </div> </div> {% endfor %} <!-- Submit Button --> <button class="btn btn-success mt-2 mb-5" type="submit" style="width: 110px;">Salvar</button> </form> This is my html code at the moment, but when I click the submit button, nothing happens. This is my views.py: class RegistrarCreate(GroupRequiredMixin, CreateView): # GroupRequiredMixin and other attributes def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ItemFormSet = inlineformset_factory(Registro, Item, form=ItemForm, extra=1, can_delete=False) if self.request.POST: context['itens_formset'] = ItemFormSet(self.request.POST, instance=self.object) else: context['itens_formset'] = ItemFormSet(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() itens_formset = context['itens_formset'] if itens_formset.is_valid(): self.object = form.save() itens_formset.instance = self.object itens_formset.save() return super().form_valid(form) else: print("Formset is invalid") print(itens_formset.errors) return self.render_to_response(self.get_context_data(form=form)) def get(self, request, *args, … -
The difference between prefetch_related and model_set in Djnago
I wonder what is the best flow when I need to retrieve foreign key model objects. is it to use prefetch_related in views.py like: queryset = queryset.prefetch_related('book_set') context={objects:queryset} or to use directly in the template by model_set: {% for attach in objects.book_set.all %} what is better and which one is good for performance? -
Cannot render custom form field in templates
So I've built this some kind of spam detection field that I want to use in our templates. As you can render other other form fields in the template with form.X, I cannot render this one: {{ forms.tour_form.form.spam_field }} <web.utils.forms.HoneypotField object at 0x7f3c0fd98820> But I can't seem to find what's the issue here? I'm using SpamDetectFormMixin in my forms. class HoneypotField(forms.BooleanField): default_widget = forms.CheckboxInput( attrs={"class": "hidden", "tabindex": "-1", "autocomplete": "off"} ) def __init__(self, *args, **kwargs): kwargs.setdefault("widget", self.default_widget) kwargs["required"] = False super().__init__(*args, **kwargs) def clean(self, value): if cleaned_value := super().clean(value): raise ValidationError("") return cleaned_value class SpamDetectFormMixin(forms.Form): spam_field_keys = ["adf", "adg", "adh"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.random_key = random.choice(self.spam_field_keys) self.fields[self.random_key] = HoneypotField() @property def spam_field(self): return self.fields[self.random_key] -
How to make generate Custom ID for employee in django using different String
I have model's like this : class Karyawan(models.Model): id_karyawan = models.CharField(max_length=10, blank=True,null=True) nama_karyawan = models.CharField(max_length=50) jabatan = models.CharField(max_length=15) branch_id = models.ForeignKey(Branch, on_delete = models.CASCADE,null=True) agen_id = models.ForeignKey(Agen, on_delete = models.CASCADE,null=True) salary = models.IntegerField() alamat_karyawan = models.TextField() tanggal_masuk = models.DateField(null=True) kota_karyawan = models.CharField(max_length=30, null=True) ttl_karyawan = models.DateField(null=True) tanggal_resign = models.DateField(null=True,blank=True) no_hp_karyawan = models.CharField(max_length=15) slug_karyawan = AutoSlugField(populate_from='id_karyawan') I want id_karyawan filled using branch_id at first then following id using unique id like 'BDO001','BDO002', 'JKT001' etc. -
How do I connect my React frontend with my Django backend?
I've been trying to connect my React frontend with Django backend server to complete development of a sign up page. I'm trying to test a simple GET HTTP request to my server which I know is functioning correctly. However every time the code compiles I get these errors in the console instead of a response. For reference here are some photos. My Signup page JSX Errors in the console I looked into the errors and found they were Axios Errors. Axios is the HTTP calls library I am using but I am unsure why these errors are being thrown. I have attempted to configure CORS headers in multiple ways as well but with no success. I think I am either declaring it incorrectly. Ways I've tried to Configure my CORS headers: Using the axios properties e.g. Method 1 I found this next fix on this site Here is how I implemented it in my index.js file Method 2 -
Edit multiple tables in database in django
I have a page with the user can edit the information in database, and this page have more than one table (InformacaoFamilia, Imagens). The images i can delete and insert. But when click in confirm the fields with a legend dont save in database. In this page have a form with all fields in InformacaoFamilia models, have a image and a textarea with respectivily legend, have all images and the user can select what goes to delete, and for a add news images. but the legend dont saving in database. update_facthseets.html <article> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <p class="form-group"> {% if field.errors %} <div class="">{{ field.errors.as_text }}</div> {% endif %} <label class="" for="{{ field.id_for_label }}"> {{ field.label }}: </label> {{ field }} </p> {% endfor %} <hr> Editar Legenda {% for image in images %} <div class="imagem"> <p> <label for="edit-legend-{{ image.id }}"> <img src="{{ image.imagens.url }}" alt="{{ image.legenda }}"> Legenda: <textarea type="text" name="imagens-{{ image.id }}-legenda" id="edit-legend-{{ image.id }}" value="{{ image.legenda }}">{{ image.legenda }}</textarea> </label> </p> </div> {% endfor %} Excluir Imagens {% for image in images %} <div class="imagem"> <!-- <p class="paragrafo-{{ image.id }}"> --> <input type="checkbox" name="delete_image" value="{{ image.id }}" id="delete-image-{{ image.id … -
How to reference/mess with a model in a JS file (Django)
So I have a model Profile with a field level (IntegerField) upon completion I would like to add a number to that field but I'm not sure how to reference it in the JS file. Can I edit a models field in a JS file? I'm new to Django and couldn't find anything in the ''documentation''. class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) rpg_class = models.CharField(max_length=100, default='Warrior') level = models.IntegerField(default=1) def __str__(self): return str(self.user) Views.py: profile = self.get_object() context['level'] = profile.level return context for now I just want to know if I can do something like this in hte JS file model_name += 1; but I cant figure out how to reference it -
Custom permission class not returning custom permission denied message - DRF
I have a custom permission class where I want a custom permission message to be returned. But it is returning the default permission denied message. Below is the custom permission class that I have written: class IsAuthenticatedAndIsLr(BasePermission): def has_permission(self, request, view): message = "user is not LR" return request.user.is_authenticated and request.user.regd_as == "LR" and here is how I am using it on the api: @api_view(['POST']) @permission_classes([IsAuthenticatedAndIsLr]) def create_profile(request): ''' this api creates profile for users based on their choosen category. ''' data = request.data model_dict = { 'IND' } try: ... return Response({'message': f'{request.user} isLR'}, status= status.HTTP_201_CREATED) except Exception as e: return Response({"message": str(e)}, status= status.HTTP_500_INTERNAL_SERVER_ERROR) I have followed the docs method to raise a custom message but for some reason it is not working. Please suggest to me what is the cause of this problem. -
Gitlab CI/CD and Azure deploying Django
Am trying to deploy Django code to Webapp using gitlab CI, here's the .gitlab-ci.yml ; image: name: docker/compose:1.25.4 entrypoint: [""] services: - docker:dind variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 stages: - deploy deploy-azure-stag: stage: deploy image: mcr.microsoft.com/azure-cli script: - echo "Logging into Azure" - az login --service-principal -u $AZURE_CLIENT_ID -p $AZURE_CLIENT_SECRET --tenant $AZURE_TENANT_ID - echo "Deploying to Azure App Service" - az webapp up --name $AZURE_APP_NAME However am getting this error, how best can I continuously deploy my Django code . Error am getting. Deploying to Azure App Service $ az webapp up --name $AZURE_APP_NAME WARNING: Webapp 'app_name' already exists. The command will deploy contents to the existing app. ERROR: Unable to retrieve details of the existing app 'app_name'. Please check that the app is a part of the current subscription if updating an existing app. If creating a new app, app names must be globally unique. Please try a more unique name or leave unspecified to receive a randomly generated name. Cleaning up project directory and file based variables 00:01 ERROR: Job failed: exit code 1 -
How can i shuffle my questions in Django views?
I have got a project with quiz and it needed to make random questions. I try like this: @login_required def test(request, test_id): test_set = get_object_or_404(TestSet, id=test_id) questions = test_set.question_set.all().order_by('?') But when i take an a next question it may be repeated. How can i fix it? Also i have a button like "repeat" -
Save() method does not save my form to database
Coding a simple form to add articles to website. Failed to add any information from form to database. My models.py from django.db import models class Articles(models.Model): title = models.CharField('Name', max_length=50) anons = models.CharField('announcement', max_length=250) full_text = models.TextField('Article') def __str__(self): return self.title class Meta(): verbose_name = 'news' my forms.py from .models import Articles from django.forms import ModelForm, TextInput, Textarea class ArticlesForm(ModelForm): class Meta: model = Articles fields = ['title', 'anons', 'full_text'] widgets = { 'title': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Header' }), 'anons': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Announcement' }), 'full_text': Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Text' }), } my views.py from django.shortcuts import render, redirect from .models import Articles from .forms import ArticlesForm def news(request): news = Articles.objects.all() #[:2] - срез записей return render(request, 'news_templates/news.html', {'news': news}) def create(request): error = '' if request.method == 'POST': form = ArticlesForm(request.POST) if form.is_valid(): form.save return redirect('./') else: error = "Wrong format" form = ArticlesForm() data = { 'form': form, 'error': error } return render(request, 'news_templates/create.html', data) template for page {% extends 'main/layout.html' %} {% block title %}Create article {% endblock %} {% block content %} <main class="features"> <h1>Add an article</h1> <form method='post'> {% csrf_token %} {{ form.title }}<br> {{ form.anons }}<br> {{ form.full_text }}<br> <button … -
No build() and create() vs build() vs create() in Factory Boy
I created UserFactory class in factories.py as shown below. I use pytest-django and pytest-factoryboy in Django: # "factories.py" import factory from django.contrib.auth.models import User class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User username = "John" Then, I registered UserFactory class in conftest.py as shown below: # "conftest.py" import pytest from pytest_factoryboy import register from tests.factories import UserFactory register(UserFactory) Then, I created test_user() which prints username with user_factory and user_factory.build() and user_factory.create() in test_ex1.py as shown below: # "test_ex1.py" import pytest from django.contrib.auth.models import User def test_user(db, user_factory): print(user_factory.username) # Here print(user_factory.build().username) # Here print(user_factory.create().username) # Here assert True Then, I got 3 John's as shown below: $ pytest -q -rP . [100%] =============== PASSES ================ ____________ test_new_user ____________ -------- Captured stdout call --------- John John John 1 passed in 0.55s My questions: What is the difference between user_factory, user_factory.build() and user_factory.create() in Factory Boy? When should I use user_factory, user_factory.build() and user_factory.create() in Factory Boy? -
Creating internet function in django webapp
I have been tinkering around with Django for about a year now and I have created a little webapp that I can put in a VPC or remote server, currently the vpn uses a full tunnel, not split. So the users have to use the internet and dns provided through the VPC. Currently the webapp has login, auth, sessions via django-redis, file transfer, chat and dm (functions like iMessage), and in admin all of the permissions for these are setup and handled. The one function I'm having a hard time with is: User requires permissions for external internet access (http/https) If user has permissions, internet access doesn't enable until user also clicks the 'Internet' button to activate it. I had come up with this for the django bit: @login_required @permission_required('accounts.proxy_access', raise_exception=True) def proxy(request): try: # Get the remote IP address of the incoming request remote_ip = request.META['REMOTE_ADDR'] # Add iptables rule to allow traffic from the remote IP subprocess.run(['iptables', '-A', 'OUTPUT', '-d', remote_ip, '-j', 'ACCEPT']) messages.success(request, 'Proxy connected. You may now open a new tab and browse the web normally.') except: messages.error(request, 'Proxy failed. Please contact your administrator.') return redirect('home') can get the incoming IP from the request metadata. Then … -
Open Graph meta tags not fully recognized
I have a Django application hosted on Heroku, which provides event details pages. Each of these pages has Open Graph meta tags set up to enable rich previews when the URLs are shared on platforms like Facebook and iMessage. However, while Facebook is able to recognize and display all the information correctly (title, description, and image), iMessage is showing only the title. Interestingly, the description and the image are completely ignored by iMessage. Here's the template with the relevant Open Graph meta tags: <head> <meta property="og:title" content="{{ name }}"> <meta property="og:description" content="{{ date }}"> <meta property="og:image" content="{{ posterURL }}"> <meta property="og:url" content="{{ request.build_absolute_uri }}"> <meta property="og:type" content="website"> Additional details: The URL for the image is from Firebase Storage, and is URL-encoded. However, it works fine on Facebook and directly in browsers. When testing the link on Chrome, the debugger shows the og:description correctly, but iMessage ignores it. The URL was provided in the format: https://firebasestorage.googleapis.com:443/v0/b/moonlight-f2113.appspot.com/o/... and works when opened directly. I've tried decoding the URL using JS unquote but it results in a non-working link. Any ideas on why iMessage would ignore both the og:description and og:image while Facebook doesn't, and potential fixes? Also note, I also tried doing "og:image:secure_url" … -
Django DateTimeField only recording Date
I have a model with two DateTimeFields. For some reason, only the dates are being entered into the database - not the times as well. So far I haven't been able to figure out the problem. The model: from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils import timezone from accounts.models import CustomUser class WorkTime(models.Model): worker = models.ForeignKey(CustomUser, null=True, on_delete=models.CASCADE) clock_in = models.DateTimeField(null=True) clock_out = models.DateTimeField(null=True) def save(self, *args, **kwargs): if self.id: # Object is being updated self.clock_out = timezone.now() super(WorkTime, self).save(*args, **kwargs) @receiver(pre_save, sender=WorkTime) def set_clock_in(sender, instance, **kwargs): if not instance.id: # Object is being created instance.clock_in = timezone.now() The view: from django.shortcuts import render from django.views.generic import DetailView, CreateView, UpdateView from django.utils import timezone from django.urls import reverse_lazy from .models import WorkTime from django.contrib.auth.mixins import LoginRequiredMixin class WorkTimeCreateView(LoginRequiredMixin, CreateView): model = WorkTime fields = [] # Remove 'worker' from fields as it will be auto-detected template_name = 'timeclock/worktime_form.html' def form_valid(self, form): # Automatically set the worker to the currently logged-in user form.instance.worker = self.request.user # Set the clock_in time form.instance.clock_in = timezone.now() return super().form_valid(form) class WorkTimeUpdateView(LoginRequiredMixin, UpdateView): model = WorkTime fields = ['worker'] template_name = 'worktime_update' # Use a custom template for update … -
Django serializer - Aggregate a function
Goal: Get the total of number of days for a trip Each trip can have multiple legs of varying duration. I have calculated the duration of each leg using a function. I now need to calculate the total sum of all these legs for any given trip. Models class Trip(models.Model): name = models.CharField(max_length=140) class Leg(models.Model): trip_name = models.ForeignKey(Trip, on_delete=models.PROTECT) depature_date = models.DateField() arrival_date = models.DateField() def total_days(self): return ((self.arrival_date - self.depature_date).days) + 1 Serializers class Trip_Serializer(serializers.ModelSerializer): total_no_of_days = serializers.SerializerMethodField() class Meta: model = Trip fields = ['id', 'name', 'total_no_of_days'] def get_total_no_of_days(self, instance): return Leg.objects.filter(trip_name=instance.id).aggregate(Sum('total_days')) class Leg_Full_Serializer(serializers.ModelSerializer): class Meta: model = Leg fields = [ 'id', 'trip_name', 'depature_date', 'arrival_date' , 'total_days' ] The issue I am having is I don't know how to use the total_days function in the Trip Serializer. -
DRF - Can't login in APIView
I have this serializer for login: class UserLoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() And an APIView: from django.contrib.auth import authenticate, login class UserLoginAPIView(APIView): def post(self, request): serializer = UserLoginSerializer(data=request.data) if serializer.is_valid(): username = serializer.data.get("username", None) password = serializer.data.get("password", None) user = authenticate(request, email=username, password=password) if user: login(request, user) return Response(serializer.data) return Response(serializer.error_messages) It authenticates users with the given email and password correctly but it the login(request, user) doesn't seem to work since afterwards, I check and I'm still not logged in. -
Is there a way in Django to specify a starting/first test?
My tests take a long time to run, and many times fixing one test often fixes multiple tests, so I often use --failfast to fix tests one by one in the order in which they error out. I fix a test, then rerun to find the next failure that wasn't due to the same root cause as the one I just fixed. The problem is that the tests take a long time to run and I have to wait through all the tests that I already know will pass. *I'm aware that code changes to fix one test could break a previously run/successful test, but I'd prefer to handle that in a second run. What I would like to do is specify a "starting test" so that I only run the tests from the previous failure forward. I don't see a way to do that using python manage.py test. Is there a trick to get it to not test previously run tests and just pick up where it left off?