Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering content by category(many to many field) using django
I would like to filter the items on my website using category. I have managed to do filtering by the title, but I am not sure about this one. models.py class Category(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.ManyToManyField(Category) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() views.py def HomeView(request): item_list = Item.objects.all() category_list = Category.objects.all() query = request.GET.get('q') if query: item_list = Item.objects.filter(title__icontains=query) paginator = Paginator(item_list, 10) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context = { 'items': items, 'category': category_list } return render(request, "home.html", context) home.html <form method="GET" action="."> <div class="form-group col-md-4"> <label for="category">Category</label> <select id="cat" class="form-control" name="cat"> <option selected>Choose...</option> {% for cat in category %} <option value="{{ cat }}">{{ cat }}</option> {% endfor %} </select> </div> <button type="submit" class="btn btn-primary">Search</button> </form> Currently the page displays the categories in a list and below theres {% for item in items %} statement witch displays all the items and they can be filtered only by the title. -
How to migrate from postgresql to sqlite3 in Django?
I was using postgresql for my project, but I have to package (into a zip file) my project along with the populated database. How do I transfer/migrate data from postgresql to sqlite3? Thankyou! -
Django data saved in the database but not show in the template
Django data is saved in the database but, when access the data in template its display nothing.the models.py and views.py code is below. models.py from django.db import models class ToDo(models.Model): title = models.CharField(max_length=100) detail = models.TextField() published_date = models.DateTimeField() def __str__(self): return self.title views.py from django.shortcuts import render, HttpResponse, redirect from django.utils import timezone from todoapp.models import ToDo def home(request): todo_items = ToDo.objects.all() context = {'todoItems': todo_items} return render(request, 'todoapp/home.html', context) def add(request): if request.method=="POST": addTitle = request.POST['addTitle'] addDetail = request.POST['addDetail'] current_date = timezone.now() addedObject = ToDo.objects.create(title=addTitle, detail=addDetail, published_date=current_date) return redirect('home') return render(request, 'todoapp/home.html') -
"Simple Dynamic" Dropdown menu in django form
First, I am quite new with django... I am trying to add a dropdown menu of available distinct Users (by name and coming from my db "dynamically") in a form. I am using django 2.2.6. # MyCustomForm class DetailedReportForm(forms.Form): AVAILABLE_USERS = MyUserModel.objects.order_by().values_list('name').distinct() selected_date = forms.DateTimeField(input_formats=['%d/%m/%Y'], required=True, widget=DateInput()) selected_user = forms.CharField(label="Select a user", widget=forms.Select(choices=AVAILABLE_USERS)) # MyModel class MyUserModel(models.Model): id = models.AutoField(db_column='Id', primary_key=True) name = models.CharField(db_column='Name', unique=True, max_length=90) ... def __str__(self): return str(self.name) The issue I am facing is my queryset is not working (not sure why) as it is giving me the following: not enough values to unpack (expected 2, got 1) I tried to google it but still not very clear to me what this error message means. Can someone please explain what this django error means so I can fix it and include the dropdown list in my form? -
Angular & Django File uploading : Forbidden (403) CSRF verification failed. Request aborted
I encounted the following problem : Forbidden (403) CSRF verification failed. Request aborted. I'm using Angular 8 to upload file and send it to django for some manipulations without saving the file and then return the pandas DataFrame as json. Here is the Angular code: uploadDatasetFile(formData : FormData){ this._http.post(`${this.baseUrl}upload_dataset`, formData).subscribe( (data) => { this.dataFrame = data; console.log(data); }, (error) => { console.error(error); } ); } And the Django codes: def upload_local_dataset(request): if request.method == 'POST': print("Request FILES : ", request.FILES) dataset = pd.read_csv(request.FILES.get('datasetfilepath'), header=0, index_col=None) request.session['ts_dataset'] = dataset.to_json(orient='values') request.session['ts_dataset_copy'] = dataset.to_json(orient='values') return HttpResponse(dataset.to_json(orient='values')) Thanks for your help. I'm new in Angular and Django, and I'm working on my internship project. -
How to kill a Celery task from the Django dev server?
Is there some sort of trick to killing or stopping a Celery task from the Django dev server? I'm trying to test some Django functionality to start and stop a Celery task on a local dev server, and the Celery worker starts the task, but is completely unresponsive to all requests to stop. The Celery task is a simple infinite loop that never ends: def my_test_task(): i =0 while 1: i += 1 print('i: %i' % i) time.sleep(1) And I launch the Celery worker directly via: celery worker -A myapp -l info -n celery@%h -Q celery I'm able to launch the task using the normal .delay() method, and I record the task_id returned. Per the docs I then try to kill the task via: app.control.revoke(task_id, terminate=True) and: app.control.revoke(task_id, terminate=True, signal='SIGKILL') However, neither of these work. I'm initializing my Celery app variable in celery_init.py which looks like: from celery import Celery from celery._state import _set_current_app app = Celery('myapp') app.config_from_object('django.conf:settings', namespace='CELERY') _set_current_app(app) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../myapp'))) django.setup() app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) # Timeout for Celery tasks if RabbitMQ message broker is down # (Tasks will throw celery.exceptions.OperationalError) app.conf.broker_transport_options = { 'max_retries': 30, # 15s, trying every half second 'interval_start': 0, 'interval_step': 0.5, 'interval_max': … -
ALLOWED_HOSTS 400 Bad Request on production environment. HOST header is NOT my website?
Django running on AWS Lightsail, and serves as backend for a mobile app. App interfaces with the DNS r.test.com My allowed hosts: ALLOWED_HOSTS = [ 'r.test.com', ] Testing this on my own works fine. When I sent my app to review, I got this weird error: Feb 10 13:37:41 ip-172-26-10-125 gunicorn[20279]: Invalid HTTP_HOST header: 'example.com'. You may need to add 'example.com' to ALLOWED_HOSTS. Feb 10 13:37:41 ip-172-26-10-125 gunicorn[20279]: Bad Request: / Feb 10 13:37:41 ip-172-26-10-125 gunicorn[20279]: - - [10/Feb/2020:13:37:41 +0000] "GET / HTTP/1.0" 400 58683 "-" "AWS Security Scanner" The submission was subsequently rejected because the reviewers we unable to use the app. The example.com you see is Copy-Pasted from the Django logs. What is this? I had never encountered this issue. I've tested on my WiFi, and 4G all around the city, and backend works fine with the app. How did the reviewers send a message to my server from example.com, and what can I do to fix this? I've seen cases where people dynamically add private IPs into allowed hosts when using AWS (like this). Should I be doing this in my case? Does this compromise on security? -
How to check otp and get phone number
I want to check my otp code is same as provided sms and get phone_number models.py class TempRegistration(models.Model): phone_number = models.CharField(max_length=45) otp_code = models.CharField(max_length=6) def __str__(self): return self.phone_number serializer.py class CheckOtpSerializer(serializers.ModelSerializer): class Meta: model = TempRegistration fields = ['otp_code'] views.py # Check otp and get username class CheckOtp(RetrieveAPIView): queryset = TempRegistration.objects.all() serializer_class = CheckOtpSerializer i wish my views.py and serializer.py is not corrrect. I want to your help to write correctly views.py and serializer.py To check otp and get or return phone_number. -
App Download from App Store got BadDeviceToken, build from source does not
I have searched over the Stackoverflow, but none of them answer to my questions Build from Xcode APNS works, but App Store version my backend raises BadDeviceToken. The Success are registration_id made by build from source In [1]: APNSDevice.objects.all().send_message("test") Out[1]: [{'27321a3d872613499e27638733e9d1da7e6aa52888a2d90769b150f6339360b1': 'Success', '798a23a46169e405c41a0c9f44faa0acd39a65119960b973acd248a6de1d624e': 'Success', '1d742a9ae1684fed5e6c672587ee27c1523cc97e931cc64f108f7c4924aba2af': 'DeviceTokenNotForTopic', '27173de1aed3a065644708602fd5659cf4e0f8c3ce5b3ef7c4b0769655b92041': 'DeviceTokenNotForTopic', 'e5647247877a0e1db3c7b52821b4230551267ca8a360f862ec5dde506e9b2f36': 'Success', '0eecae0cb6f4c27ee4b915e37dbb9c7cc84e4967e71c8efab808e231f46b8ec6': 'BadDeviceToken', '582d6a7c4628131cba9d0dfa9096cc81e3b48f6b6409252515d7402ef1c3ef30': 'BadDeviceToken'}] I don't care DeviceTokenNotForTopic for now. Just stay focus on BadDeviceToken Step to reproduce are: Follow this to get .p12 file Then make .pem from doc. I must put passphrase to key otherwise I can not proceed next step Download my own app from App Store and login to get registration_id Checkings: pushtry.com I upload .p12 and put registration_id. It works I can get push notification openssl s_client -connect gateway.push.apple.com:2195 -cert aps-cert.pem -key aps-key-noenc.pem also works without any problem. The connection still remain My configuration: Django3 django-push-notification @master commit: c610dd9c7871f4e81bdffce783df8b040ca22878 settings.py PUSH_NOTIFICATIONS_SETTINGS['APNS_CERTIFICATE'] = str(APPS_DIR) + '/push_noti/dd/aps.pem' PUSH_NOTIFICATIONS_SETTINGS['APNS_USE_SANDBOX'] = "gateway.push.apple.com:2195" PUSH_NOTIFICATIONS_SETTINGS['APNS_TOPIC'] = "com.multy.herr.reviews" FYI: I take care only Django backend. My iOS developer upload app from his computer. I am not sure this will be problematic or not Question: Where am I wrong? Another Solution: I might use AWS SNS to deal with this -
Django: Relating a property that returns a QuerySet to a SubQuery annotation
I'm not sure how best to go about this. I have the following @property method on my Modal: @property def check_ins(self): return SurfCheckIn.objects.filter(surf_waiver=self) However, I would like to return this compited property in my values() of a queryset. I thought of using a SubQuery annotation: queryset = self.get_queryset().filter( performance_datetime__year=date.year, performance_datetime__month=date.month, performance_datetime__day=date.day, void_type='0' ).exclude( surf_code='SPECTATOR' ).order_by( 'performance_datetime' ).annotate( surf_check_ins=SubQuery() ).values() But I'm not sure where to take the SubQuery from here? What would be the most sensible approach to retrieve that @property inside an annotation? -
checkboxes won't submit even when checked
As you can see here, I have the code for checkboxes to modify admin permissions. However, the checkboxes aren't being sent to the server even when they are checked. I can't understand why this is happening. Only the hidden input and the csrf_token is being sent when the submit button is clicked. <tbody> {% for profile in admins %} <tr> <td>{{ profile.player.guid }}</td> <td>{{ profile.user.username }}</td> <form method="post"> {% with permissions=profile.admin_permissions_as_list %} {% csrf_token %} <input type="hidden" name="action" value="modify,{{ profile.user }}"> <td style="text-align: center"><input class="form-check-input" type="checkbox" value="ban" {% if permissions.0 == '1' %}checked="checked"{% endif %}></td> <td style="text-align: center"><input class="form-check-input" type="checkbox" value="unban" {% if permissions.1 == '1' %}checked="checked"{% endif %}></td> <td style="text-align: center"><input class="form-check-input" type="checkbox" value="checkplayers" {% if permissions.2 == '1' %}checked="checked"{% endif %}></td> <td style="text-align: center"><input class="form-check-input" type="checkbox" value="viewlog" {% if permissions.3 == '1' %}checked="checked"{% endif %}></td> <td style="text-align: center"><input class="form-check-input" type="checkbox" value="key" {% if permissions.4 == '1' %}checked="checked"{% endif %}></td> <td style="text-align: center"><input class="form-check-input" type="checkbox" value="faction" {% if permissions.5 == '1' %}checked="checked"{% endif %}></td> <td><button type="submit" class="btn btn-sm btn-outline-primary">修改权限</button></td> {% endwith %} </form> <td> <form method="post"> {% csrf_token %} <input type="hidden" name="action" value="remove,{{ profile.user }}"> <button type="submit" onclick="return confirmRemove('{{ profile.user.username }}');" class="btn btn-sm btn-outline-danger">取消权限</button> </form> </td> </tr> {% endfor … -
How to connect angular 8 with django backend and spotify api?
I can't wrap my head around this problem. What i want to do is to make frontend app with angular that connects to Django api, that uses authentication flow to make request to Spotify Api. What works now is that i can make frontend on Django, but i want django to just make web request and all views would be managed with angular. -
Domain name in emails from production to some customers show wrong domain
Sometimes, for some customers (same ones all the time) The hyperlink or buttons in emails lead to a bad-domain name 0.0.0.1 or 0.0.0.9. not for all users only to a few. Mails are probably fine. Most costumers get the correct domain. Mail example (simplified): Hello {{ customer.name }} please login to : <a href="{{button_link}}" > {{button_link}} </a> In the email example above instead of having: Hello Jack please login to : https://example.com/login domain name is changed to: Hello Jack please login to : http://0.0.0.9/login Setup: mail provider: MailJet Browsers: Samsung mail, Iphone-mail app, . Happens in France (IDK why) -
How to let the objects be changed just by his creator
thanks for your time. i got a project where the user can create a model Parceiros and in that model is a model linking all the Servicos to that model Parceiros. the problem is that the Parceiros should be linked to the current user as the only way to create a Parceiros object is logging in before. after that the only user that should be able to change the Parceiros fields or Servicos should be the current user that created o Parceiros object. i've read some questions and tried with context processors, but ain't got the Parceiros linked to the user. accounts/forms.py: from django import forms from django.contrib.auth import get_user_model, authenticate User = get_user_model() class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput()) def clean (self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError('usuario não encontrado') if not user.check_password(password): raise forms.ValidationError('senha incorreta') if not user.is_active: raise forms.ValidationError('usuario desativado') return super(LoginForm, self).clean(*args, **kwargs) class RegisterForm(forms.ModelForm): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) email = forms.EmailField(label='Email address') email2 = forms.EmailField(label='Confirm Email') password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'first_name', 'last_name', 'username', 'email', 'email2', 'password' ] def clean(self, … -
can't access image url from template, python django
this is the code in views.py def store (request): products = { 'products':product.objects.all() } return render (request, 'neizer/products.html', context = products) this is the template {% block content %} <div class="products-parent"> {%for product in products%} <div class="product-child"> <img src="{{product.image.url}}" alt="no image available" /> <h2>{{product.name}}</h2> <button id="learn-more-btn">learn more</button> <p>${{product.price}} <i class="fas fa-cart-plus"></i></p> </div> {% endfor %} </div> {% endblock content %} I uploaded images using the /admin interface, when i access the image url in the django shell i get an actual url (which opens in the browser to the image), but when i try to access it in the template i get the above error -
Not able to Delete the Mongo index with django using pymongo
I have a simple model which is defined as(sample_app/models.py): class ABC(models.Model): field1 = models.CharField(max_length=255, db_index=True) field2 = models.CharField(max_length=255) then I run python3 manage.py makemigration sample_app Migration is created. The run python3 manage.py migrate sample_app Migration is performed successfully. I logged into mongo shell and checked the Indexes: db.collectino_name.getIndexes() Output--> [ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "some_info" }, { "v" : 2, "unique" : true, "key" : { "id" : 1 }, "name" : "__primary_key__", "ns" : "some_info" }, { "v" : 2, "key" : { "field1" : 1 }, "name" : "some_info_field1_a59e0e95", "ns" : "some_info" } ] So the index has been created. Great. Now I want to remove the indexes. I changed my model.py to look like this. class ABC(models.Model): field1 = models.CharField(max_length=255) field2 = models.CharField(max_length=255) Then successfully run makemigration and but got an error while migrating. File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command _line utility.execute() File "venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "venv/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "venv/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File … -
(DJANGO) How to be redirect to another URL from a view?
I'm new to Django and now I'm getting some problems in redirecting to another URL from the current view. In this case I'd like to be redirect to the Spotify Login page. Here's my view: ############################################################################# client_id = 'somestring'; # Your client id client_secret = 'anotherstring'; # Your secret redirect_uri = 'http://127.0.0.1:8000/callback/'; # Your redirect uri stateKey = 'spotify_auth_state' ############################################################################# def generateRandomString(length): text = '' possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' for i in range(0,length): text += possible[math.floor(random.random() * len(possible))] return text ############################################################################## def login_process(request): if request.method == 'GET': state = generateRandomString(16) print(str(state)) HttpResponse.set_cookie(stateKey, state) #your application requests authorization scope = 'user-top-read user-read-email' return HttpResponseRedirect(request, 'https://accounts.spotify.com/authorize?' + urllib.parse.urlencode({ response_type: 'code', client_id: client_id, scope: scope, redirect_uri: redirect_uri, state: state }), {}) def login_view(request, *args, **kwargs): print(args, kwargs) print(request.user) #return HttpResponse("<h1>Hello world</h1>") return render(request, "login.html", {}) def callback_view(request, *args, **kwargs): return render(request, "callback.html", {}) here's the link I should click to be redirect: <a href="login/">Login with spotify</a> here's my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', login_view, name='login_view'), path('login/', login_process, name = 'login'), path('callback/', callback_view, name = 'callback_view'), ] The error I get is "AttributeError at /login/'str' object has no attribute 'cookies' " and I don0t even know if the method "return HttpResponseRedirect" is the … -
What does 'serializer.initial_data' mean?
How can I use 'serializer.initial_data' in Django Rest-API. What is the difference between using request.data and serializer.initial_data. -
Django Celery: TypeError: 'NoneType' object is not iterable
I'm adding django-celery to my project, there's currently an issue you'll experience where a first install of this installs an outdated celery which you need to update and it has a dependency django-celery-results which also has it's expected version for each depending on it's version. I've ended up with the following versions Name: django-celery-results Version: 1.0.0 Name: django-celery Version: 3.3.1 Name: celery Version: 4.4.0 in my app/tasks.py I have the following code from celery import shared_task from django.conf import settings @shared_task def update_extend(): users = User.objects.filter(is_active=True) for user in users: .... based on the docs this seems like the next line of code to test (fortnox) sam@sam:/media/veracrypt1/fortnox$ python manage.py celery Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/sam/code/envs/fortnox/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/sam/code/envs/fortnox/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sam/code/envs/fortnox/lib/python3.6/site-packages/django/core/management/__init__.py", line 244, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/sam/code/envs/fortnox/lib/python3.6/site-packages/django/core/management/__init__.py", line 37, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/home/sam/code/envs/fortnox/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
Invalid password format or unknown hashing algorithm in django class based view
I want to create user by Api View. But i get this problem. serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password') views.py class UserRegistration(CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer please assist to solve this problem. Thanks in advanced. -
restricting users from entering into forms
i am trying to implement some sort of business logic into my django project, of which only 1 instance of an object should be created per parent object. So far , im doing so by hiding the buttons to the create form and showing another update button when the transaction is being done. However , theres a certain scenario that may happen: User A and B are in the same page User A goes into the createview User A fills up the form User B page has not refreshed , clicks into the createview button User A fills up the form , exits , the button switches to the update view user B finishes the form , exits, the button switches to an update view There is now 2 objects being created. Hence my question , is there a way to lock a createview when a user is inside it? -
Django Create View form validation warnings
I have a Create View form that looks like this: class LineItemCreateView(CreateView): model = LineItem fields = ('sku', 'description', 'quantity', 'order', 'status') def get_form(self, form_class=None): form = super(LineItemCreateView, self).get_form(form_class) form.fields['order'].initial = self.kwargs['order_id'] form.fields['description'].widget = forms.Textarea() return form When the user loads the form page for the first time, validation warnings appear for every field. This behavior is causing the form to not show initial values I have set. However, if I refresh the URL, then everything looks the way it should. I believe validation messages should appear after user clicks submit, not before. How can I remove the validation so it doesn't show up when user first opens the form? New item page -
Image field in Django rest api shows "null". Why so?
I was trying to display images. The images are stored in the media/pics folder. My model has the image names column. settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Model: img = models.ImageField(upload_to="pics") urls: urlpatterns = urlpatterns + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Serializer: class PerGroupImageViewSerializer(serializers.HyperlinkedModelSerializer): img = serializers.ImageField(max_length=None, use_url=True) class Meta: model = ExampleModel fields = ('photoId', 'img') output: "data": [ { "photoId": 4, "img": null }, Please help! New to django and learning it every day :) Thank you! -
Replacing a file in django
I have a standard Form to edit an object that has a file field in it. When I add a new profile, everything works fine, but when I want to modify a field, then problems happen: when I don't include request.FILES, all fields get retrieved in the form and can be updated with no problems, except the avatar (filefield), but when I add the request.FILES, fields are no longer retrieved in the inputs, and the form is not valid. What am I doing wrong? models.py: from django.db import models class Profile(models.Model): name = models.CharField(max_length=45) email = models.EmailField() avatar = models.FileField(upload_to="avatars/") def __str__(self): return self.name forms.py: from django import forms from .models import Profile class EditUserForm(forms.ModelForm): class Meta: model = Profile fields = ["name", "email", "avatar"] profile.html: <form method="POST"> {% csrf_token %} <div class="col-md-12"> <div class="row border m-3 p-5"> <div class="col-md-6">Name</div> <div class="col-md-6">{{ form.name }}</div> </div> <div class="row border m-3 p-5"> <div class="col-md-6">Email</div> <div class="col-md-6">{{ form.email }}</div> </div> <div class="row border m-3 p-5"> <div class="col-md-6">Avatar</div> <div class="col-md-6"> <img src="{{ profile.avatar.url }}" width="100rem" /> {{ form.avatar }} </div> </div> <div class="row"> <button type="submit" class="btn btn-success">Save</button> </div> </div> </form> views.py: def profile(request, pk): profile_instance = Profile.objects.get(id=pk) form = EditUserForm(request.POST, request.FILES, instance = profile_instance) … -
Issue with Django Serializers when fields are from many tables FK
i a newi'm trying to understand how serializers from django works when we have multiple fields from multiple tables, and this fields are related with FK. My Goal is retrieve all informations in one Json. I create a scenario ti post here, My Models: class operacoes(models.Model): # Fields date = models.DateTimeField() class Meta: ordering = ('-pk',) def __unicode__(self): return u'%s' % self.pk def get_absolute_url(self): return reverse('sales_operacoes_detail', args=(self.pk,)) def get_update_url(self): return reverse('sales_operacoes_update', args=(self.pk,)) class type(models.Model): # Fields name = models.CharField(max_length=255) description = models.TextField(max_length=100) # Relationship Fields venda_operacoes = models.ForeignKey( 'sales.operacoes', on_delete=models.CASCADE, related_name="types", ) class Meta: ordering = ('-pk',) def __unicode__(self): return u'%s' % self.pk def get_absolute_url(self): return reverse('sales_type_detail', args=(self.pk,)) def get_update_url(self): return reverse('sales_type_update', args=(self.pk,)) class car(models.Model): # Fields name = models.CharField(max_length=255) # Relationship Fields car_type_relate = models.OneToOneField( 'sales.type', on_delete=models.CASCADE, related_name="cars", ) class Meta: ordering = ('-pk',) def __unicode__(self): return u'%s' % self.pk def get_absolute_url(self): return reverse('sales_car_detail', args=(self.pk,)) def get_update_url(self): return reverse('sales_car_update', args=(self.pk,)) class source_car(models.Model): # Fields name = models.CharField(max_length=255) brand = models.TextField(max_length=100) price = models.TextField(max_length=100) # Relationship Fields source_car_car = models.OneToOneField( 'sales.car', on_delete=models.CASCADE, related_name="source_cars", ) class Meta: ordering = ('-pk',) def __unicode__(self): return u'%s' % self.pk def get_absolute_url(self): return reverse('sales_source_car_detail', args=(self.pk,)) def get_update_url(self): return reverse('sales_source_car_update', args=(self.pk,)) class bike(models.Model): # Fields name …