Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
add image field in UserCreationForm in django
I'm new to python and Django and trying to build a user profile.I have created user form directly in forms.py but don't know how to add user profile picture in registration and display it in profile template. Help me please, Thanks in advance. Here's my files: forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class LogoutForm(forms.Form): pass class SignUpForm(UserCreationForm): class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2',) def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) self.fields['email'].required = True self.fields['first_name'].required = True self.fields['last_name'].required = True I don't have defined anything in models.py for user. -
how Django reads http request and sends http response
If I write a simple http server in C. I can read http request through a file descriptor generated by accept() function in a while loop. And I can send http response to client through that file descriptor. In Django I know the HttpRequest object will be passed to view function as a argument, but I want to know which function reads the HttpRequest through the socket and generate a HttpRequest object? I know view function will return a HttpResponse object. But which function will send the actual http response to the client? And where is the while loop? -
Django and mod_wsgi python versions?
Can Django run on Python 3.6.x while mod_wsgi is create using Python 2.7.x? thank you very much for the help. -
How do I include the id field in a django form?
I'm trying to create a simple form that pulls up a record by asking its ID in the form. views.py class Bill(models.Model): """ Represents a single purchase made by a customer at a business. """ business = models.ForeignKey(Businesses) customer = models.ForeignKey(User, blank=True, null=True) charge = models.ForeignKey(Charge, blank=True, null=True) amount = models.IntegerField(verbose_name='Purchase amount (in cents)', validators=[MinValueValidator(0)]) tip = models.IntegerField(verbose_name='Tip amount (in cents)', validators=[MinValueValidator(0)]) comments = models.CharField(max_length=255, blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) forms.py from django import forms from django.forms import ModelForm from transactions.models import Bill class BillSelectForm(ModelForm): class Meta: model = Bill fields = ('id',) views.py @login_required(login_url='/sign-in/') def select_bill(request): """ Finds a bill based on its ID number. """ if request.method == 'POST': form = BillSelectForm(request.POST) if form.is_valid(): pass # look up db for id number # go to bill view page if id found AND bill not paid # go back to same page and create message saying wrong bill else: form = BillSelectForm() return render(request, 'bill_select.html', {'form': form}) However, on the template, when I use {{ form.as_p }}, I'm seeing nothing at all. Thoughts? -
Retrieving and updating users with Postman, djangoAPI?
So I'm learning using a tutorial, I'm stuck on one part, i have followed and tried to understand it, there are no errors, but the result I'm getting according to the tutorial is wrong. I don't know how to post code on here but I will try. this is my serializer class from django.contrib.auth import authenticate from rest_framework import serializers from .models import User class RegistrationSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=128, min_length=8, write_only=True ) token = serializers.CharField(max_length=255, read_only=True) class Meta: model = User fields = ['email', 'username', 'password', 'token'] def create(self, validated_data): return User.objects.create_user(**validated_data) class LoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) username = serializers.CharField(max_length=255, read_only=True) password = serializers.CharField(max_length=128, write_only=True) token = serializers.CharField(max_length=255, read_only=True) def validate(self,data): email = data.get('email',None) password = data.get('password',None) if email is None: raise serializers.ValidationError( 'An email address is required to log in.' ) if password is None: raise serializers.ValidationError( 'A password is required to log in.' ) user = authenticate(username=email, password=password) if user is None: raise serializers.ValidationError( 'A user with this email and password was not found.' ) if not user.is_active: raise serializers.ValidationError( 'This user has been deactivated.' ) return { 'email': user.email, 'username': user.username, 'token': user.token } class UserSerializer(serializers.ModelSerializer): """Handles serialization and deserialization of User objects.""" # Passwords must … -
Outputing images using xhtml2pdf: URI=None in xhtml2pdf\util.py
I’m trying to output PDF with images using xhtml2pdf in Django 1.10.6. Using a wrapper like django-xhtml2pdf won’t fit me since the handling of the file is somewhat specific (long story short I try to upload files using post method without any referrencing models or databases, and all have to be done in memory). I've tried to implement the solution proposed here: django - pisa : adding images to PDF output Here are relevant fragments of my code (let me know if you need more): views.py def render_to_pdf(request, template_source, context_dictionary): html = render(request, template_source, context_dictionary) result = StringIO.StringIO() pdf = pisa.pisaDocument(html.content, encoding="utf-8", dest=result, link_callback=fetch_resources) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse(u"""Error <pre>%s</pre>""" % escape(html)) def fetch_resources(uri, rel): path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, "")) return path settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") template.html {% load static %} <img src="{% static '/img/image.gif' %}"> The exception I’ve stumbled upon goes like this: C:\PYTHON27\lib\site-packages\xhtml2pdf\util.py in __init__, line 516 uri = uri.encode('utf-8') AttributeError: 'NoneType' object has no attribute 'encode' User ‘ghost’ had similar problem, but didn’t manage to find a permanent solution. https://github.com/nigma/django-easy-pdf/issues/4 I’ve tried to look into xhtml2pdf\util.py code, but I can’t find way out. Please help. I’m using xhtml2pdf-0.0.6 -
Can you change the name of the Django admin 'is_staff' flag?
I want to rename the "is_staff" flag to "is_volunteer" to better model the use-cases of our system. The function of this flag should stay exactly the same: only users with is_volunteer = True can access the admin interface. I haven't dug through the django.contrib.auth library to determine how rigid the model is, but I'm curious if anyone has done this before. -
NoReverseMatch error from python-social-auth custom pipeline
I'm trying to implement Facebook and Gmail authentication for my backend, but keep getting the following error: django.urls.exceptions.NoReverseMatch django.urls.exceptions.NoReverseMatch: Reverse for 'repairs-social-network-error' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] And here's the traceback: Traceback (most recent call last) File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 170, in __call__ response = self.get_response(request) File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in get_response response = self._middleware_chain(request) File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 44, in inner response = response_for_exception(request, exc) File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 94, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 136, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/django_extensions/management/technical_response.py", line 6, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/six.py", line 686, in reraise raise value File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/django/utils/deprecation.py", line 136, in __call__ response = self.get_response(request) File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 44, in inner response = response_for_exception(request, exc) File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 94, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 136, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/django_extensions/management/technical_response.py", line 6, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/six.py", line 686, in reraise raise value File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/Users/user/anaconda/envs/ebenv/lib/python3.6/site-packages/django/utils/deprecation.py", line 136, in __call__ response = … -
How to get Twilio's RequestValidator to work
I'm not sure why this doesn't work. I have been looking at Twilio's documentation here, and I tried just making it a function call, but that didn't work, so I put it directly in my view, and it still didn't work. It always returns 403. I have verified that my auth token is the same as what is on Twilio as well. from braces.views import CsrfExemptMixin from django.http import HttpResponse, HttpResponseForbidden from twilio.util import RequestValidator from secretphone.settings import TWILIO_AUTH_TOKEN class SMSWebhook(CsrfExemptMixin, View): def post(self, request): validator = RequestValidator(TWILIO_AUTH_TOKEN) request_valid = validator.validate( request.build_absolute_uri(), request.POST, request.META.get('HTTP_X_TWILIO_SIGNATURE', '') ) if not request_valid: return HttpResponseForbidden() -
Error while importing data from csv in django
I am trying to import data from csv into the django database. models.py class contactDetails(models.Model): firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) phonenumber = models.IntegerField() email = models.CharField(max_length=100) def __str__(self): return self.firstname save_form_data is project name and AppFormSaving is an app. import.py project_dir = 'K:\\PY\\save_form_data' ## project_dir = 'K:\\PY\\save_form_data\AppFormSaving' sys.path.append(project_dir) os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' import django django.setup() from AppFormSaving.models import contactDetails data = csv.reader(open('K:\\sample.csv'), delimiter=",") for row in data: if row[0] != 'firstname': details = contactDetails() details.firstname = row[0] details.lastname = row[1] details.phonenumber = row[2] details.email = row[3] details.save() when I run import.py K:\PY\save_form_data>python import.py I get an error below, File "C:\Python34\lib\site-packages\django\conf\__init__.py", line 55, in __geta ttr__ self._setup(name) File "C:\Python34\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Python34\lib\site-packages\django\conf\__init__.py", line 99, in __init __ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2224, in _find_and_load_unlocked ImportError: No module named 'settings' I followed this tutorial. What am I missing here? -
Change group in Django admin is very slow
Django 1.11 If I click Groups in Django admin site, I can see a list of groups. Namely, the address is http://localhost:8000/admin/auth/group/ I monitor the CPU usage in terminal. Python is consuming 4-5 % now. I have organized 4 groups. So, if I click any group, the server just calculating something for several minutes. The address now is like http://localhost:8000/admin/auth/group/6/change/ Maybe about 5 minutes the server is calculating something. And Python is now consuming 100 % of CPU resources. Well, Django admin is analyzing something. I have about 23-25 models. Well, this is not a very big number of models. Each model is 3 standard permissions (add, change, delete). And I created one permission myself in the Meta class of a model. So, as soon as "Change group" page is in front of me with available permissions and chosen permissions, CPU consumption by Python is again 4-5 %. Could you comment on this? Is it curable? -
apache2 python 3.4.3 ubuntu error wsgi no module named
I try deploying Django in apache2 with python 3.4, but send error 500. apache error.log: [Sat May 13 15:56:53.638802 2017] [mpm_event:notice] [pid 3610:tid 140692947613568] AH00489: Apache/2.4.12 (Ubuntu) mod_wsgi/4.3.0 Python/3.4.3+ configured -- resuming normal operations [Sat May 13 15:56:53.638897 2017] [core:notice] [pid 3610:tid 140692947613568] AH00094: Command line: '/usr/sbin/apache2' [Sat May 13 15:56:56.622523 2017] [wsgi:error] [pid 3613:tid 140692834260736] [remote 181.75.140.109:26259] mod_wsgi (pid=3613): Target WSGI script '/var/www/html/reportado-plataforma/reportalo/wsgi.py' cannot be loaded as Python module. [Sat May 13 15:56:56.622610 2017] [wsgi:error] [pid 3613:tid 140692834260736] [remote 181.75.140.109:26259] mod_wsgi (pid=3613): Exception occurred processing WSGI script '/var/www/html/reportado-plataforma/reportalo/wsgi.py' [Sat May 13 15:56:56.622646 2017] [wsgi:error] [pid 3613:tid 140692834260736] [remote 181.75.140.109:26259] Traceback (most recent call last): [Sat May 13 15:56:56.622842 2017] [wsgi:error] [pid 3613:tid 140692834260736] [remote 181.75.140.109:26259] File "/var/www/html/reportado-plataforma/reportalo/wsgi.py", line 12, in <module> [Sat May 13 15:56:56.622851 2017] [wsgi:error] [pid 3613:tid 140692834260736] [remote 181.75.140.109:26259] from django.core.wsgi import get_wsgi_application [Sat May 13 15:56:56.622876 2017] [wsgi:error] [pid 3613:tid 140692834260736] [remote 181.75.140.109:26259] ImportError: No module named 'django' I installed sudo apt-get install python3-pip apache2 libapache2-mod-wsgi-py3 my VirtualHost: SGIScriptAlias / /var/www/html/reportado-plataforma/reportalo/wsgi.py WSGIDaemonProcess reportalo python-path=/var/www/html/reportado-plataforma:/root/env/lib/python3.4/site-packages WSGIProcessGroup reportalo WSGIPassAuthorization On virtualhost directory: <Directory /var/www/html/reportado-plataforma/reportalo> <Files wsgi.py> Require all granted </Files> </Directory> my environment: appdirs==1.4.3 Django==1.11.1 django-cors-headers==2.0.2 django-filter==1.0.2 django-geoposition==0.3.0 django-location-field==2.0.3 djangorestframework==3.6.2 djangorestframework-gis==0.11.1 Markdown==2.6.8 olefile==0.44 packaging==16.8 Pillow==4.1.1 psycopg2==2.7.1 pyparsing==2.2.0 … -
Is it possible to add a new function to the class based view of django rest framework
In class-based views of django rest framework, we have by default functions like get, post etc.. Other than that, Is it possible to add our own function? If it is possible how we will refer that in url. -
Django, how to access to a library methods?
I need consume some methods defined in a library. In my module, I have /mymodule/lib/mod.py In my mod.py I have declared: class ModClient(object): """REST client for Mod API""" def __init__(self, client_id, secret, environment): self.client_id = client_id self.secret = secret self.environment = environment def _base_url(self): base_url = '' if self.environment == 'sandbox': base_url = 'https://sandbox.mod.com' elif self.environment == 'development': base_url = 'https://development.mod.com' elif self.environment == 'production': base_url = 'https://production.mod.com' return base_url def _base_params(self): params = { 'client_id': self.client_id, 'secret': self.secret } return params def _parse_response(self, response): result = response.json() if response.status_code != 200: raise ModClientException(message='HTTP status {}: {}'.format(response.status_code, result), http_status=response.status_code, error_type=result.get('error_type', None), error_code=result.get('error_code', None)) return result def get_accounts(self, access_token): url = '{}/accounts/get'.format(self._base_url()) params = self._base_params() params['access_token'] = access_token response = requests.post(url, json=params) return self._parse_response(response) How I can access to my method get_accounts from my view.py assuming that both are in the same module? -
For single user to multiple users Django app
i have a chatbot web application that simulate a customer service, where it takes the input and shows the output via request/response and some back-end python files.So far it is working for one user at a time. Now i want it to talk to multiple users at the same time where each user has his/her chatting page and cabot application. i found out that i should use: Django multi-session==> to create a session for each user. Sub-process==> to create a chatbot app of each user session. The problem i don't know how?!. So,if these any resource to example on how to implement it that will be very helpful. PS: i'm using Django 10.1,Python3 and new in the Django development field. thank you, -
Why am I getting IntegrityError: NOT NULL constraint failed
IntegrityError: NOT NULL constraint failed: app_userprofile.email The field looks like this: email = models.CharField(max_length=100, blank=True, default=None) I do not understand. Error happens when creating instance of the model and not setting the email field. But it's blank and it's charkfield, and None if not overwritten, why is it happening? -
Django Optional File Upload
I want my users to be able to update their profile, one section class Profile(models.Model): user = models.OneToOneField(User, blank=False, null=False) pic = VersatileImageField(upload_to='profile/', blank=True, default="") team = models.ForeignKey(Teams, blank=True, null=True) sport = models.ForeignKey(Sports, blank=True, null=True) first_name = models.CharField(max_length=225,blank=True, null=True) last_name = models.CharField(max_length=225,blank=True, null=True) So I wrote a form to go along with the UpdateView class EditProfile(ModelForm): def __init__(self, *args, **kwargs): super(EditProfile, self).__init__(*args, **kwargs) self.fields['first_name'].required = False self.fields['last_name'].required = False self.fields['pic'].required = False self.fields['team'].required = False class Meta: model = Profile fields = ['first_name', 'last_name', 'pic', 'team'] class EditProfile(LoginRequiredMixin, UpdateView): template_name = 'edit_profile.html' model = Profile success_url = reverse_lazy('CoachView') login_url = 'accounts/login/' form_class = EditProfile def get_object(self): obj = Profile.objects.get(user=self.request.user) return obj def get_context_data(self, **kwargs): context = super(EditProfile, self).get_context_data(**kwargs) my_profile = Profile.objects.get(user=self.request.user) context['my_profile'] = my_profile return context And the HTML. I'm using some JS in order to preview the picture before it is uploaded. <form action="" method="post" enctype="multipart/form-data">{% csrf_token %} {{ form.non_field_errors }} <div class="fieldWrapper w3-margin"> {{ form.first_name.errors }} <label for="{{ form.first_name.id_for_label }}"><h2>First:</label> {{ form.first_name|add_class:"text_input" }}</h2> </div> <div class="fieldWrapper w3-margin"> {{ form.last_name.errors }} <label for="{{ form.last_name.id_for_label }}"><h2>Last:</h2></label> {{ form.last_name|add_class:"text_input" }} </div> <div class="fieldWrapper w3-margin"> {{ form.team.errors }} <label for="{{ form.team_for_label }}">Your Team:</label> {{ form.team }} </div> <div class="fieldWrapper w3-margin"> <label for="id_photo" … -
Using Chosen.js with Django
Hello Im trying to implement chosen.js into my Django project and so far it works great. I only have one issue which I cannot solve. I have a model where "language" is a ChardField. I wanted to let the User choose more than one language so I tried to use chosen Multiple. Since a Charfield can only hold one Value so I used Django Multiselect. Now the Chosen.js is not working anymore and I have no idea what to do. Models: from multiselectfield import MultiSelectField class UserProfile(models.Model): language = MultiSelectField(verbose_name=_(u"Content Language"), max_length=40, choices=settings.LANGUAGES,default='en')` Forms: class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields=[ 'language', ..... ] Template: {% load widget_tweaks %} {% csrf_token %} <span>Content language {{ form.language|add_class:"chosen-select" }}</span> So the question is how do I get the normal chosen.js input field to a multiple chosen field (with Django)? I know there is the possibility to add a multiple field to the forms but this messes up my hole code. -
Django Models: combine multiple fields entries for one field
I am making a site for a competition and I have a model something like this class Participant(models.Model): def __unicode__(self): return "Participant: " + str(self.uuid) uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) participant = models.CharField(max_length=30, blank=False) redditusername = models.CharField("Reddit Username",max_length=21) slackusername = models.CharField("Slack Username", max_length=21) challengeone = models.CharField("Points for challenge 1", max_length=30,blank=False) challengetwo = models.CharField("Points for challenge 2", max_length=30,blank=False) challengethree = models.CharField("Points for challenge 3", max_length=30,blank=False) challengefour = models.CharField("Points for challenge 4", max_length=30,blank=False) challengefive = models.CharField("Points for challenge 5", max_length=30,blank=False) totalpoints = models.CharField("Points for all challenges ", max_length=30,blank=False) This is a terrible design I know. I have to input the points manually. Calculate the points and then add them to the totalpoints. The question I have is how can I combine the challengeone, two, three, four, five and get the total points and have a field totalpoints where the field points are added to that one automatically -
Django REST auth - users stored in external service
I've been wondering the best way to handle the case where a Django is used in a service-oriented architecture, so individual Django applications do not maintain their own user stores. One service maintains the user store, and others must call it in order to retrieve user information. So far example, here is how I was thinking of building a custom authentication class in Django REST to handle this: class SOAAuthentication(authentication.BaseAuthentication): def authenticate(self, request): token = request.get_token_from_auth_header() if not remote_auth_service.is_token_valid(token): raise AuthFailed('Token is invalid') user_properties = remote_users_service.get_user(token): # user_properties is a dict of properties if not user_properties: raise AuthFailed('User does not exist.') user = MyCustomUserClass(**user_properties) return (user, 'soa') So no user info would get persisted in the Django application's database, and permission classes could interrogate the instance of MyCustomUserClass to figure out what groups a user belongs to. Would this approach work for simple group-based authorization? My think is that I don't need object-level permissions, so there's no need to create rows for my users in the Django database. -
How to debug django ajax function when using djangorestframework decorator?
How to debug ajax function when using djangorestframework decorator. @api_view(['POST', ]) def authfb(request): require_more_data = True if request.method == 'POST': first_name = request.data['fb_first_name'] last_name = request.data['fb_last_name'] fb_picture = request.data['fb_picture'] fb_friends_number = request.data['fb_friends_number'] fb_username = request.data['fb_username'] fb_id = int(request.data['fb_id']) fb_link = request.data['fb_link'] username = fb_username.replace(' ', '') # print(username) password = '112358' user = auth.authenticate(username=username, password=password) Example of code. Django doesn't tell about any errors, when calling view functions through ajax request. This makes me using print and searching the wrong line manually and still leaves no idea what exactly is wrong. How to debug it, how to make django log errors as usual? -
Local OP file taking lower priority than Django default translation
In my settings.py, I have LOCALE_PATHS = ( os.path.join(BASE_DIR, "locale"), ) So local OP file should take higher priority than Django's default translation. However, the translation for some words which have a default translation, say first name and last name, are still the default 名字 and 姓氏, rather than 姓 and 名, which are what I've specified in /project/app/locale/zh_Hans/LC_MESSAGES/django.po: #: models.py:51 msgid "first name" msgstr "姓" #: models.py:55 msgid "last name" msgstr "名" I can bypass this issue by using Contextual markers, but it's merely a workaround which isn't "semantic". Also, I want to know why default translation can override the one in LOCALE_PATHS. -
How to create unique method for url parameters?
This is my get method: if request.method == 'GET': myObject = myObjectClass.objects.all() serializer = myObjectSerializer(myObject, many=True) return Response(serializer.data) Let's assume that response looks in this way: [ { "id": 1, "data1": 12, "data2": "example1" }, { "id": 2, "data1": 11, "data2": "example3" }, { "id": 3, "data1": 12, "data2": "example3" } ] I would like to create method using URL http://localhost:8000/data/?data1=12 to get in response: [ { "id": 1, "data1": 12, "data2": "example1" }, { "id": 3, "data1": 12, "data2": "example3" } ] My problem is that I would like to create unique method. For instance we could use URL http://localhost:8000/data/?data2="example3" and in response we would get: [ { "id": 2, "data1": 11, "data2": "example3" }, { "id": 3, "data1": 12, "data2": "example3" } ] I wonder if this is possible? What is best solution? I have been trying with request.GET, request.GET.get() etc., but nothing works. Thanks in advance. -
Problems with save ManyToMany field data
I have modal with 2 ManyToManyField. I have problems when try to save my form. Why save_m2m() method dont work? As you see in my form for function field I use ModelChoiceField and for program field I use ModelMultipleChoiceField. modals.py: class Requirement(models.Model): group_requirement = models.ForeignKey(GroupRequirement, on_delete=models.CASCADE) function = models.ManyToManyField("Function") program = models.ManyToManyField('Program') forms.py: class RequirementForm(forms.ModelForm): function = forms.ModelChoiceField(widget=Select2Widget(), queryset=Function.objects.none()) program = forms.ModelMultipleChoiceField(widget=Select2MultipleWidget(), queryset=Program.objects.none()) class Meta: model = Requirement fields = ('function', 'program') def __init__(self, all_functions, all_programs, *args, **kwargs): super(RequirementForm, self).__init__(*args, **kwargs) self.fields['function'].queryset = all_functions self.fields['program'].queryset = all_programs views.py: def requirement_add(request, group_requirement_id): group_requirement = get_object_or_404(GroupRequirement, pk=group_requirement_id) if request.method == 'POST': requirement_form = RequirementForm(data=request.POST, all_functions=all_functions, all_programs=all_programs) if requirement_form.is_valid(): requirement = requirement_form.save(commit=False) requirement.group_requirement = group_requirement requirement.save() requirement_form.save_m2m() ERROR: Traceback (most recent call last): File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 1397, in fa_requirement_add requirement_form.save_m2m() File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\models.py", line 436, in _save_m2m f.save_form_data(self.instance, cleaned_data[f.name]) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\fields\related.py", line 1573, in save_form_data getattr(instance, self.attname).set(data) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 928, in set objs = tuple(objs) TypeError: 'Function' object is not iterable -
How do I add a FlatPageAdmin?
Welcome friends I need your help. I would like to use FlatPageAdmin. Like in the example above. from django.contrib import admin class FlatPageAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('url', 'title', 'content', 'sites') }), ('Advanced options', { 'classes': ('collapse',), 'fields': ('registration_required', 'template_name'), }), ) https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fieldsets It may of course be very simple, but I don't know, how to do this. this my admin.py from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import Order from django.http import HttpResponse from django.core.urlresolvers import reverse class OrderAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'email'] list_filter = ['name'] admin.site.register(Order, OrderAdmin) I'm trying. But whatever I do I always get: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Although I add admin.site.unregister(FlatPage) admin.site.register(FlatPage, FlatPageAdmin) How to solve a problem ? I would appreciate your help