Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to inherit django model to make models records independent?
I'm creating ToDo app and I want to archive task when completed. To do so I have created Todo model and TodoArchive, which inherits after Todo: from django.db import models from django.utils import timezone class Todo(models.Model): date_added = models.DateTimeField(default=timezone.now) task = models.CharField(max_length=100) story = models.CharField(max_length=100, default="-") project = models.CharField(max_length=100) complete = models.BooleanField(default=False) def __str__(self): return self.task class TodoArchive(Todo): date_archived = models.DateTimeField(default=timezone.now) def __str__(self): return f'ARCH {self.task} - {self.date_added}' After that I loop through each task in view and create new archive object: def archive_completed(request): for todo in Todo.objects.all(): if todo.complete: archive_todo = TodoArchive(task=todo.task, story=todo.story, project=todo.project, complete=todo.complete, date_added=todo.date_added) archive_todo.save() todo.delete() return redirect('home') But after that elements moved to Archive model belongs to both models as shown on the picture below: https://i.stack.imgur.com/AVxHy.png The effect is that when I delete element from one model it removes it from the other immediately. Does anyone knows why and how to eliminate this behaviour? -
Combine multiple foreign key in a single field in Django serializer
My model.py camera_choices = ( ('0', 'Entry'), ('1', 'Exit'), ) class Device(models.Model): DeviceId = models.AutoField(primary_key=True, db_column='DeviceId') DeviceName = models.CharField(max_length=50, null=True, default=None, blank=True) DeviceCode = models.CharField(max_length=25, null=False, blank=False) IpAddress = models.CharField(max_length=15, null=True, default=None, blank=True) Description = models.CharField(max_length=250, null=True, default=None, blank=True) DefaultAccess = models.BooleanField(default=True, null=True, blank=True) EntryCamera = models.ForeignKey(Camera, on_delete=models.CASCADE, db_column='EntryCameraId', related_name="entry_camera", null=True, blank=True, default=None) ExitCamera = models.ForeignKey(Camera, on_delete=models.CASCADE, db_column='ExitCameraId', related_name="exit_camera", null=True, blank=True, default=None) DeviceType = models.ForeignKey(DeviceType, on_delete=models.CASCADE, db_column='DeviceTypeId') DeviceStatus = models.SmallIntegerField(default=1, null=True, blank=True) class Meta: db_table = "Device" class Camera(models.Model): CameraId = models.AutoField(primary_key=True, db_column='CameraId') CameraName = models.CharField(max_length=50, unique=True) CameraUrl = models.URLField() CameraType = models.CharField(max_length=30, choices=camera_choices) class Meta: db_table = "Camera" my serialiser.py class DeviceListSerializer(serializers.ModelSerializer): class Meta: model = Device fields = ['DeviceId', 'DeviceCode', 'DeviceName', 'IpAddress', 'Description', 'DefaultAccess', 'DeviceStatus', 'DeviceType', 'EntryCamera', 'ExitCamera'] depth = 1 my views.py def device_list(request): try: device = Device.objects.all() serializer = DeviceListSerializer(device, many=True, read_only=True) return Response(serializer.data, status=status.HTTP_200_OK) except Exception as ex: logging.getLogger("error_logger").exception(repr(ex)) i got the response [ { "DeviceId": 3, "DeviceCode": "DevTest3", "DeviceName": "", "IpAddress": "", "Description": "", "DefaultAccess": false, "DeviceStatus": 1, "DeviceType": { "DeviceTypeId": 1, "DeviceType": "Devicetype1", "DeviceTypeStatus": true }, "EntryCamera": { "CameraId": 1, "CameraName": "Camera1", "CameraUrl": "http://www.dgdge", "CameraType": "0" }, "ExitCamera": { "CameraId": 2, "CameraName": "Camera2", "CameraUrl": "http://www.hth", "CameraType": "1" } } ] is it possible … -
Django Google Cloud Storage file upload failed with 400 error
I have written my django rest framework which I want to deploy to GCP. I decided to use Google Cloud Storages for files. I'm using this: https://github.com/jschneier/django-storages/blob/master/docs/backends/gcloud.rst I have an API endpoint, from where a user can upload his/her image. This is how the model looks like: class EndUser(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to="users/", blank=True) name = models.CharField('Name', max_length=256) location = models.PointField() device = models.ForeignKey(FCMDevice, on_delete=models.CASCADE) current_task = models.ForeignKey('tasks.Task', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name Here's how the view is set up: class EndUserViewSet(viewsets.ModelViewSet): parser_classes = (MultiPartParser, FormParser) queryset = EndUser.objects.all() def get_serializer_class(self): if self.request.method == "GET": return EndUserSerializer return CreateUpdateEndUserSerializer Now, this works fine locally but if I change my settings and try to upload to google cloud storage it gives a 400 error: google.api_core.exceptions.BadRequest: 400 POST https://storage.googleapis.com/upload/storage/v1/b/my-project-id/media/o?uploadType=multipart&predefinedAcl=publicRead: ('Request failed with status code', 400, 'Expected one of', <HTTPStatus.OK: 200>) Here's the relevant part of my settings.py: GS_DEFAULT_ACL = "publicRead" MEDIA_ROOT = "https://storage.googleapis.com/project-id/media" STATIC_ROOT = "https://storage.googleapis.com/project-id/static/" DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_BUCKET_NAME = "my-media-bucket" GS_CREDENTIALS = service_account.Credentials.from_service_account_file( "credentials.json" ) -
Disable Django Form Field only in UpdateView
I have a UserForm in forms.py which is common between Register and Edit Profile features, its Views are also common, as 90% of the functionalities are similar in both the views. I want to disable the EMailField from UserForm only in Edit Profile page but should be editable in Register page. Here is my code: forms.py class UserForm(forms.ModelForm): password = None email = forms.EmailField(required=False, disabled=True) salutation = forms.ChoiceField(choices=Choices.SALUTATIONS) blood_group = forms.ChoiceField(choices=Choices.BLOOD_GROUPS) class Meta: model = User fields = ('salutation', 'blood_group', 'email', 'first_name', 'middle_name', 'last_name', 'gender', 'birth_date', 'profile') Same Form is being rendered both the times in register and edit views. Here are my urls.py. path('register/', StudentView.as_view(), name='addview'), path('<int:pk>/edit/', StudentView.as_view(), name='editview'), in the views.py (For detailed views.py, check the accepted answer) userform = UserForm(request.POST or None, instance=self.object) admission.html <form class="form" name="admissionForm" id="admissionForm" method="post" enctype="multipart/form-data" action="{% url 'addview' %}"> {% csrf_token %} <div class="pages"> <h4 class="mt-2 mb-3">Personal Information</h4> {% include "student_errors.html" %} {{userform|crispy}} .... <div class="btn_container"> <button type="submit" class="btn btn-info float-right btn-next">Submit</button> </div> </div> -
How can I display my data in a table using django [closed]
I need to store the data from this API in a database. I managed that, but now I need to render this data in the following way: How can I display this data as a table, in the format as shown in the image? -
Allow ordering in list_display a property field
I am trying to setup ordering in django admin list_display, but I cannot make it to work. I have tried with using queryset annotations, but I have not found how to annotate it with a model property. The code: models.py class Person(models.Model): name = models.CharField(max_length=150, verbose_name='Nome Próprio') dob = models.DateField(verbose_name="Date of birth") @property def age(self): born = self.dob today = date.today() return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) admin.py @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ['name', 'dob', 'age'] def get_queryset(self, request): qs = super(PersonAdmin, self).get_queryset(request) qs = qs.annotate(age='age') return qs This is my attempt so far, is there any easy fix? I am quite a novice on Django. Thank you -
Make static files from django's collecstatic part of Docker image
I want to include static files generated from python manage.py collectstatic in the Docker image. For this, I included the following line in my Dockerfile CMD python manage.py collectstatic --no-input But since it runs the command in an intermediate container, the generated static files aren't present STATIC_ROOT directory. The following lines I can see on the logs of build. Step 13/14 : CMD python manage.py collectstatic --no-input ---> Running in 8ea5efada461 Removing intermediate container 8ea5efada461 ---> 67aef71cc7b6 I'd like to include the generated static files in the image. What shall I do to achieve this? -
Django custom SimpleListFilter
I have this two models: class Intervencao(models.Model): ....... class Alvaras(models.Model): intervencao = models.ForeignKey(Intervencao, related_name='IntervencaoObjects2',on_delete=models.CASCADE) data_alv = models.DateField(blank=True,null=True,verbose_name="Data do alvaras") I want to add a custom filter in my Intervencao.Admin, that do a query to the last record i have in Alvaras and check if the field data_alv it is empty or not. I already got it working, but i want only the last record. class Dataalv(admin.SimpleListFilter): title = ('data de alvaras') parameter_name = 'data_alv' def lookups(self, request, model_admin): return ( ('yes', 'yes'), ('no', 'no') ) def queryset(self, request, queryset): value = self.value() if value == 'yes': return queryset.filter(IntervencaoObjects2__data_alv__isnull=False) elif value == "no": return queryset.filter(IntervencaoObjects2__data_alv__isnull=True) class IntervencaoAdmin(admin.ModelAdmin): list_filter = Dataalv, -
Find reverse ForeignKey instances of Queryset?
The django documentation is pretty clear on how to look up fields on single instances but what about reverse relationship QuerySet objects. Example: class Author(models.Model) name = models.Charfield(...) class Book(models.Model) author = models.ForeignKey(Author, ...) I now create a queryset object: special_authors = Author.objects.filter(name__icontains="lui") Now, I want to find all books that belong to special authors. I want to do something like this: special_authros.book_set.all() Without doing this: books = [] for author in special_authors: books += author.book_set.all() Is there a way to do this easily? -
Well I am having issue with publish button in my django site .It is not performing its' function
I am using django 3.0.3,python 3.8.5 and Vs code as an IDE. I am clicking on the publish button but it is not working. ---Models.py--- def publish(self): self.published_data = timezone.now() self.save() ---views.py--- @login_required def post_publish(request,pk): post = get_object_or_404(Post,pk=pk) post.publish() return redirect('post_detail',pk=pk) ---urls.py--- path('post/<int:pk>/publish/',views.post_publish,name ='post_publish'), --post_detail.html(template)-- <a class="btn btn-primary" href="{% url 'post_publish' pk=post.pk %}">Publish</a> Any help will be appreciated Thank you -
Django static files cannot find the path specified double backslash in path
I'm getting the following error when running collectstatic in Django: FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\rutha_000\\Documents\\DjangoProjects\\jarvis\\static' with two backslashes rather than one in the path My stylesheet is located in C:\Users\rutha_000\Documents\DjangoProjects\jarvis\static\jarvis\css\ And my settings file looks like this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Not sure why there is a double backslash or what's going wrong here? Thanks -
how to show and load another django website with access cookies in HTML
how can i load another website with accessing cookies for this features: Login / Register(POST Method) CRUD operations NOTE : my iframe run at local index.html: <iframe src="https://example.com" frameborder="0" width="800" height="800" sandbox="allow-same-origin allow-scripts"></iframe> NOTE : example.com written in django what should i do to django website(example.com) show and load in HTML with accessing cookies? my settings.py: X_FRAME_OPTIONS = 'ALLOW-FROM ALL' CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' -
CSS isn't loading to style HTML-connected to static in Django
So basically I can't manage to connect .css file to my .html Previously it just wasn't finding the .css file but after I've referenced the full path it stopped giving me the 'not found' error on cmd local host so it does find it it just doesn't load it to change styling <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href=C:\Users\Any1\Desktop\personal_portfolio- project\blog\templates\blog\master.css"> </head> <body> <h1>Example heading</h1> <p>Lori is home blog</p> </body> </html> #my just trying to change h1 color to red for testing h1 { color: #FF0000; } #and my settings.py STATIC_URL = '/static/' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' -
django Storing string instead of dictionary object in (djongo)mongodb table while using jsonfield to store dynamic dict data
I am getting payload which included key like { "id": UUID, "phone_number": "+141 98324 2434", "organization": "xyz", "property":{ "name": "abc", "email": "xyz", "address": { "street": "6th St", "city": "San Francisco", "state": "CA", "postalCode": "94103", "country": "USA" }, "age":14, } } my model looks like this: from jsonfield import JSONField organization = models.ForeignKey(Organization, on_delete=models.DO_NOTHING) phone_number = models.CharField(max_length=16, unique=True, db_index=True) tags = models.TextField(blank=True, null=True) property = JSONField(default={}, blank=True, null=True) Now while storing property(its dynamic) in my djongo DB, i want it to save as object(dict) data type so that later i can query using customer.object.filter(property__age=14). Right now its getting stored as string hence i m not able to query my property field. here is some what is looks like in mongodb. id: UUID phone_numer: "xyz" organization: "xyz" property:"{"name":"abc","age":14}" How should i store property as object in mongodb? -
How do i group by month with other annotated fields?
I have a model like this: class Diary(models.Model): name = models.CharField() gender = models.CharField() date = models.DateField() happy = models.BooleanField() and in the views, i want to group the Diary by month. and i also want to annotate the diary by feelings, so if happy=False, i want to return it as Sad, if happy=True then i want to return Happy. but if there both happy=False and happy=True in the queryset after i group by date, i want to return the feelings as Sad. i tried to annotate like this: queryset = Diary.objects.all() queryset = queryset.values('date') queryset = queryset.annotate(feelings=Case(When(happy=True, then=Value(""))), default=Value("Sad")) but in the same month, if i have both Sad and Happy feelings, i get two rows like this: { "date": "2020-08-20", "feelings": "Happy" }, { "date": "2020-08-20", "feelings": "Sad" } is there a way to group it by month and annotate the feelings as Sad if there is at least one queryset that have happy=False? sorry i'm rather new to Django, thanks in advance! -
How to remove unactivated reservation in Django?
I am creating a web app where people can book a football court, the user select the day and the hour, and insert his email and phone number to book the football court. I don't ask for a sign up, but the user receive an email with an "activation" link to confirm the reservation. I would write a method or something that every X minutes check for the unactive reservations and delete them if the time has expired. How can I do it in Django? -
How to build a multi step form in Django within a unique view passing data between steps?
I need a multi step form in Django for whom next step make use of some previous step fields data. Also hitting "previous" button need to bring back form data enterred in previous step by user. Current implementation is made of a unique view with a counter (named "step") grabbed from URL, 3 forms and HTML templates (one per visual step). I came with the following code so far but steps after first one don't render properly. 1 ) First step (edition) Show all editable fields to user 2 ) Second step (verification) Let user verify some fields (2 of 3), showing them as read only. Previous button will let user edit form data in previous step 3 ) Third step (verification & edition) Let user verify other field (1 of 3) and uncheck some values if needed. Previous button will let user verify other fields 3 ) Fourth step (no user interaction) No visual here, data will be processed in the "backend" urls.py path('multipage_form/<int:step>/', views.multipage_form, name='multipage_form') forms.py # First form step (initial) class Form_0(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['subject'] = forms.CharField(label='Subject',required=True,widget=forms.TextInput(attrs={ 'class': 'form-control' })) self.fields['message'] = forms.CharField(label='Message',required=False,widget=forms.Textarea(attrs={ 'class': 'form-control' })) self.fields['recipients'] = forms.ModelMultipleChoiceField(queryset=Contacts.objects.none(),required=True,widget=forms.SelectMultiple(attrs={ 'class': 'form-control' })) def … -
Unable to connect with Postgresql in apache2
This is the error I'm getting when I try to run my django application on localhost: File "/home/hussam7102/JobPortal/venv/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Then I checked the log file and it shows "Permission Denied" errors: 2020-08-26 06:54:16.573 UTC [28369] LOG: received smart shutdown request 2020-08-26 06:54:16.579 UTC [28369] LOG: worker process: logical replication launcher (PID 28385) exited with exit code 1 2020-08-26 06:54:16.579 UTC [28380] LOG: shutting down 2020-08-26 06:54:16.587 UTC [28369] LOG: database system is shut down pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission … -
ModelForm Editfield without own html template
I want to create a ModelForm to update a certain Modelfield, but I do not need a new template for this, I want it to be integrated into an already existing template with other functionality. How can I do this? All documentation & tutorials I found show how to do something like this and then render a new template in a views method. Any help is appreciated! -
My Webpage has different views in same browser but another computer with same inches
Hello I just deployed my Django project and everthing is fine but after I opened my webpage with my second computer I sav that the webpage has another look. I just thought it is because my second computer is old but my friend has the same ugly look. I just wondered why this happened because we both used chrome and our computers are 16 inch. So it should be the same. The main reason why I am asking because on the ugly view the fonts are so big that a part of my jumbotron does not fit in the webpage so I cannot read it. Also my footer at the bottom and navbar on the top are real big. I will post my html and the pictures so you can understan what I am saying Thank you very much. Note: For the homepage I have a base.html with the navbar and a homepage.html base.html <!DOCTYPE html> {% load static %} {% load crispy_forms_tags %} <html lang="en" dir="ltr"> <head> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css2?family=Architects+Daughter&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> <meta charset="utf-8"> <title></title> </head> <body style="background-color:#FF9900;;"> <nav … -
How to set up a scheduler and background task with Django and Heroku?
I'm following the guides found here: https://devcenter.heroku.com/articles/clock-processes-python and https://devcenter.heroku.com/articles/python-rq What I'm trying to build is a function to send out emails every X days. Essentially, I need to create a clock process and then set up a scheduler to perform the clock process, but not sure how that works in practice. From the first link, the clock process looks like this: from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() @sched.scheduled_job('cron', day_of_week='mon-fri', hour=17) def scheduled_job(): print('This job is run every weekday at 5pm.') sched.start() Where in the background task part (https://devcenter.heroku.com/articles/python-rq) should the scheduled_job function be called? I got these two loose docs but not sure how to tie them together -
Django 3.0.8 Test Cases Failing
This is my first time posting here, so I apologize if I make a mistake when asking my question or include too much detail. I'm quite new to Django, and I'm trying to follow a Simple is Better than Complex tutorial. Specifically, I just completed Part 4. I encounter the following 4 failures when I run tests: $ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). .............................FFF.F.................................. ====================================================================== FAIL: test_contains_form (accounts.tests.test_view_password_reset.PasswordResetTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\admin\Desktop\Development\Django\myproject\myproject\accounts\tests\tes t_view_password_reset.py", line 30, in test_contains_form self.assertIsInstance(form, PasswordResetForm) AssertionError: None is not an instance of <class 'django.contrib.auth.forms.PasswordRes etForm'> ====================================================================== FAIL: test_csrf (accounts.tests.test_view_password_reset.PasswordResetTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\admin\Desktop\Development\Django\myproject\myproject\accounts\tests\tes t_view_password_reset.py", line 26, in test_csrf self.assertContains(self.response, 'csrfmiddlewaretoken') File "C:\Users\admin\Desktop\Development\Django\myproject\venv\lib\site-packages\djang o\test\testcases.py", line 454, in assertContains self.assertTrue(real_count != 0, msg_prefix + "Couldn't find %s in response" % text_ repr) AssertionError: False is not true : Couldn't find 'csrfmiddlewaretoken' in response ====================================================================== FAIL: test_form_inputs (accounts.tests.test_view_password_reset.PasswordResetTests) The view must contain two inputs: csrf and email ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\admin\Desktop\Development\Django\myproject\myproject\accounts\tests\tes t_view_password_reset.py", line 36, in test_form_inputs self.assertContains(self.response, '<input', 2) File "C:\Users\admin\Desktop\Development\Django\myproject\venv\lib\site-packages\djang o\test\testcases.py", line 449, in assertContains self.assertEqual( AssertionError: 0 != 2 : Found 0 instances of … -
How to write a test for a custom action on a viewset in Django Rest Framework
I am new to Django, and Django Rest Framework. I would like to know how to go about testing custom actions. For example, assume we have the following code from the DRF tutorials class UserViewSet(viewsets.ModelViewSet): """ A viewset that provides the standard actions """ queryset = User.objects.all() serializer_class = UserSerializer @action(detail=True, methods=['post', 'put']) def set_password(self, request, pk=None): user = self.get_object() serializer = PasswordSerializer(data=request.data) if serializer.is_valid(): user.set_password(serializer.data['password']) user.save() return Response({'status': 'password set'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) How would I go about calling this view in a test in DRF. def test_password_set(self): user = User.objects.create(name="Joe") factory = APIRequestFactory() request_url = f'users/{user.id}/set_password/' request = factory.post(request_url) view = UserViewSet.as_view({'put': 'update'}) response = view(request) self.assertEqual(response.status_code, 200) That code gives me the error below AssertionError: 405 != 200 which means that the given method is not allowed. Could anyone help me figure out what the error could be? -
Dynamic file upload with datetime folder structure
New to Django. I want to upload my files to /uploads/YYYY/MM/DD folder. What I try is as follows, a function to generate default value of the folder; and in the file field, I try to set that value to upload_to parameter. Makemigrations works fine, when I run: python3 manage.py migrate The mistake I get is as follows. The method has those arguments? image_upload_folder() missing 2 required positional arguments: 'instance' and 'filename' Here's my code: # generates folder name depending on the date: def create_image_upload_folder(): now = datetime.datetime.now() image_date_folder = now.strftime("%Y/%m/%d") return image_date_folder def image_upload_folder(instance, filename): ROOT_DIR = os.path.dirname(os.path.abspath(__name__)) return ROOT_DIR + '/uploads/' + instance.folder class FileSystem(models.Model): folder = models.CharField(max_length=255, blank=False, null=False, default=create_image_upload_folder) file = models.FileField(blank=False, null=False, upload_to=image_upload_folder) ... -
Django Rest Framework Throttle doesn't work instantly on production
I have an issue with throttling user requests to a certain endpoint. I set the limit for them to make only one request/hour and it works okay locally. However on production, the request may take a bit to return a response and in that case, if the users make any new requests during the processing time, it will pass, until the first request returns a response. Any help or pointers?