Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot return field dict from django-revisions Version instance
I'm trying to introduce django-reversion into my app, which also uses django-organizations. While the core functionality is functional- I'm getting some issues when fetching Version field_dict. I have an account class that looks like this, which is registered with revisions from organizations.models import Organization reversion.register(Organization) @reversion.register() UserAccount(Organization): account_type = serializers.CharField() feature_1_enabled = serializers.BooleanField() ... I create the initial revisions using the provided management command, and everything seems fine. After modifying and saving, I have a few Version objects as expected. However, when writing tests, or working in the django shell, I get unexpected errors when fetching the field_dict. account = UserAccount.objects.first() arbitrary_version = Version.objects.get_for_object(account)[0] print arbitrary_version.field_dict Results in File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/reversion/models.py", line 295, in field_dict db=self.db, File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name DoesNotExist: Version matching query does not exist. However, pretty much everything else works. I can use these Version objects to revert, fetch see the serialized_data, etc. I'm pretty clueless as to whats causing this, and the traceback isn't particularly helpful. Any help in diagnosing this is greatly appreciated. -
How to only display a gif in a modal windows in django when clicking the submit button if the form is complete
I am new to stackoverflow, this is my first post so please accept my apologies if I manage something wrong. I have prepared an upload page in django. The submit button activates a bootstrap modal page with animated gif+ text"please wait". If the file to upload is not provided or the disclaimer not read, an error default message is shown on the page and nothing else should happen; but the modal page opens and is active for ever. I would like the modal page to open only if the data and files are present. The probleme is I am quite new to Django (only a few months formation), I don't know java/jquery at all and I am not at ease with HTML, coming from maths and python. I have tried to adapt some jquery scripts provided on Stackoverflow as fro example "Show a loading image after clicking the submit button when the form is valid" and in "How do I get a jQuery dialog window to display only if a form validates when I click the submit button?". I tried to adapt the jquery functions to my data but I failed. I have also tried to insert "data-dismiss" and modal.close … -
custoomizing success_message in SuccessMessageMixin
Cant get my head around 1 thing: In Django documentation said that you can do something like that when use SuccessMessageMixin: success_message = "%(name)s was created successfully" where (name) is a field of the form used by a View. I am trying to add name of the user in the success message in PasswordResetView. PasswordResetView has by default form called “PasswordResetForm” and this form has only 1 field “email” that I have already used. Example --- success_message = "Email with the instructions has been sent to your email - %(email)s" # original Django code class PasswordResetView(PasswordContextMixin, FormView): email_template_name = 'registration/password_reset_email.html’ extra_email_context = None form_class = PasswordResetForm # this form # original Django code class PasswordResetForm(forms.Form): email = forms.EmailField(label=_("Email"), max_length=254) # this field I am trying to somehow do something like : success_message = "Email with the instructions has been sent to your email - %(email)s, %(username)s" but question where is to get username if this form has only 1 field “email”? Interesting moment that PasswordResetForm has a method called get_users(), where we could get username from: def get_users(self, email): """Given an email, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies … -
Django: Using signals with inline models
I have two models, Job and Operation, where Operation has a foreign key relation to Job (ie, a job can have 0 or more operations). I want people to enter info about jobs and operations together via the Django Admin interface, using inlines. Job has a few fields computed from its related operations. Rather than simply make them computed @property properties, I want them to be regular database fields that get updated when the operations change via signals. I set up a receiver that looks like this: @receiver(post_save, sender=Operation) def update_job_on_operation_save(sender, instance, **kwargs): instance.job.compute_fields() Here is the issue: If someone is editing the Job form on the Django Admin, and they add multiple operations inline before hitting save, then the receiver function gets called multiple times simultaneously. I am a little worried about a race condition, as well as the inefficiency of each signal leading Job to recompute some properties and save to the database. It would be better, perhaps, to attach the receiver to Job, so the function only gets called once, but if someone were to edit an Operation outside of the Job form that should also trigger a recompute. Is it possible to set up similar post_save … -
showing error:Reverse for 'hompage' not found. 'hompage' is not a valid view function or pattern name
I added hompage function to my views.py and define spam namespace in url.py and also added spam app to setting.py file.now i want that after clicking 'detect' button which is in my template index.html i will redirect to same page but i am getting error:Reverse for 'hompage' not found. 'hompage' is not a valid view function or pattern name. view.py file from django.shortcuts import render from django.urls import reverse from django.http import HttpResponse,HttpResponseRedirect def hompage(request): return render(request,'index.html') url.py file from django.conf.urls import url from . import views app_name = "spam" urlpatterns=[ url(r'^',views.hompage) ] index.html file {% block content %} <form action="{% url 'spam:hompage' %}" method="post" > {% csrf_token %} {{ form.as_p }} <input type="submit" name="submit" value="Detect"> {% endblock %} installed app part of setting.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'spam', ] -
How can I cache a view only for unauthenticated users?
I have a view which I want to cache only for unauthenticated users, so my question is exactly as this, which is unanswered, and I could not make sense of the comments. The view should be something like this: @cache_page_for_unauthenticated(60 * 15) def my_view(request): I've looked at the docs but could not but could not find any hints about this. So appreciate your help. -
GPS latitude and longitude
I have some code to get latitude and longitude and this code working in local server but not working in real server ,why? *I have some code to get latitude and longitude and this code working in local server but not working in real server ,why?** <body> <td align="center">{{res.product_id.Arabic_name}}</td> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href='/static/style/file.css'/> <br><br><br> <div align="center" style="width=40%" id="bt"> <p><a href="/start/1"><button class="dropbtn" >العربية</button></a></p> <p><a href="/start/4"><button class="dropbtn">Türk</button></a></p> <p><a href="/start/2"><button class="dropbtn">ENGLISH</button></a></p> <p><a href="/start/3"><button class="dropbtn">Русский</button></a></p> </div> <center><h2 id="loc" style="visibility:hidden">أنت بعيد عن المقهى يرجى التواجد في المقهى لتشغيل النظام</h2></center> <p name="lat" id="demo" style="visibility:hidden" ></p> <p name="long" id="demo1" style="visibility:hidden"></p> <script> var x = document.getElementById("demo"); var y = document.getElementById("demo1"); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } function showPosition(position) { x.innerHTML = position.coords.latitude y.innerHTML= position.coords.longitude; var L=position.coords.latitude var K=position.coords.longitude; if ((L !=21.556428800000003)||(K!=39.211827199999995)) { document.getElementById("bt").style.display = 'none'; document.getElementById("loc").style.visibility = 'visible'; } } </script> </body> {% endblock %} </html> -
How to force a full reload of a page after a POST
I am using class based view with a get and a post methods class MyView(View): def get(self,request, *args, **kwargs): #some code def post(self,request, *args, **kwargs): #update some data which is used in the view redirect('app:my-view') the problem with this is that django does not re-execute the get method after the redirect (the GET request can be confirmed in firebug). If I hit F5 manually in the browser, I can see the modified data. This is probably a cache issue, but want to update the page but if the page is no reloaded in the GET after the POST, I can't do this. -
Defining settings in a Django project
I'm making a simple blog application on Django, using PyCharm as IDE. If I try to use Python Console, I get this error every time. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. If I open console command line in Terminal, I have to specify my settings using this command every time: set DJANGO_SETTINGS_MODULE=mysite.settings It looks like manage.py file already has a settings reference but for some reason it seems to be ignored: import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Example.settings") try: from django.core.management import execute_from_command_line except ImportError: ... -
Validate if user account is active in Django Rest Framework
I'm trying to implement account activation by e-mail link. My User model is very simple, inherits from django.contrib.auth.models.AbstractUser, so it has is_active field by default. Upon registration, new user is created with is_active=False param and I want to handle case, when user tries to log in and even though credentials are fine, should not be logged in because account is not activated. I'm using Knox Token Authentication. My serializer: from django.contrib.auth import authenticate from rest_framework import serializers, exceptions class LoginUserSerializer(serializers.ModelSerializer): class Meta: model = UserModel fields = ('username', 'password') def validate(self, data): user = authenticate(**data) if user: if user.is_active: return user raise exceptions.AuthenticationFailed('Account is not activated') raise exceptions.AuthenticationFailed() And view: from django.contrib.auth import login from rest_framework.permissions import AllowAny from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.views import LoginView from .serializers import LoginUserSerializer class LoginUserView(LoginView): serializer_class = LoginUserSerializer permission_classes = [AllowAny] def post(self, request, *args, **kwargs): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginUserView, self).post(request) And with that code, I stumbled upon problem: when I try to log in with already activated account, everything looks fine, but when I try unactivated one, instead of Account is not activated, I get: { "non_field_errors": [ "Unable to log in with provided credentials." … -
How do i make the "Send email" button work in a Boostrap template?
For my website, i use a free template form startbootstrap.com, in this template there is a "Send Mail" button, i tried to get it running, but it doest, work. How can i make it work? I have already changed the mailto@something.com to my real email and it didnt work. I am not very experienced in web developing, so it might be a very simple thing. Any help would be much appreciated Here is the code section for the email part: \n The only line i changed was : action="mailto:myreal@mail.com" method="POST" enctype="text/plain"> This section tells me that i should configure my web server differently if things dont work, how would i do that <!-- The form should work on most web servers, but if the form is not working you may need to configure your web server differently. --> I expected this part, to just send an email to me from the provided email addres with the given content, but when i try to run it it says: Sorry, it seems that my mail server is not responding. Please try again later! Thanks in advance! -
convert a docx/pdf file to text file automatically after saving a new model in a django class based view
I'm setting up a django application for applying online, my model contains some charfields and a file field for the resumes, what i want is : every time a new resume is saved, it will automatically be converted to txt format and saved in the media folder. the problem is that the conversion only works if I restart the server. Here's my view : from django.shortcuts import render from rest_framework import viewsets, permissions from rest_framework.parsers import FormParser, MultiPartParser from .serializers import candidateSerializer from .models import Candidate from .conversion import convertPDF, convertDOCX, handle_uploaded_file #from django.db.models.signals import post_save #from django.dispatch import receiver from rest_framework.response import Response from rest_framework.decorators import action #from django.core.files import File class candidateView(viewsets.ModelViewSet): permission_classes = [ permissions.AllowAny, ] serializer_class = candidateSerializer queryset = Candidate.objects.all() cv = list(queryset.values('CV')) cvName = [el['CV'] for el in cv] file = cvName[len(cvName)-1] handle_uploaded_file(file) -
Django access PK/Object in URL
I have two classes - event and round. Round has a foreign key constraint to event, so a round is bound to an event. Now to create a round I have the following route <slug:slug_event>/new/ And to access a round <slug:slug_event>/<int:pk_round>/ To save a round I need to declare a event. So in my round/views.py I have fields = [..., 'event'] and I can select the event the round will be attached to. But I'd like to not have that event field, because the event is already given in the URL. So I'd like something like class RoundCreateView(CreateView): model = Round pk_url_kwarg = 'pk_round' fields = [...] def form_valid(self, form): form.instance.event = self.request.event #obviously this dosn't work return super().form_valid(form) so i don't need to specify the event "twice". -
Django:How can I prevent authenticated user from both register and login page in Django-registration-redux
I am currently using Django-registration-redux for my authentication system. Already logged in user can visit the login and registration page again; which is not good enough. How can I prevent them from this since the views.py comes by default in Django-registration-redux I think that should be done in the views.py that come with Django-registration-redux Here is the views.py """ Views which allow users to create and activate accounts. """ from django.shortcuts import redirect from django.views.generic.base import TemplateView from django.views.generic.edit import FormView from django.conf import settings from django.utils.decorators import method_decorator from django.views.decorators.debug import sensitive_post_parameters try: from django.utils.module_loading import import_string except ImportError: from registration.utils import import_string from registration import signals # from registration.forms import RegistrationForm REGISTRATION_FORM_PATH = getattr(settings, 'REGISTRATION_FORM', 'registration.forms.RegistrationFormUniqueEmail') REGISTRATION_FORM = import_string( REGISTRATION_FORM_PATH ) class _RequestPassingFormView(FormView): """ A version of FormView which passes extra arguments to certain methods, notably passing the HTTP request nearly everywhere, to enable finer-grained processing. """ def get(self, request, *args, **kwargs): # Pass request to get_form_class and get_form for per-request # form control. form_class = self.get_form_class(request) form = self.get_form(form_class) return self.render_to_response(self.get_context_data(form=form)) def post(self, request, *args, **kwargs): # Pass request to get_form_class and get_form for per-request # form control. form_class = self.get_form_class(request) form = self.get_form(form_class) if form.is_valid(): # … -
user.is_authenticated not working on production
I am using django 1.11.5 version and in my template {{ user.is_authenticated }} is printing CallableBool(False) or CallableBool(True) Which is confusing my this template condition {% if not user.is_authenticated %} https://code.djangoproject.com/ticket/26988 I have seen this issue on django project website and it was saying to upgrade to django version 1.10 but my django version is 1.11.5 My python version is 3.5 I think instead of bool value true or false i am getting CallableBool which is type and is confusing my condition user.is_authenticated -
pymongo.errors.OperationFailure: Authentication failed
i am trying to use MongoDB data base in django. For that i changed my setting to this I am using mlab here. settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'crud-django', 'HOST': 'mongodb://adityakmr:password1@ds231956.mlab.com:31956/', 'USER': 'adityakmr', 'PASSWORD': 'password1' } } But everytime i try to run migrations i got some error like this. I have no idea where it is comming from i have already provided correct user name and password. I have also installed djongo using pip. 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 "C:\Users\adity\Desktop\crud-django\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\adity\Desktop\crud-django\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\adity\Desktop\crud-django\env\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\adity\Desktop\crud-django\env\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\adity\Desktop\crud-django\env\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\adity\Desktop\crud-django\env\lib\site-packages\django\core\management\commands\migrate.py", line 87, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\adity\Desktop\crud-django\env\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\adity\Desktop\crud-django\env\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\adity\Desktop\crud-django\env\lib\site-packages\django\db\migrations\loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\adity\Desktop\crud-django\env\lib\site-packages\django\db\migrations\recorder.py", line 73, in applied_migrations if self.has_table(): File "C:\Users\adity\Desktop\crud-django\env\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "C:\Users\adity\Desktop\crud-django\env\lib\site-packages\django\db\backends\base\introspection.py", line 48, in table_names return … -
Django / Factoryboy - unable to delete instances in test
I am writings tests for a django application and I've run into a problem were deleted objects still exist in the test database after I've supposedly deleted them. I'm using the following factory class CMSPageFactory(factory.DjangoModelFactory): class Meta: model = CMSPage title = factory.Faker('company') tenant = factory.SubFactory(TenantFactory) key = factory.Faker('slug') protected = False in_navigation = False active = True This is the test I am running def test_example_for_so(self): page = CMSPageFactory() page.delete() self.assertFalse(page) And it raises the following error: AssertionError: <CMSPage: Fletcher LLC> is not false I must be missing something very obvious but for the life of me I cannot figure out what. Does anyone know what I am doing wrong? -
How to get the primary key value on the post response in django rest frame work
I am using the Django Rest Framework. I am using post method. After call the post method i need to get the primary key in that post call response. This is my Serializer code: from rest_framework import serializers from .models import ImtsRequest, MercadoPagoPayment class ImtsRequestSerializer(serializers.ModelSerializer): class Meta: model = ImtsRequest fields = ('taskid', 'publisherid', 'isbn', 'imts_mode', 'imts_logmode', 'imts_packagepath', 'databasename', 'callbackurl', 'counter', ) read_only_fields = ('CreatedDateTime', 'status', 'retry',) class MercadoPagoPaymentSerializer(serializers.ModelSerializer): # paymentRequestID = serializers.IntegerField(read_only=False) class Meta: model = MercadoPagoPayment fields = '__all__' # read_only_fields = ('CreatedDateTime','paymentRequestID') def create(self, validated_data): data = MercadoPagoPayment(token = validated_data['token'], payment_method_id = validated_data['payment_method_id'], issuer_id = validated_data['issuer_id'],installments = validated_data['installments'], order_id = validated_data['order_id'], payer_email = validated_data['payer_email'], transaction_amount = validated_data['transaction_amount'], capture = validated_data['capture'], requestjsondata = validated_data['requestjsondata']) data.save() print(data.paymentRequestid) return data This is my Model: from django.db import models # Create your models here. class MercadoPagoPayment(models.Model): paymentRequestid = models.AutoField(db_column="paymentRequestid", primary_key=True) token = models.CharField(max_length=32, blank=False, null=True) payment_method_id = models.CharField(max_length=10, blank=True, null=True) issuer_id = models.IntegerField(db_column='Issuer_id', null=True) installments = models.IntegerField(db_column='installments', null=True) order_id = models.CharField(max_length=32, blank=False, null=True) payer_email = models.CharField(max_length=200, blank=True, null=True) transaction_amount = models.FloatField(blank=False, null=False) capture = models.BooleanField(default=False) requestjsondata = models.TextField(db_column='requestjsondata', null=True) CreatedDateTime = models.DateTimeField(db_column='CreatedDateTime', null=False, auto_now_add=True) # Field name made lowercase. class Meta: managed = True db_table = 'MercadoPago_Payment' This is my view: … -
what is mean by current user model for this line of code. from django.contrib.auth import get_user_model
I can't understand this line of code from django.contrib.auth import get_user_model. It tells that it takes the current user model. But what is meant by the current user model? -
problem in views, Class 'Student' has no 'objects' memberpylint(no-member)?
when i create a variable students equal models.Student.objects.all() it shows a problem Class 'Student' has no 'objects' memberpylint(no-member) ! but the syntax is true because i see this in django documentation ! def Students(request): students = models.Student.objects.all() con = { 'students': students } return render(request, 'students.html', con) enter image description here -
Can't connect to https
I´m doing and application in django and using auth_views.PasswordResetView , and when i click in the link that is sended to a email to reset the password, i´m getting this message: [04/Apr/2019 10:17:22] code 400, message Bad request version ('\x8b\x00\x00\x1c\xfa\xfa\xc0+\xc0/\xc0,\xc00\xcc\xa9\xcc\xa8 \xc0\x13\xc0\x1\x00\x9c\x00\x9d\x00/\x005\x00') [04/Apr/2019 10:17:22] You're accessing the development server over HTTPS,but it only supports HTTP. I have tried many different things first, i use this: CORS_REPLACE_HTTPS_REFERER = False HOST_SCHEME = "http://" SECURE_PROXY_SSL_HEADER = None SECURE_SSL_REDIRECT = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False SECURE_HSTS_SECONDS = None SECURE_HSTS_INCLUDE_SUBDOMAINS = False SECURE_FRAME_DENY = False and clean the cookies but doesn´t work, also I tried installing django-extensions and using python manage.py runserver_plus --cert /tmp/cert?, but i get that /tmp/cert? doesn´t exists. what can i do ?? -
Django multiple users login and logout
Two users of the same type login. When one of the users changes the tab, now the user is the one who logged in last ({{ user.username }} changes). The more major issue for me is that once one of them logout, the other logs out automatically. Basically, there is no two users, there is only one at a time, the user who logged last. Also, all the views are @login_required. @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('login')) def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: login(request, user) return HttpResponseRedirect(reverse('success_page')) else: return render(request, 'login.html') else: return render(request, 'login.html') In settings.py: SESSION_COOKIE_AGE = 24*60*60 LOGIN_URL = '/login/' My question is how I can have multiple users logged in at a same time in a Django application. -
DRF: Method GET return objects based on parameter
I am learning Django and am trying to build an endpoint that returns the objects based on a parameter given in the URL. Currently I have these URLS: /api/v1/ as root which returns: GET /api/v1/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "device-groups": "http://127.0.0.1:8000/api/v1/device-groups/" } /api/v1/device-groups/ which returns all the device groups: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "device_group_name": "Default", "group_uuid": "7465febe-7c46-4420-85a1-73dfe0af812c", "color": "4286f4", "is_default": true, "customer": { "customer_name": "Customer1", "customer_uuid": "b3eb5d7d-d1a8-4997-a65b-28bed71b7cc6" } }, { "device_group_name": "Default", "group_uuid": "e12d02d0-7916-477e-b318-9680a38617db", "color": "4286f4", "is_default": true, "customer": { "customer_name": "Another customer", "customer_uuid": "5b5dafab-c311-4f58-80f5-c50d77fcf8a5" } }, { "device_group_name": "group of customer1", "group_uuid": "c72e87b1-e7c8-4dcd-a9c7-4f6a016d7676", "color": "#ffffff", "is_default": false, "customer": { "customer_name": "Customer1", "customer_uuid": "b3eb5d7d-d1a8-4997-a65b-28bed71b7cc6" } } ] I want an endpoint like /api/v1/device-groups/<customer_uuid>/ which returns the device groups that are related to the given customer_uuid. My serializers.py: class CustomerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Customer fields = ('customer_name', 'customer_uuid') class DeviceGroupSerializer(serializers.HyperlinkedModelSerializer): customer = CustomerSerializer(many=False, read_only=True) class Meta: model = DeviceGroup fields = ('device_group_name', 'group_uuid', 'color', 'is_default', 'customer') My views.py: class DeviceGroupViewSet(viewsets.ModelViewSet): serializer_class = DeviceGroupSerializer queryset = DeviceGroup.objects.all() My urls.py: router = routers.DefaultRouter() router.register(r'device-groups', views.DeviceGroupViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include(router.urls)), ] I … -
How to properly serialize a table with multiple foreign keys to same table
I'm trying to create an API for a quiz. However, the table data is not being serialized properly. the field incorrect_answers_ar is sending ascending numbers instead of actual data. all other fields work fine the serializers is working partially. I'm running django 1.11 models.py class Question(models.Model): question = models.CharField("Question",max_length=255,blank=True, null=True) question_ar = models.CharField("Question arabic",max_length=255,blank=True, null=True) correct_answer = models.CharField("Correct Answer",max_length=255,blank=True, null=True) correct_answer_ar = models.CharField("Correct Answer arabic",max_length=255,blank=True, null=True) def __str__(self): return (self.question) class Incorrect(models.Model): incorrect_answers = models.CharField("Incorrect Answer",max_length=255,blank=True, null=True) incorrect_answers_ar = models.CharField("Incorrect Answer arabic",max_length=255,blank=True, null=True) question = models.ForeignKey(Question,related_name='incorrect_answers', on_delete=models.CASCADE,blank=True, null=True) question_ar = models.ForeignKey(Question,related_name='incorrect_answers_ar', on_delete=models.CASCADE,blank=True, null=True) def __str__(self): return (self.incorrect_answers) admin.py class IncorrectInline(admin.TabularInline): model = Incorrect fk_name = "question" class QuestionAdmin(admin.ModelAdmin): inlines = [ IncorrectInline, ] admin.site.register(Question, QuestionAdmin) serializers.py from .models import Question,Incorrect class QuestionSerializer(serializers.ModelSerializer): incorrect_answers = serializers.StringRelatedField(many=True) class Meta: model = Question fields = ('question','question_ar', 'correct_answer','correct_answer_ar','incorrect_answers_ar','incorrect_answers') views.py class ListQuestionsView(generics.ListAPIView): queryset = Question.objects.all() serializer_class = QuestionSerializer this is what I'm getting now [ { "question": "how old are you", "question_ar": "old arabic", "correct_answer": "21", "correct_answer_ar": "21 ar", "incorrect_answers_ar": [ 1, 2, 3 ], "incorrect_answers": [ "22", "23", "24" ] }, { "question": "my mobile?", "question_ar": "my mobile arabic?", "correct_answer": "asus", "correct_answer_ar": "asus arabic", "incorrect_answers_ar": [ 4, 5, 6 ], "incorrect_answers": [ "redmi", "samsung", … -
My changes for .py files not working on Django
I have a Django app on a linux server, I made some changes and not reflected, I think I need restart the app but, When I use this command python manage.py runserver for restart app, I getting this response: Non-ASCII character '\xc9' in file /home/project/settings.py on line 140, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details therefore, I think need update settings.py with #! /usr/bin/env python # -*- coding: UTF-8 -*- this codes, but my changes not reflected on server again. How can I do ? Thanks.