Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Python LoadData: Error Problem Installing Fixture
First i have migrate and makemigrations and then I have dump data with this command : python manage.py dumpdata --exclude auth.permission --exclude contenttypes > dvvv.json and i have tried to flush database and when i put python manage.py loaddata dvvv.json it says this: pymysql.err.ProgrammingError: (1146, "Table 'webcnytc_prilert_tool.Prilert_confirmationemail' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 78, in handle self.loaddata(fixture_labels) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 123, in loaddata self.load_label(fixture_label) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 190, in load_label obj.save(using=self.using) File "/root/Django/my_env/lib/python3.7/site-packages/django/core/serializers/base.py", line 223, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/base.py", line 778, in save_base force_update, using, update_fields, File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/base.py", line 859, in _save_table forced_update) File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/base.py", line 912, in _do_update return filtered._update(values) > 0 File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/query.py", line 802, in _update return query.get_compiler(self.db).execute_sql(CURSOR) File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1559, in execute_sql cursor = super().execute_sql(result_type) File "/root/Django/my_env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "/root/Django/my_env/lib/python3.7/site-packages/django/db/backends/utils.py", line 66, in execute return … -
DRF Add annotated field to nested serializer
I have two serializers that represent comments and their nested comments. I'm provide a queryset to viewset with annotated field likes. But my problem is that field only working in parent serializer. When i add this field to nested serializer i got error Got AttributeError when attempting to get a value for field likes on serializer CommentChildrenSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Comment instance. Original exception text was: 'Comment' object has no attribute 'likes'. Here is some my code. Thanks Models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(blank=True) body = models.TextField() tags = TaggableManager(blank=True) pub_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-pub_date'] class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) text = models.TextField(max_length=500) pub_date = models.DateTimeField(auto_now=True) parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE, related_name='children') class Meta: ordering = ['-pub_date'] class Vote(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name='votes') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) choice = models.BooleanField(null=True) Serializers.py class PostRetrieveSerializer(PostSerializer): comments = CommentSerializer(read_only=True, many=True) author = AuthorInfoSerializer(serializers.ModelSerializer) class Meta: model = Post fields = ['id', 'author', 'slug', 'title', 'body', 'tags', 'pub_date', 'comments'] class CommentChildrenSerializer(serializers.ModelSerializer): author = AuthorInfoSerializer(read_only=True) likes = serializers.IntegerField() class Meta: model = Comment fields … -
Saas cannot find stylesheet to import. Django project
I am trying to use bootstrap saas in my django project. I installed saas and bootstrap via npm sucessfully however when I try to compile my sass/scass to css I get an error below. I think i am somehow getting file directories incorrect project structure Error -
django.db.utils.IntegrityError: UNIQUE constraint failed: new__product_product.brand_id
I am preparing an ecommerce project in Django. Now I'm trying to change some things When I run the python manage.py makemigrations and python manage.py migrate commands, I get an error that I can't understand. error django.db.utils.IntegrityError: UNIQUE constraint failed: new__product_product.brand_id models.py class Brand(models.Model): name = models.CharField(max_length=10) image = models.ImageField(upload_to='brand') slug = models.SlugField(max_length=15, unique=True) date = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return self.name class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) main_image = models.ImageField(upload_to='product_images/%Y/%m/%d/') detail = models.TextField() keywords = models.CharField(max_length=50) description = models.CharField(max_length=1000) price = models.FloatField() #brand = models.CharField(max_length=50, default='Markon', verbose_name='Brand (Default: Markon)') brand = models.ForeignKey(Brand, on_delete=models.DO_NOTHING, default='Markon') sale = models.IntegerField(blank=True, null=True, verbose_name="Sale (%)") bestseller = models.BooleanField(default=False) amount = models.IntegerField(blank=True, null=True) available = models.BooleanField(default=True) stock = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) used = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) -
What authentication actually does? [closed]
Let's say I'm building a web application and I can choose between 2 different ways of authenticating users. Outcome is same(same record in database, same user experience), but when I look how both ways are written I can see plenty of differences. I would want to know what could be differences between the 2 ways and should I choose more or less complicated. -
Is there a way to save a Django object and update other objects without a recursion loop?
I have a Django model: class Event(models.Model): fk = models.ForeignKey(Foreign, null=True, on_delete=models.SET_NULL) display = display = models.BooleanField(default=True) ... I'd like to override the save method to turn off display for other events that share the fk value. However, I keep reaching infinite recursion loops because if I override the save method and then save the other objects, it keeps calling the function. Is there a way to only run the save method on the first object that's saved and not keep creating recursive instances? -
Validator errors
I'm running my code through validator and it's coming back with four errors which I don't know how to fix as the code has been imported from django forms. Does anyone know how to fix these? <div class="form-group"> <form method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="0AxrgENq77DUAfiu7a1XIsQ2gveB9bBBO96oqSIrlW5OQxoV8EMCrmIIbAn31wa4"> <p><label for="id_username">Username:</label> <input type="text" name="username" maxlength="150" autofocus class="form-control" required id="id_username"> <span class="helptext">Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</span></p> <p><label for="id_first_name">First name:</label> <input type="text" name="first_name" class="form-control" maxlength="100" required id="id_first_name"></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" class="form-control" maxlength="100" required id="id_last_name"></p> <p><label for="id_email">Email:</label> <input type="email" name="email" required id="id_email"></p> <p><label for="id_password1">Password:</label> <input type="password" name="password1" autocomplete="new-password" class="form-control" required id="id_password1"> <span class="helptext"> <ul> <li>Your password can’t be too similar to your other personal information.</li> <li>Your password must contain at least 8 characters.</li> <li>Your password can’t be a commonly used password.</li> <li>Your password can’t be entirely numeric.</li> </ul> </span></p> <p><label for="id_password2">Password confirmation:</label> <input type="password" name="password2" autocomplete="new-password" class="form-control" required id="id_password2"> <span class="helptext">Enter the same password as before, for verification.</span></p> <div class="d-grid"> <button class="btn btn-dark ">Register</button> </div> </form> </div> -
Is my DRF create function losing data before saving?
I have the following DRF viewset: class RecordViewSet(ModelViewSet): queryset = Record.objects.all() serializer_class = RecordSerializer filterset_fields = ['task', 'workday'] def get_workday(self, request): date = get_date_from_calendar_string(request.data['date']) obj, _ = Workday.objects.get_or_create(user=request.user, date=date) return obj.id def create(self, request): request.data['workday'] = self.get_workday(request) print(request.data) return super().create(request) The create() method is failing on a not-null constraint: django.db.utils.IntegrityError: null value in column "task_id" violates not-null constraint DETAIL: Failing row contains (159, Added via task panel., 0, 0, 0, null, t, f, null, 98). However, the print statement in create() shows that the data present in the submission: {'minutes_planned': 5, 'description': 'Added via task panel.', 'minutes_worked': 5, 'task': 148, 'workday': 98} I am not seeing the pk for task (148) in the error statement for some reason, indicating to me that it is getting dropped somewhere. I am not using any signals, or overriding save() in the model. What else could be causing this problem? I've just started using DRF, so it might be something obvious. ===== This is the model: class Record(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='records') workday = models.ForeignKey(Workday, on_delete=models.CASCADE, related_name='records') description = models.CharField(max_length=128, blank=True, null=True) minutes_planned = models.IntegerField(default=0) minutes_worked = models.IntegerField(default=0) minutes_worked_store = models.IntegerField(default=0) user_generated = models.BooleanField(default=True) completed = models.BooleanField(default=False) and the serializer: class RecordSerializer(serializers.ModelSerializer): task … -
error django.db.utils.IntegrityError: NOT NULL constraint failed
I am really stuck here. I went back and edited some models that I made a while ago and now I can't get anything to migrate without getting "django.db.utils.IntegrityError: NOT NULL constraint failed: new__accounts_instrument.room_id" The model that seems to be causing problems: ...\acounts\models.py class Instrument(models.Model): LEVEL = ( ('HS', 'HS'), ('MS', 'MS'), ) event = models.ForeignKey(Event, blank=False, null=True, on_delete=models.PROTECT) name = models.CharField(max_length=200, blank=False, null=True) abbreviation = models.CharField(max_length=10, blank=False, null=True) level = models.CharField(max_length=200, blank=False, null=True, choices=LEVEL) room = models.ForeignKey(AuditionRoom, default=None, on_delete=models.PROTECT) I've tried deleting the migration history but that throws other codes so I "undo" it. I've tried dropping the instrument table but that didn't seem to matter. I'm very grateful for any pointers as I am pretty frustrated at the moment. Please let me know if you need more code snippets... THANK YOU -
Reference a django variable in html to perform a function
I am trying to to output a function on the string that a user selects in a dropdown form. I have a custom template tag that works when you feed it the right variable, but am not sure how to pass on the selected item to it. <select> {% for drink in drinks %} <option id="dropdown" value="{{drink.drink_name}}">{{drink.drink_name}}</option> {% endfor %} </select> <li>{{drink.drink_name|drink_joins}}</li> I know the list gives me an error because drink.drinkname is out of the loop but this is the logic I'm going for. Also fetching the selected value with JavaScript (document.getElementById("dropdown").value) only gives me the first item from the dropdown so that is a problem too. Any remedies? -
Django container is rejecting nginx containers traffic
I have a pretty simple setup, a single django container in a pod and an nginx container in another pod. I'm using nginx because I want to move the django app into production and I need an actual web server like nginx to put an ssl cert on the site. The problem is that it seems like django is rejecting all of the traffic from the nginx container as the web browser gets 502 bad gateway error when browsing to localhost and the nginx logs show: *3 recv() failed (104: Connection reset by peer) while reading response header from upstream I already have 127.0.0.1 and localhost added to the allowed hosts in django settings. Below is the kubernetes file with the nginx config that I'm loading through a config map. I've tried about 30 different nginx.conf configurations, this is just the most recent and simplest one. apiVersion: v1 kind: Service metadata: name: my-nginx-svc labels: app: nginx spec: type: LoadBalancer ports: - port: 80 selector: app: nginx --- apiVersion: apps/v1 kind: Deployment metadata: name: my-nginx labels: app: nginx spec: replicas: 1 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:latest ports: - containerPort: 80 … -
How to get difference between two annotate fields in django orm
The problem is that with this approach, annotate ignores equal amounts, and if you remove distinct=True, then there will be duplicate objects and the difference will not be correct. In simple words, I want to get the balance of the account by getting the difference between the amount in cash and the amount on receipts for this personal account queryset = PersonalAccount.objects.select_related( 'apartment', 'apartment__house', 'apartment__section', 'apartment__owner', ).annotate( balance= Greatest(Sum('cash_account__sum', filter=Q(cash_account__status=True), distinct=True), Decimal(0)) - Greatest(Sum('receipt_account__sum', filter=Q(receipt_account__status=True), distinct=True), Decimal(0)) ).order_by('-id') class PersonalAccount(models.Model): objects = None class AccountStatus(models.TextChoices): ACTIVE = 'active', _("Активен") INACTIVE = 'inactive', _("Неактивен") number = models.CharField(max_length=11, unique=True) status = models.CharField(max_length=8, choices=AccountStatus.choices, default=AccountStatus.ACTIVE) apartment = models.OneToOneField('Apartment', null=True, blank=True, on_delete=models.SET_NULL, related_name='account_apartment') class CashBox(models.Model): objects = None number = models.CharField(max_length=64, unique=True) date = models.DateField(default=datetime.date.today) status = models.BooleanField(default=True) type = models.BooleanField(default=True) sum = models.DecimalField(max_digits=10, decimal_places=2) comment = models.TextField(blank=True) payment_items = models.ForeignKey('PaymentItems', blank=True, null=True, on_delete=models.SET_NULL) owner = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, related_name='owner') manager = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='manager') personal_account = models.ForeignKey('PersonalAccount', blank=True, null=True, on_delete=models.SET_NULL, related_name='cash_account') receipt = models.ForeignKey('Receipt', blank=True, null=True, on_delete=models.SET_NULL) class Receipt(models.Model): objects = None class PayStatus(models.TextChoices): PAID = 'paid', _("Оплачена") PARTIALLY_PAID = 'partially_paid', _("Частично оплачена") NOT_PAID = 'not_paid', _("Не оплачена") number = models.CharField(max_length=64, unique=True) date = models.DateField(default=datetime.date.today) date_start = models.DateField(default=datetime.date.today) date_end = models.DateField(default=datetime.date.today) … -
Posting Date Data to Django Model
I was wondering if any of you guys here knew how to fix this error, I have been dealing with it for quite a few hours, it has to do with posting json date (a date from a html date picker) to a backend model using the django web framework. Please let me know if my question is unclear. ViewOrders.html <form id="form"> <label for="start">Drop Off Date Selector:</label> <br> <input type="date" id="dropOffDate" name="drop_Off_Date" min="2022-01-01" max="3000-12-31"> <button type="submit" value="Continue" class="btn btn-outline-danger" id="submit-drop-off-date" >Submit Drop Off Date</button> </form> <script type="text/javascript"> var form = document.getElementById('form') form.addEventListener('submit', function(e){ e.preventDefault() submitDropOffData() console.log("Drop Off Date submitted...") }) function submitDropOffData() { var dropOffDateInformation = { 'dropOffDate':null, } dropOffDateInformation.dropOffDate = form.drop_Off_Date.value var url = "/process_drop_off_date/" fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'drop-off-date':dropOffDateInformation}), }) .then((response) => response.json()) .then((data) => { console.log('Drop off date has been submitted...') alert('Drop off date submitted'); window.location.href = "{% url 'home' %}" }) } </script> Views.py def processDropOffDate(request): data = json.loads(request.body) DropOffDate.objects.create( DropOffDate=data['drop-off-date']['dropOffDate'], ) return JsonResponse('Drop off date submitted...', safe=False) Models.py class DropOffDate(models.Model): dropOffDate = models.CharField(max_length=150, null=True) def __str__(self): return str(self.dropOffDate) Errors -
A good way to authenticate a javascript frontend in django-rest-framework
What's an excellent method to implement token-based httpOnly cookie authentication for my drf API for a javascript frontend I looked into django-rest-knox for token-based authentication but its built-in LoginView required the user to be logged in already. Why is that?. I want a good method to authenticate the user from the javascript frontend. Thanks! -
How to migrate from sqlite to postgres using a local sqlite database in Django?
I have a 'xxxxx.db' sqlite3 database and I want to move the data to PostgreSQL. I have done some research and seen a couple of options but none of them worked (PGloader etc.). What are some other options? I am using Windows but solutions in Linux are welcome as well. I have tried doing it in PowerShell(via Jupyter Notebook): !pip install virtualenvwrapper-win !mkvirtualenv [name] !pip install django !django-admin startproject [name] cd [name] !python manage.py startapp app !python manage.py inspectdb !python manage.py inspectdb > models.py !python manage.py migrate !manage.py runserver !python manage.py dumpdata > data.json But the dump does not include the data from my db, I have also changed the settings to DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': absolute_path_to_db/db, } } Thanks in advance! -
How to make a drf endpoint that returns model fields with description and choices?
There are rest api endpoints being built for questionnaires, that accept only POST requests. The frontend should dynamically display the questionnaires based on their model fields, their descriptions, and possible choices. How to make such django rest framework endpoint, which returns model fields, their description and choices as json? It cannot be a hard coded json so when a model field description changes, it is reflected in the API response. -
Django Python besides uploading text, i would like to be able to upload image and videos
I work on a Social Media Website. I get the Base code from an Open Source Project on GitHub. On my Website you can only upload Text, and link some images, but these are not very user friendly. I would love to be able to upload images and videos besides the Text. When I watch Tutorials on YouTube, it's always very hard to implement that code to mine. Is there a way that someone could help me? The code of post_form.html, post_detail.html, forms.py, views.py, models.py, urls.py, admin.py, settings.py are under this text: post_form.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block title %}Post{% endblock %} {% block content %} <div class="m-auto w-100 container"> <div class="content-section"> <form action="" method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New Post</legend> {{form.media}} {{form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-info" type="submit">Post</button> <a class="btn btn-danger" href="{% url 'blog-home' %}">Cancel</a> </div> </form> </div> </div> <!-- Modal --> <div class="modal fade" id="modalCrop" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Crop the photo</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" style="max-width: 100%; overflow:auto"> <img style="max-height:100%; max-width: 100%" src="" id="image"> </div> <div class="modal-footer"> <div class="float-left"> <button type="button" class="btn btn-primary … -
Input abc.png of type: <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> is not supported
Unable to save image two times in django Im trying to save image through form in one model and add in another model. But at new_account.save() I get the above error. image_file = request.FILES.get('profile_image') ... ... instance.save() new_account = Account.objects.get(id=classroom_profile.user.id) new_account.profile_image.delete() new_account.profile_image = image_file new_account.save() -
`TransactionManagementError` when callinfg another model save function inside my custom save method for a model
While performing a save operation from the admin site the model when saving is raising a TransactionManagementError, The model has a custom save method in which there is another save function called for another model so just put it with the transaction.atomic(): solves the issue but atomic might affect performance or cause deadlock due to lock. Is there any other way I can override the admin save or only do this when the save call is coming from admin? -
What could be causing "connection refused" error when uploading file via form (post request) to Django app deployed on Heroku?
I have this working on google cloud but recently deployed my django app to Heroku. Everything is working fine except file upload here is debug log. I tried heroku run ls -l to create a files directory and confirmed /files directory it exists on server but I'm not sure why I get connection refused. Debug log is below it should just upload file submitted to /files directory so I'm not sure why it's refusing connection. OperationalError at /upload/ [Errno 111] Connection refused Request Method: POST Request URL: <redacted> Django Version: 4.0.5 Exception Type: OperationalError Exception Value: [Errno 111] Connection refused Exception Location: /app/.heroku/python/lib/python3.10/site-packages/kombu/connection.py, line 450, in _reraise_as_library_errors Python Executable: /app/.heroku/python/bin/python Python Version: 3.10.5 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python310.zip', '/app/.heroku/python/lib/python3.10', '/app/.heroku/python/lib/python3.10/lib-dynload', '/app/.heroku/python/lib/python3.10/site-packages'] Server time: Mon, 11 Jul 2022 17:37:37 +0000 Traceback Switch to copy-and-paste view /app/.heroku/python/lib/python3.10/site-packages/kombu/utils/functional.py, line 30, in __call__ return self.__value__ … Local vars During handling of the above exception ('ChannelPromise' object has no attribute '__value__'), another exception occurred: /app/.heroku/python/lib/python3.10/site-packages/kombu/connection.py, line 446, in _reraise_as_library_errors yield … Local vars /app/.heroku/python/lib/python3.10/site-packages/kombu/connection.py, line 433, in _ensure_connection return retry_over_time( … Local vars /app/.heroku/python/lib/python3.10/site-packages/kombu/utils/functional.py, line 312, in retry_over_time return fun(*args, **kwargs) … Local vars /app/.heroku/python/lib/python3.10/site-packages/kombu/connection.py, line 877, in _connection_factory self._connection = self._establish_connection() … Local … -
Django with ngrok. CSRF verification failed. Request aborted. Origin checking failed
I have a simple django project with user login/register capabilities that I wanted to view on mobile, the only way I know how to do this besides actually deploying the website is to use ngrok. So I ran ngrok http 8000 and added ALLOWED_HOSTS = ['*'] to my settings.py file. Went over to the url provided by ngrok, tried to login as one of the users I had created while running the project on localhost and upon submitting the form got the following error: CSRF verification failed. Request aborted. Origin checking failed - https://myurl.ngrok.io does not match any trusted origins. Not really sure what to do here, does django user auth not work with ngrok or do I just have to add something to my settings file to make this a 'trusted origin'? Thanks for any help. -
Retrieving Date Value and Assigning Date to Django Backend
I am trying to figure out a way to assign a date that I retrieve from the standard html date picker and then assign it to a backend model after a button of type 'submit' is clicked. I wrote some javascript but the value keeps being retrieved as NULL. I am relatively new to javascript so please bare with me. Attached are all the files that I have been working on, along with screenshots of the error. Please let me know if there is anything else you may need from me to help me with my question! vieworders.html <div class="row mb-4"> <label for="start">Drop Off Date Selector:</label> <br> <input type="date" id="dropOffDate" min="2022-01-01" max="3000-12-31"> <button type="submit" value="Continue" class="btn btn-outline-danger" id="submit-drop-off-date">Submit Drop Off Date</button> </div> <script type="text/javascript"> var date = document.getElementById("date"); date.addEventListener('submit', function(e){ e.preventDefault() submitDropOffData() console.log("Drop off data submitted...") }) function submitDropOffData() { var dropOffDateInformation = { 'dropOffDate':null, } dropoffDate.date = date.value var url = "/process_drop_off_date/" fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'dropoffDate':dropOffDateInformation}), }) .then((response) => response.json()) .then((data) => { console.log('Drop off date has been submitted...') alert('Drop off date submitted'); window.location.href = "{% url 'home' %}" }) } </script> views.py def processDropOffDate(request): data = json.loads(request.body) DropOffDate.objects.create( DropOffDate=data['dropoffDate']['date'], ) return JsonResponse('Drop off date … -
DRF multiple ManyToOne relations serializer
sorry my english is not good. Get request book_id(pk) How to I serialize ManyToOne fields using BookSerializer to retrieve something class Book(TimeStampedModel): name = models.CharField(max_length=25, null=False) owner = models.ForeignKey(User, on_delete=models.DO_NOTHING,unique=True) ... class Meta: db_table = 'books' class BookMember(TimeStampedModel): user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=False) book = models.ForeignKey(Book, on_delete=models.CASCADE, null=False) class Meta: db_table = 'book_member' class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=20, unique=True) email = models.EmailField(verbose_name=_('email')) ... class Meta: db_table = 'user' class BookSerializer(serializers.ModelSerializer): user = UserDetailSerializer(read_only=True, many=True, required=False) owner = UserDetailSerializer(read_only=True, many=True, required=False) class Meta: model = Book fields = '__all__' I need to book retrieve class BookViewSet(ModelViewSet): permission_classes = [AllowAny] queryset = Book.objects.all() serializer_class = BookSerializer renderer_classes = [JSONRenderer] def retrieve(self, request, *args, **kwargs): instance = get_object_or_404(self.queryset, many=True) serializer = self.get_serializer(instance) return serializer.data -
pytest: how to mock database query at module
I have a module with different functions inside and several global variables defined at the beginning of the module. module.py MIN_PLACE = 7 START_DAY = 4 func1(): pass func2(): pass func3(): pass .... tests.py @pytest.mark.django_db test_func1(): #logic ..... Tests have been written for this module (several dozen) and everything works. But I needed to make the variables dynamic, with the ability to change them from the django admin panel and store them in the database. MIN_PLACE: int = int(RedshiftQueryParam.objects.get(name=RedshiftQuery.MIN_PLACE).value) START_DAY: int = int(RedshiftQueryParam.objects.get(name=RedshiftQuery.START_DATE).value) And after that, all the tests fell down with an error message E RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. In order to use the database reference to test the function, the decorator @pytest.mark.django_db is used But what about when a call to the database occurs in the body of a module rather than in a specific function? Every time the pytest context enters the module, it tries to connect to the database. How can I fix this? Can this be done globally in one place so as not to have to fix all the test files ? -
Can I use redirect or render as a way to "refresh" the current web page I'm on in django?
I'm wondering if I can use the redirect()/render() function and point to the default page (http://127.0.0.1:8000) as a way to essentially refresh the page I'm on. I feel like it'd work but I'm not sure what to put in the parameters of the function, I've seen people say redirect("/path/") but that gives me an error the second I click my submission button. as well as if I need to change anything elsewhere within the framework. I also know you can return multiple items in python, but can I return the original item as well as a call to redirect()/render()? Here is my views.py file: from django.shortcuts import render from django.shortcuts import redirect from django.urls import reverse from django.views.generic.edit import FormView from django.views.decorators.csrf import csrf_exempt from .forms import FileFieldForm from django.http import HttpResponse from .perform_conversion import FileConverter import zipfile import io def FileFieldFormView(request, *args, **kwargs): form = FileFieldForm(request.POST) files = request.FILES.getlist('file_field') if request.method == 'POST': print(request) form = FileFieldForm(request.POST, request.FILES) if form.is_valid(): zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, "w", False) as zip_file: for f in files: fileconverter = FileConverter(f.name) fileconverter.run(f.file) for img_name, img in fileconverter.output.items(): data = io.BytesIO(img) zip_file.writestr(img_name, data.getvalue()) # Set the return value of the HttpResponse response = HttpResponse(zip_buffer.getvalue(), content_type='application/octet-stream') …