Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access a JSON variable via a POST response in Django?
I have JSON data is coming in via POST. The data I am sending is via JavaScript const items = [{ id: "T-shirt" }]; async function initialize() { const response = await fetch("/getorder/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ items }), }); On the python side in my view, I can access items fine: return HttpResponse(data.get("items")) Which returns {'id': 'T-shirt'} My problem is accessing just the value for the 'id' key so I can assign 'T-shirt' to a variable. So far I have tried tried: Using data.get('items')['id'] which returns: "list indices must be integers or slices, not str" Using data.get('items')[id]` returns: list indices must be integers or slices, not builtin_function_or_method Using data.get('items')[0] returns 'id', but I still can't access the matching item. Using data.get('items')[1] returns list index out of range Using data.get('items')[0[0]] returns type int not subscriptable Using data.get('items')[0]['id'] returns just 'id' How can I just access 'id' to assign the value 'T-shirt' to a variable? -
Unclear how to set __package__ variable
I have a Django project that I've been working on for a while. I came to the point where I wanted to load a significant amount of data into my Postgres database. I set aside a new Django project with sqlite3 just to work out the code and run some tests to make sure everything was inserted properly. Everything seemed fine until I got to the point where I actually wanted to test the insert script. ImportError: attempted relative import with no known parent package The error refers to this line in the script: from .models import Statute As of right now, this has no red squiggly line on it. models.py and this script are right beside each other in the same directory: $ tree └── parsecodetree ├── db.sqlite3 ├── manage.py ├── parsecodetree │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── ustitles ├── admin.py ├── apps.py ├── __init__.py ├── insert504.py ├── insert_script_results ├── migrations ├── models.py ├── t10p1b.html ├── tests.py └── views.py I found this trick in an old David Beazely video: parsecodetree/ustitles/__init__.py: from .models import * print("This is ustitles.__init__") “This is ustitles.__init__” does not print. Commenting or uncommenting ‘from .models import … -
Django Auto Increment
I want input data to DB by using html form. I try two method. First, I create Django form -> Working all case, But Difficult to styling UI. Second, I create HTML form -> working unless my DB ID is Auto Increment. Is there other method for input data to DB by using html form. Thank -
Django not rendering static image files localted in MEDIA directory
im relatively new to Django. I have an app where I specify MEDIA_URL and MEDIDA_ROOT in settings.py file in project root. My paired down project srucutre looks like this: / ../files ../files/media ../files/media/logo.png ../solid/settings.py ../solid/urls.py /web/templates (contains all my HTML) inside settings I have MEDIA_ROOT = BASE_DIR / 'files' MEDIA_URL = '/media/' DEFAULT_FILE_STORAGE = BASE_DIR /'files' and files the "media" directory has images subfolder and logo.png in my template (index.html) under web/template directory I'm trying to reference it <img src="{{% MEDIA_ROOT %}}/images/ourlogo.png" class="" alt="Logo" height="40"> In solid/urls.py I have: urlpatterns = [ path('admin/', admin.site.urls), path('',web_views.index,name="index"), ###################################################### path('login/',login_page,name="login"), path('logout/',log_out,name="logot"), path('register/',register,name="register"), ####################################################### path('upload/',web_views.upload,name="upload"), path('list/',web_views.list_uploads,name="list"), path('details/<int:oid>', web_views.view_download,name='view_download'), path('download/<str:filename>', web_views.download_file,name='download_file'), ####################################################### path('paypal/', include("paypal.standard.ipn.urls")), path('payment/',web_views.upgrade,name="payment"), path('paypal-cancel/', PaypalCancelView.as_view(), name='paypal-cancel'), path('paypal-return/', PaypalReturnView.as_view(), name='paypal-return'), ####################################################### ]+static('s/',document_root=settings.MEDIA_ROOT) the image is not rendering. -
Django runserver getting stuck on strptime
In my django project, python manage.py runserver runs extremely slowly. To check where the problem is I run python -v manage.py check. This shows that it's getting stuck on: # C:\Users\mvren\miniconda3\envs\dataenv\lib\__pycache__\_strptime.cpython-39.pyc matches C:\Users\mvren\miniconda3\envs\dataenv\lib\_strptime.py # code object from 'C:\\Users\\mvren\\miniconda3\\envs\\dataenv\\lib\\__pycache__\\_strptime.cpython-39.pyc' import '_strptime' # <_frozen_importlib_external.SourceFileLoader object at 0x000002084418A670> When I delete _strptime.py from my env, it runs smoothly. But then my app doesn't work. Specifically, I get the following traceback: File "C:\Users\mvren\miniconda3\envs\dataenv\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\mvren\miniconda3\envs\dataenv\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\mvren\miniconda3\envs\dataenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\mvren\miniconda3\envs\dataenv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\mvren\miniconda3\envs\dataenv\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\mvren\miniconda3\envs\dataenv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\mvren\miniconda3\envs\dataenv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\mvren\miniconda3\envs\dataenv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\mvren\miniconda3\envs\dataenv\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\mvren\miniconda3\envs\dataenv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\mvren\miniconda3\envs\dataenv\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\mvren\miniconda3\envs\dataenv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\mvren\miniconda3\envs\dataenv\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\mvren\miniconda3\envs\dataenv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import … -
How much information can a django project hold
So, listen, I am building websites and I am using django, imagine I want to make a video sharing website, so for this I use django, I set a limit per video to 50MB, how many videos would be able to be uploaded, where would they be stored, how do I store alot of them (and where) How do I make the database to store the info and how much can be stored in django? -
`django-import-export` update data with followed model relationships like `author__name`
Code below succeed to export user data with department name, succeed to import part of data, but not update department data. I need to extend user model How to fix it to import data? Help, thanks... # pip install django-import-export from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from django.db import models from import_export import fields, resources from import_export.admin import ImportExportModelAdmin from import_export.widgets import ForeignKeyWidget class Department(models.Model): name = models.CharField(max_length=180, blank=True, null=True, ) class User(get_user_model()): class Meta: proxy = True class HseUser(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, blank=True) dept = models.ForeignKey(Department, on_delete=models.CASCADE, blank=True, null=True, ) name = models.CharField(max_length=180, blank=True, null=True, ) class UserResource(resources.ModelResource): name = fields.Field(attribute='hseuser', widget=ForeignKeyWidget(HseUser, 'name')) dept = fields.Field(attribute='hseuser__dept', widget=ForeignKeyWidget(Department, 'name')) class Meta: model = User exclude = ['id'] import_id_fields = ['username', 'name'] fields = ['username', 'dept', 'email', ] class MyUserAdmin(UserAdmin, ImportExportModelAdmin): resource_class = UserResource fieldsets = ( (None, {'fields': ('username', 'password')}), ) admin.site.register(Department) admin.site.register(HseUser) admin.site.register(User, MyUserAdmin) -
im not sure if i implement correctly the cleaning method in django
I'm not sure if I'm implementing the clean and the clean_ methods correctly. In the documentation it says that we should call them, but where? we have to call them because at the moment of trying to go through form.is_valid() the data comes out as not validated and my question would be what I have to do heres my model: class Users(models.Model): USERNAME_FIELD = models.CharField(max_length=90, blank=False, null=False, primary_key=True) LASTNAME_FIELD = models.CharField(max_length=90, null=False, blank=False) USERAGE_FIELD = models.IntegerField(null = True ) USER_IMAGE_FIELD = models.ImageField(null = True, blank = False, upload_to='media/') USERMAIL_FIELD = models.EmailField() USERPSSWD_FIELD = models.CharField(max_length= 100) CONFPSSWD_FIELD = models.CharField(max_length=100) def clean(self): if (len(self.USERNAME_FIELD) = 0): raise ValidationError(_('not empty space')) def __str__(self): return self.USERNAME_FIELD and heres my forms: from django import forms from .models import Users from django.forms import ModelForm from django.utils.translation import gettext_lazy as _ from django.forms import formset_factory from django.core.exceptions import ValidationError class Usersform(ModelForm): class Meta: model = Users fields = '__all__' labels = { 'USERNAME_FIELD': _('Nombre del Usuario:'), 'LASTNAME_FIELD': _('Apellido del Usuario'), 'USERAGE_FIELD': _('Edad del Usuario:'), 'USER_IMAGE_FIELD': _('Foto del Usuario:'), 'USERMAIL_FIELD': _('Email del Usuario:'), 'USERPSSWD_FIELD': _('Contraseña:'), 'CONFPSSWD_FIELD': _('Confirma la Contraseña:'), } def clean_USERAGE_FIELD(self): data = self.cleaned_data['USERAGE_FIELD'] if (data < 18): raise ValidationError('you cant sign up youre to young') return … -
Django - sending email to user even if there offline
I want to send email to a user when their subscription date is due even when Thier offline . Any thoughts or ideas would be much appreciated. Thanks -
Django Time Series with Chart JS
I'm building a Django app that is dynamically feeding data to Chart JS. because I'm trying to join two line series together (historical values and predictions), I'm trying to have Chart JS understand NaN. This is how the code is written: <script> new Chart(document.getElementById("chart"), { type: 'line', data: { labels: {{ new_dates|safe }}, datasets: [ { data: {{ orig_val|safe }}, label: "Historical Sales", borderColor: "#3e95cd", fill: false }, { data: {{ preds|safe }}, label: "Predictions", borderColor: "#22DD66", fill: false } ] }, options: { title: { display: true, text: 'output chart' }, maintainAspectRatio: false, responsive: true, scales: { xAxes: [{ gridLines: { display:false } }], yAxes: [{ gridLines: { display:false } }] }, animation: { duration: 2000, }, } }); </script> This is what the console sees: <script> new Chart(document.getElementById("chart"), { type: 'line', data: { labels: ['2019-01', '2019-02', '2019-03', '2019-04', '2019-05', '2019-06', '2019-07', '2019-08', '2019-09', '2019-10', '2019-11', '2019-12', '2020-01', '2020-02', '2020-03', '2020-04', '2020-05', '2020-06', '2020-07', '2020-08', '2020-09', '2020-10', '2020-11', '2020-12', '2021-01', '2021-02', '2021-03', '2021-04', '2021-05', '2021-06', '2021-07', '2021-08', '2021-09', '2021-10', '2021-11', '2021-12', '2022-01', '2022-02', '2022-03', '2022-04', '2022-05', '2022-06', '2022-07', '2022-08', '2022-09'], datasets: [ { data: [71.0, 67.0, 84.0, 65.0, 78.0, 74.0, 73.0, 88.0, 86.0, 77.0, 94.0, 123.0, 71.0, 77.0, 57.0, … -
Values are not going to the database with signals
I'm using a signal to register a user in the Profile table, every time a User is registered in the Django User. I'm able to get the results of username and email, however, the first and last name are not being assigned. Model Perfil class Perfil(models.Model): username = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, verbose_name="first name", blank=True) last_name = models.CharField(max_length=30, verbose_name="last name", blank=True) email = models.EmailField(max_length=75, verbose_name="email address", blank=True) def __str__(self): return self.username.username Signal new_profile def new_profile(sender, instance, created, **kwargs): user_db = User.objects.filter(username__exact=instance).values().first() if created: Perfil.objects.create( username = instance ) Perfil.objects.filter(username__exact=instance).update( first_name = user_db['first_name'], last_name = user_db['last_name'], email = user_db['email'] ) post_save.connect(new_profile, sender=User) Note: I already tried to create with everything together and my measure of desperation was to try to update after having created. Print of the table without the last_name and the first_name but with the email. -
Django: template to list data from 2 models related each other
I have 2 models. One of them is primary key of the other as in example below. class Product(models.Model): name = models.CharField(max_length=32, unique=True) power = models.IntegerField(default=0) class Price(models.Model): product = models.OneToOneField(Product, on_delete=models.PROTECT, primary_key=True) price = models.IntegerField(default=0) I'd like to build a template that displays the data from the 2 models. For example: List of Products product: P_A power: 1000W price: $ product: P_B power: 1500W price: $ product: P_C power: 2000W price: $ I have made several attempts without being successful in displaying the prices. One of them were the following template and view: <h2>List of Products</h2> <ul> {% for product in list_of_products %} <li>product: {{ product.name }} &emsp; &emsp;power: {{ product.power }}W &emsp; price: {{prices.product.price }} $</li> {% endfor %} </ul> def index(request): products = Product.objects.all() prices = Price.objects.all() return render(request, "index.html", {'list_of_products': products, 'prices': prices}) Thank you for any help in solving my problem. -
How to check in Django template if user has delete permission?
I would like to check if the user has permission to delete an object in the template. If the user has permission, I display or enable the button. Permissions are per group. How can I implement this in the Django template? {% if ... %} <button><a href="/delete">Delete</a></button> {% endif %} -
Select a valid choice. That choice is not one of the available choices. error with Django Form
I've got a comment section html page and whenever I try to fill the fields and click sumbit it gives the following error - Select a valid choice. That choice is not one of the available choices. views.py @login_required(login_url='/accounts/login') def add_comment(request, slug): movie = Movie.objects.get(slug=slug) form = CommentForm(request.POST) if form.is_valid(): form.save() return redirect('movie:movie_list') context = {'form': form} return render(request, 'add_comment.html', context) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('commenter_name', 'comment_body') widgets = { 'commenter_name': forms.TextInput(attrs={'class': 'form-control'}), 'comment_body': forms.Textarea(attrs={'class': 'form-control'}), } models.py class Comment(models.Model): movie = models.ForeignKey(Movie, related_name="comments", on_delete=models.CASCADE) commenter_name = models.ForeignKey(User, default=None, on_delete=models.CASCADE) comment_body = models.TextField() date_added = models.DateTimeField(auto_now=True) def __str__(self): return '%s - %s' % (self.movie.title, self.commenter_name) Please note I am able to add a comment through the /admin panel but once I tried adding an API to it things kinda went wrong. -
error: UNIQUE constraint failed: accounts_user.username
I need to register a new user so wheen I seed data I get this error return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.username model.py: from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager from phonenumber_field.modelfields import PhoneNumberField # custom manager class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) GENDER_CHOICES = ( ('M', "Male"), ('F', "Female"), ('O', "Other"), ) class User(AbstractUser): #username = None email = models.EmailField( verbose_name='email address', max_length=255, unique=True ) date_of_birth = models.DateField(default='1990-01-01') gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True) picture = models.ImageField( upload_to='img/users', null=True, … -
How to validate data in nested ModelSerializer?
class Test(models.Model): name = CharField() a_str = CharField() a_int = IntegerField() b_str = CharField() b_int = IntegerField() class ASerializer(Serializer): str = CharField(source='a_str') int = IntegerField(source='a_int') class BSerializer(Serializer): str = CharField(source='b_str') int = IntegerField(source='b_int') class TestSerializer(ModelSerializer): A = ASerializer(source="*") B = BSerializer(source="*") class Meta: model = Test fields = ('name', 'A', 'B') Having these serializers, I am able to create Test instance, but only 'name' field is being used in create method. Validated data does not contain fields from ASerializer and BSerializer. How do I, for example, map [A][int] to Test.a_int? Or just add a_int (which is initial_data[A][int])to validated_data, so I can use it in create method? This nesting method was taken from: drf-docs -
How would I go about creating a Django + SvelteKit webapp?
I've already gotten my fair share of Bootstrap and Django but never tried out other frontend frameworks like Angular, React, etc. and finally wanted to try SvelteKit. So I'm really inexperienced and new with this sort of stuff. Currently I've already set-up my Django project as well as a SvelteKit project by following the tutorial on their website. My problem is that I'm confused about how to combine Django and SvelteKit now. Do I just run both servers simultaneously on different ports and get the data from Django JSON APIs into my Svelte frontend or is there some kind of approach to this? I thought that maybe there's a way to get my Django app to render the Svelte files from the Svelte server for me. I just feel really lost at the moment so if anyone could help me or has some resources I could read to get more familiar with the topic, since I didn't find a lot online, that'd be great! Many thanks in advance! -
How to create values to foreign key model in DRF serializer?
When sending json to the server, it shows the following error: Direct assignment to the reverse side of a related set is prohibited. Use items.set() instead. Help me please. I recently started to study DRF, and I don't understand how to correctly write def create in django to write data to a foreign key model? Here is my code serializer.py class ConsignmentNoteSerializer(serializers.ModelSerializer): create_user = serializers.HiddenField(default=serializers.CurrentUserDefault()) create_user = UserSerializer(source='creator', read_only=True) contragent_detail = ContragentSerializer(source='contragent', read_only=True) items = ConsignmentItemSerializer(many=True) class Meta: model = ConsignmentNote fields = ['id', 'doc_type', 'date', 'number', 'contragent_detail', 'comment', 'create_user', 'items', 'created'] **def create(self, validated_data): items_data = self.validated_data.pop('items') return ConsignmentNote.objects.create(**validated_data)** Here is the json I am trying to send { "id": 9, "doc_type": "capitalize", "date": "2022-06-04", "number": 98, "contragent_id": 4, "comment": "", "items": [ { "id": 18, "product": 10, "buy_price": "200.00", "sell_price": "500.00", "quantity": 5 }, ], } -
Manager isn't accessible via WatchList instances How do I fix this error?
I am trying to create an e-commerce site (CS50 Project 2) through Django and have a Django view with multiple forms. In this view I am trying to use a Boolean Field in a Django form to enable the user to add a listing to his watchlist, both of which are models. While trying to do that, I am receiving the above error. part of the views.py def listing(request, id): #gets listing listing = Listings.objects.get(id=id) watchlist_form = WatchListForm() if request.method == "POST": watchlist_form = WatchListForm(request.POST) if watchlist_form.is_valid(): watchlist = watchlist_form.save(commit=False) watchlist.user = request.user watchlist.add_to_watchlist = True new_watchlist_listing = watchlist.objects.listings.add(listing) return render(request, "auctions/listing.html",{ "auction_listing": listing, "watchlistForm": watchlist_form }) else: return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": comment_form, "comments": comment_obj, "bidForm": bid_form, "bids": bid_obj, "watchlistForm": watchlist_form }) return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": comment_form, "comments": comment_obj, "bidForm": bid_form, "bids": bid_obj, "watchlistForm": watchlist_form }) models.py class Listings(models.Model): CATEGORY = [ ("Miscellaneous", "Miscellaneous"), ("Movies and Television", "Movies and Television"), ("Sports", "Sports"), ("Arts and Crafts", "Arts and Crafts"), ("Clothing", "Clothing"), ("Books", "Books"), ] title = models.CharField(max_length=64) description = models.CharField(max_length=500) bid = models.DecimalField(max_digits=1000000000000, decimal_places=2) image = models.URLField(null=True, blank=True) category = models.CharField(max_length=64, choices=CATEGORY, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE, default="") class WatchList(models.Model): listings = models.ManyToManyField(Listings) user = models.ForeignKey(User, on_delete=models.CASCADE, … -
How to use load model in TensorFlow with Django quickly
I have a Django API that makes predictions using a TensorFlow model. The first time the model loads it takes Django up to 12 seconds. In production, this is unacceptable. How can I speed up the loading of my TensorFlow model for use in Django? This is how I load Django: from tensorflow.keras.models import load_model model = load_model('test/models/test', compile=False) model.predict(padded) I read that compile=False might speed things up, but it doesn't. My Django app only uses the predict function as the model is simply handed to me and trained elsewhere. Simply importing tensorflow.keras.models is where it takes all the time. -
How to do auto selected country code in django forms to send whatsapp massege?
In django model countries and country code are there. I want to display country code if user select a country , then he can enter his contact number without entering country code. I want to send whats app message for those people. -
One to One vs Many to One
I'm thinking of storing event and event location but I'm wondering about how should I do it. Because many events can be hosted at a single event location. And just to inform we are going to take event location information by a map most probably longitude and latitude (#if possible textual address as well") Now the questions is how should I go about it Shall i store the address in the same table of event Shall i create a event and address table seperately and have a relationship as oneToOne field Or should I keep the event and address table seperately but have the relationship as foreign key (Note in the last method I think it can potentially reduce the amount of data that I need to store but I'm scared that it could bring a lot of complications when dealing with lot of data ) Please if you tell which is better way of doing it please mention why it is better Any help or guidance will help me great deal , Thank you in advance -
Is it possible to create django passwords using php?
I'm trying to use php to create password hashes acceptable by django, i tried using php function "hash_pbkdf2" and then "base64_encode", then making it into django's password format ( algorithm$iterations$salt$hash ). i also used 320000 iterations (same as django) and created a random string for salt. $n=22; function getName($n) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; for ($i = 0; $i < $n; $i++) { $index = rand(0, strlen($characters) - 1); $randomString .= $characters[$index]; } return $randomString; } $pass = "erf1377"; $iterations = 320000; $salt = getName($n); $hash = hash_pbkdf2("sha256", $pass, $salt, $iterations); $hash = base64_encode($hash); $final_hash = "pbkdf2_sha256$".$iterations."$".$salt."$".$hash; echo $final_hash; (getName() creates my salt) but the end result is not accepted by django. what am i doing wrong here? -
how to convert datetime with timezone to time only with python [closed]
For example, I want to convert datetime with timezone to datetime without timezone : 2022-06-05 05:37:21.537071+02:00 to 2022-06-05 07:37:21.537071 2022-06-05 05:37:21.537071+05:00 to 2022-06-05 10:37:21.537071 -
How to solve in Django REST API the serializing of data from 2 models with ForeignKey
I was wondering what the correct way is to serialize data in Django REST API from 2 models connected with ForeignKey. The situation is: i have a 1st table called NewUsers with the user registrations, and a 2nd table called Ticker with data saved from an external API. The goal is: create a 3rd table with parts of the 2 tables interconnected - one part is the user loggedin, and the other part is the selection of one crypto object. This new table will then be displayed via Django REST API serializer. The problem is: this new 3rd table does not display the complete list of values selected by the user. I have gone through the documentation here https://books.agiliq.com/projects/django-admin-cookbook/en/latest/override_save.html and here https://www.django-rest-framework.org/tutorial/1-serialization/ but could not find a complete solution. What am i missing? my views.py from rest_framework import generics from .serializers import WatchlistSerializer from ticker.serializers import TickerSerializer from watchlist.models import SectionWatchlist from ticker.models import Ticker import requests from rest_framework.views import APIView from rest_framework.decorators import api_view from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class CreateSectionWatchlist(generics.CreateAPIView): queryset = SectionWatchlist.objects.all() serializer_class = WatchlistSerializer class ListSectionWatchlist(generics.ListAPIView): queryset = SectionWatchlist.objects.all() serializer_class = WatchlistSerializer def get_queryset(self): queryset = SectionWatchlist.objects.all() author = self.request.query_params.get('author') if author: queryset …