Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
problem in sending html email using django
I am trying to send emails to my clients using django send_mail function. I have configured my email host using a gmail account. This is how I send my email: send_mail(cv.QT_CONFIRMATION_MAIL_TITLE[lan], cv.QT_CONFIRMATION_MAIL[lan].format(str(uid, encoding="utf-8"), token), 'mygmail@gmail.com', [useremail], fail_silently=False, html_message=cv.QT_CONFIRMATION_MAIL[lan].format(str(uid, encoding="utf-8"), token)) this html_message has an anchor tag in it which links to the activation link. it gmail clients the link works but when I try this in yahoo emails the link is empty. it is shown in html like this: <a rel="nofollow"> click here </a> what should I do? thanks. -
Django - No file write in tmp - invalid syntax (connections.py, line 36)
I put in prod my django site in centos7 server. I had some recent problem to upload file in tmp directory (it didn't work) so i specify a tmp directory (see the last lines of the settings.py). But i still block on a problem of write file in this directory... On my dev computer, during the upload the tmp file is creating during the uplaod of the web browser (normal indeed). But here, nothinfg is write during the upload on the web browser and i have this error. error [Thu Oct 11 14:35:07.440646 2018] [mpm_prefork:notice] [pid 507] AH00170: caught SIGWINCH, shutting down gracefully [Thu Oct 11 14:35:10.692254 2018] [core:notice] [pid 956] SELinux policy enabled; httpd running as context system_u:system_r:httpd_t:s0 [Thu Oct 11 14:35:10.692948 2018] [suexec:notice] [pid 956] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Thu Oct 11 14:35:10.702639 2018] [auth_digest:notice] [pid 956] AH01757: generating secret for digest authentication ... [Thu Oct 11 14:35:10.703223 2018] [lbmethod_heartbeat:notice] [pid 956] AH02282: No slotmem from mod_heartmonitor [Thu Oct 11 14:35:10.706726 2018] [mpm_prefork:notice] [pid 956] AH00163: Apache/2.4.6 (CentOS) mod_wsgi/4.6.4 Python/3.6 configured -- resuming normal operations [Thu Oct 11 14:35:10.706750 2018] [core:notice] [pid 956] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Thu Oct 11 14:35:14.654917 2018] [wsgi:error] [pid β¦ -
how to add search_fields in django forms
I was making a django forms and there is a field owner which is related with ForeignKey by User model , Sometimes name of user is same so I want to search it by their email address , How can I add searching of email field in forms like this search_fields = ['email']. class GroupForm(forms.ModelForm): class Meta: model = Group fields = ('name', 'owner', 'club', 'moderator', 'group_type', 'country') def __init__ (self, *args, **kwargs): # brand = kwargs.pop("brand") super(GroupForm, self).__init__(*args, **kwargs) language_results = User.objects.all() # self.fields["owner"].widget = forms.widgets.CheckboxSelectMultiple() # self.fields["owner"].widget = autocomplete.ModelSelect2() self.fields["owner"] = forms.ModelMultipleChoiceField( queryset=User.objects.all(), required=True, widget = forms.SelectMultiple(attrs={ 'placeholder': "Choose the users(s)", 'class': 'chzn-select', 'multiple tabindex': '6', })) -
Using Django Geo and Google Map
I'm trying to do restaurant listing application with Django. I've done almost all the operations. I would like to list the registered restaurants near the users. I have not tried the use of a search like this before. In short, I want to tell you what I want to do; The user enters the site and wants to list the restaurants near by typing his / her address instead of searching. As a result, we list the restaurants near 5 miles. What kind of a way should I go for that. Can you help me? -
Want to add a map to my website which allows me to and other user to mark locations as specific zones and for all users to have their location shown
I'm working on a project which involves tracking users and their live locations and allowing them mark a map with various pins. How would i go about implementing this on website which would all all users to view each other's location and pin various points. how should I go about this? I don't know where i should start from. -
Template does not exists Error...in Django error while running the manage.py
{% extends 'base.html' %} <script> {% block jquery %} {% endblock %} </script> {% block content %} <div class='row'> <div clas = 'col-sm-12'> <h1>Hello world!!</h1> </div> </div> {% endblock content %} This is the simple code of chart.html and the structure of the directory is (venv) sevenbits@sevenbits-H110M-H:~/chart-django/chart$ tree . βββ chart β βββ __init__.py β βββ __init__.pyc β βββ settings.py β βββ settings.pyc β βββ urls.py β βββ urls.pyc β βββ views.py β βββ views.pyc β βββ wsgi.py β βββ wsgi.pyc βββ chartapp β βββ admin.py β βββ admin.pyc β βββ __init__.py β βββ __init__.pyc β βββ migrations β β βββ __init__.py β β βββ __init__.pyc β βββ models.py β βββ models.pyc β βββ templates β β βββ chartapp β β βββ base β β β βββ bootstrap_defaults.html β β β βββ css.html β β β βββ js.html β β βββ base.html β β βββ charts.html β βββ tests.py β βββ views.py β βββ views.pyc βββ db.sqlite3 βββ manage.py This is the urls.py file from django.conf.urls import patterns, include, url from django.contrib import admin from .views import HomeView, get_data urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$',HomeView.as_view(), name='home'), url(r'^api/data/$', get_data, name='api-data'), ] TemplateDoesNotExist at charts.html This type of error shows while running β¦ -
How to manage django admin for country section with same back and frontend listing page
I am new in Django. I am creating a app countries which will have listing page in both frontend and backend. I have manage frontend by writing code in root urls.py path('countries/', include(('countries.urls', 'countries'), namespace = 'countries')) And in countries/urls.py path('', views.index, name='index'), in models.py I write country model for frontend and In views.py write index function for frontend. This is my models.py class Country(models.Model): iso_code = models.CharField(max_length=2, unique=True) name = models.CharField(max_length=255, unique=True) is_featured = models.IntegerField(max_length=1) class Meta: db_table = 'countries' And in views.py I write def index(request): countries = Country.objects.all().order_by('id') context = { "countries" : countries } return render(request, 'countries/index.html', context) If I run http://127.0.0.1:8000/countries/ then it will load country listing page in frontend. Now, I want http://127.0.0.1:8000/admin/countries/ to see backend listing page with custom admin template. Please help me if someone know -
many to many validation in django rest framework
I have three models first is Activity and second is User and they linked to each other with many to many relationship as following and the last one is rating which has a foreign key from activity as following: models.py class Activity(models.Model): name = models.CharField(blank=True, unique=True, max_length=100) rating_average = models.FloatField(blank=True, null=True, default=0, max_length=1) members = models.ManyToManyField(User, blank=True, related_name='activitymembers') class ActivityRating(models.Model): activity = models.ForeignKey(Activity, related_name='activity', on_delete=models.CASCADE, blank=True, null=True) rate = models.IntegerField(blank=True, null=True, default=0) created_by = models.ForeignKey(User, related_name='rate_user', blank=True, null=True, on_delete=models.CASCADE) serializer.py class ActivityRateSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): created_by = kwargs['context']['request'].user super(ActivityRateSerializer, self).__init__(*args, **kwargs) self.fields['created_by'].queryset = User.objects.filter(id=created_by.id) class Meta: model = ActivityRating fields = ['id', 'activity', 'rate', 'created_by'] def create(self, validated_data): obj = ActivityRating.objects.create(**validated_data) obj.save() return obj its work fine but what i need is: how to add validator that make the rating is impossible unless you are member in activity please any one has a solution help me , thanks -
Django: UnboundLocalError: local variable 'qs' referenced before assignment
This is my view: @login_required def ledger1_detail_view(request, pk1, pk2): company_details = get_object_or_404(company, pk=pk1) ledger1_details = get_object_or_404(ledger1, pk=pk2) form_class = DateRangeForm if request.method == 'POST': form = form_class(request.POST or None) if form.is_valid(): start_date = request.POST.get('start_date') end_date = request.POST.get('end_date') qs : journal.objects.filter(Q(User=request.user) | Q(Date__range=(form.cleaned_data['start_date'], form.cleaned_data['end_date']))) return HttpResponseRedirect(ledger1_details.get_absolute_url()) else: form = DateRangeForm() context = { 'company_details' : company_details, 'ledger1_details' : ledger1_details, 'journal_list' : qs, } return render(request, 'accounting_double_entry/ledger1_details.html', context) This is my DaterangeForm: class DateRangeForm(forms.Form): start_date = forms.DateField(widget=DateInput()) end_date = forms.DateField(widget=DateInput()) This is my journal model: class journal(models.Model): Date = models.DateField() By = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') To = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2) Credit = models.DecimalField(max_digits=10,decimal_places=2) I want to filter the journal objects in ledger1_detail_view for a specific daterange...So,I have created a form named 'Daterangeform" which can filter the journal objects where "Date" of the journal objects is between the "start_date" and "end_date" of Daterangeform which will be given by the user according to their choise... I have done some form validation in my "ledger1_detail_view" as you can see...But getting this error "UnboundLocalError: local variable 'qs' referenced before assignment" Can anyone help me to accomplish this? Thank you -
Django file logger doesn't logs as excepted
I have written a simple django LOGGING in my settings.py and I excepted that to log all error with a traceback in my file. But it doesn't and it just logs errors and everything in one line, but tracebacks are logged into the console. here is my LOGGING: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '{levelname} {asctime} {name} {module}.{funcName}:{lineno} {message}', 'style': '{', }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'logs/debug.log', 'formatter': 'simple' }, }, 'loggers': { '': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': False, }, }, } can anybody help me to understand why and what to do? thanks. -
html table is not rendered in outlook using Python
Using Python, I try to render the html table and plain text in a email. But it is shown as a single text(not in a tabular format). Kindly refer below: "id created_date testrun comments assignedto 1 Sept. 24, 2018 P0 , canary , , d gomathis@xyz.com" But is expected to be as below: Hi team, Please find the below mentioned tasks for today: id created_date testrun comments assignedto 1 Sept. 24, 2018 P0 , canary , , d gomathis@xyz.com code: def send_mail(request): if request.method == 'POST': message = request.POST['message'] print("ewasrew"+message) else: htmltable = '' # os.startfile("outlook") SERVER = "smtp.xyz.com" me="gomathis@xyz.com" you="gomathis@xyz.com" msg = MIMEMultipart('alternative') msg['Subject'] = "Today's task" msg['From'] = me msg['To'] = you text = "Hi team\nPlease find the below mentioned tasks for today:\n" html = message part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') msg.attach(part1) msg.attach(part2) server = smtplib.SMTP(SERVER) server.sendmail(me, you, msg.as_string()) server.quit() return HttpResponse("Email sent") value of message is in html file. <thead class="thead-light"> <tr><th>id</th> <th>created_date</th> <th>testrun</th> <th>comments</th> <th>assignedto</th> </tr> </thead> <tbody> <tr> <td> 1 </td> <td> Sept. 24, 2018 </td> <td> <a href="http://www.google.com"> P0 </a>, <a href="http://www.google.com"> canary </a>, <a href=""> </a>, <a href=""> </a> </td> <td> d </td> <td> gomathis@xyz.com </td> </tr> </tbody> -
Django Rest Framework - Serialize multiple objects in a single object
I'm trying to integrate support for an external library in my project. The external library requires a precise data structure that it uses to call response-as-a-table. A simple serializer for my model, could be: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('id', 'title', 'author') So, supposing a snippet like this: queryset = Book.objects.all() serializer = BookSerializer(queryset, many=True) serializer.data Which gives this output: [ {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'}, {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'}, {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'} ] How should I reshape my BookSerializer class to achieve this result? I can't figure it out. { 'id': [0, 1, 2], 'title': ['The electric kool-aid acid test', 'If this is a man', 'The wind-up bird chronicle'], 'author': ['Tom Wolfe', 'Primo Levi', 'Haruki Murakami'] } -
register user by email or mobile number in django
i have custom user model with email as unique identifier for auth instead of username. i want register a user by email or mobile number. if user enter email address, then register user by activation link, and if user enter phone number then register by SMS OTP. something like instagram registration: https://www.instagram.com/accounts/emailsignup/ i found this topic but the answer is not explained well. -
Deserialize POST request with subset of serializer fields in DRF
I'm having a rather simple problem, but found a few solutions and couldn't stop wondering what the intended DRF approach would be. I have a (simplified) model and serializer like this: class CartProduct(models.Model): cart = models.ForeignKey('Cart', on_delete=models.CASCADE) product = models.ForeignKey('Product', on_delete=models.CASCADE) class CartProductSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField() product = ProductSerializer() class Meta: model = CartProduct fields = ('id', 'url', 'product') Which produces a GET response like this: "url": "http://localhost:8000/appUsers/1/cart/products/16/", "id": 16, "product": { "url": "http://localhost:8000/products/1/", "id": 1, "name": "Tomatoes", }, "cart": "http://localhost:8000/carts/1/" However, when creating a new CartProduct now, in this default scenario I would need to pass a nested product dictionary like the one above to create / deserialize a new CartProduct from a POST request. What I would like instead is to send a POST request with a body using just primary keys or urls to create a new cart product, e.g. like this: "product": 1, "cart": 1 or "product": "http://localhost:8000/products/1/" "cart": "http://localhost:8000/carts/1/" So now I was wondering what would be the best way to achieve this? I thought of: Writing two separate serializers (but I don't like the idea of having two serializers for pretty much every model like this) Adding additional fields to every serializer making sure β¦ -
Module WSGI don't recognize by Heroku
I'm deploy Django==2.1 with Python==3.6.5 on Heroku and the push works fine but when i goes to the link appears aplicaition error. The log say me that wigs module doesn't exist: $ heroku logs --tail 2018-10-11T10:19:04.796988+00:00 app[web.1]: __import__(module) 2018-10-11T10:19:04.801708+00:00 app[web.1]: ModuleNotFoundError: No module named 'healthylife.wsgi' 2018-10-11T10:19:04.801978+00:00 app[web.1]: [2018-10-11 10:19:04 +0000] [11] [INFO] Worker exiting (pid: 11) But i have revised and i think it's ok: Procfile: web: gunicorn healthylife.wsgi --log-file - settings.py: WSGI_APPLICATION = 'healthylife.wsgi.application' wsgi.py: from django.conf import settings from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "healthylife.settings") application = get_wsgi_application() if not settings.DEBUG: try: from dj_static import Cling application = Cling(get_wsgi_application()) except: pass Someone could help me ? Thanks in advance -
Django ORM query fails when executed as query in db
I have a django query which compares datetime like this - filters = {'order_created_on__gte':'2018-10-10'} model.objects.filter(**filters) It creates a query - select ... where order_created_on >= 2018-10-10 00:00:00 When fired on db, it gives an error - syntax error at or near "00". If I fire the same query in db manually by replacing the date by '2018-10-10' it works. Now I actually tried the following ways, but all queries give the same text in the db query filters = {'order_created_on__gte':datetime(2018-10-10)} filters = {'order_created_on__year__gte':2018, 'order_created_on__month__gte':10, 'order_created_on__day__gte':10} Also used the range filter, all of the above insert this text in the final query - where order_created_on >= 2018-10-10 00:00:00 Updating the time zone too didnt have any effect rather than just removing a +5:30 from the query. -
Passing Data returned from (SqLite) QuerySet in Django to a React frontend. How would i go about achieving this
I want to pass Data returned from (SqLite) QuerySet in Django to a React frontend. How would i go about achieving this. I have the react app being built (npm run build) with the React index.html having its <script> var json_data = {{{window.jsonData || null}}} </script> When my django backend queries for data, I want to pass the result as json to django index.html (which will be the react index.html). How do i go about achieving this . Newbie to Django here. -
Django Session Not Set using CROS
i am having problem with setting up session for CROS request. i have also used the cros header repo. this is my cross origin header setting CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'Cookie', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken','x-requested-with' ) CORS_ORIGIN_ALLOW_ALL=True CORS_ALLOW_CREDENTIALS=True CORS_URLS_REGEX = r'.*' CORS_ORIGIN_WHITELIST = ( 'localhost', '192.168.1.6', '127.0.0.1', ) and i am setting up the session using request.session['device'] = 'WEB' request.session['user'] = {'current_user': username, 'token': 'token'} and set-cookie is not sent by django server to front-end server on authentication request, but as of for postman all this is working fine. -
url path from categories in DetailView
I use a DetailView to display all elements inside a category. I am trying to get my category slugs as variables in urls. But I don't know how to make the link between categories and details. So far I get an "Cannot resolve keyword 'slug' into field" error. #Models.py class categories(models.Model): name = models.CharField(max_length=50,unique=True) slug = models.SlugField(max_length=100,unique=True) def __str__(self): return self.name class details(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=42) category = models.ForeignKey('categories', on_delete=models.CASCADE,related_name="detail") def __str__(self): return self.title #Views.py class IndexView(generic.ListView): model = categories context_object_name = "list_categories" template_name='show/index.html' class CategoryDetails(DetailView): model = details context_object_name = "detail" template_name = "show/categories.html" slug_url_kwarg = 'slug' #Urls.py urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<slug:slug>', views.CategoryDetails.as_view(), name='category_details'), ] #Index.html {% load staticfiles %} <p>These is a list of categories</p> {% for category in list_categories %} <div class="article"> <h3>{{ category.name }}</h3> {% for detail in category.categories.all %} <p> {{detail.title}} </p> <li><a href="{% url 'category_details' category.slug %}">URLS</a></li> {% endfor %} </div> -
Django - cant creat directory in settings.py - Apache2
I work to put in prod mode a Django website. I stuck in Error Permission for create a folder by my settings.py. I cant in my settings.py create a directory... why ? =( Error log (i remove not useful informations) mod_wsgi (pid=440685): Failed to exec Python script file '/PATHMYSITE/wsgi.py'. mod_wsgi (pid=440685): Exception occurred processing WSGI script '/PATHMYSITE/wsgi.py'. Traceback (most recent call last): File "/PATHMYSITE/wsgi.py", line 21, in <module> application = get_wsgi_application() File "/PATHMYENV/lib64/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/PATHMYENV/lib64/python3.6/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/PATHMYENV/lib64/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/PATHMYENV/lib64/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/PATHMYENV/lib64/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib64/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 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 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 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/PATHMYSITE/MYSITE/__init__.py", line 5, in <module> from .settings import β¦ -
creating logs in Django after Update
I try to Implement an logger in Django. I had it allready working in Django Version 1.5 and Python 2.7. But when I try to implement it on my actual Version(Django 2.0.8 and Python 3.6.5) I get the Error on the following Code in the manage.py: logging.config.fileConfig('ProjectServer/logging.ini') Exception has occurred: TypeError '>' not supported between instances of 'str' and 'int' File "C:\path\ProjectServer\manage.py", line 10, in<module> logging.config.fileConfig('ProjectServer/logging.ini') My logging.ini: [loggers] keys=root [handlers] keys=consoleHandler, rotatingFileHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=consoleHandler,rotatingFileHandler [handler_consoleHandler] class=logging.StreamHandler level=INFO formatter=simpleFormatter args=(sys.stdout,) [handler_rotatingFileHandler] class=logging.handlers.RotatingFileHandler args=(r'c:\log\debug.log','maxBytes=1000000','backupCount=3') level=INFO formatter=simpleFormatter [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt= I donΒ΄t really get how it would come to the Error. When I checked the Pythonversion I didnΒ΄t notice any changes regarding the Logging. Afterwards iΒ΄m importing the Logging and use it like this in my Models and Views import logging logger = logging.getLogger(__name__) logger.info('error creating calendar file') -
How to display the profile pic in facebook and google+ in django template?
I am working on an accounting application which has a feature of login using google+ and Facebook... The functionality of the social-auth is working properly... I am using: 'social_django' Downloaded using: pip install social-auth-app-django I was just wondering how to grab the current profile pic(of google+ or facebook) of the user who is signing in through social-auth in my django project... I want to display their updated profile pic in my project which they have for google+ and facebook... Can this be done in a django project??? -
Django - Filter the prefetch_related queryset
I am trying to reduce my complexity by doing the following. I am trying to get all the teachers in active classrooms. teachers = Teacher.objects.prefetch_related(Prefetch('classroom_set',queryset=Classroom.objects.filter(status='Active')) for teacher in teachers: classrooms = teacher.all() # run functions By doing this I get teachers with classrooms. But it also returns teachers with no active classrooms(empty list) which I don't want. Because of this, I have to loop around thousands of teachers with empty classroom_set. Is there any way I can remove those teachers whose classroom_set is [ ]? Thanks -
Django(1.11) rest framework post user.id in nested serializer
I want to get user.id in the background when user creates a delivery address and product data in models and i get this error ull value in column "ordered_by_id" violates not-null constraint DETAIL: Failing row contains (66, 5051, tetsst, 2018-10-11, f, null). Which means that user.id is not being added to models for some reason. My models.py class Product(models.Model): price = models.FloatField() name = models.CharField(default='gift', max_length=512) ordered_by = models.ForeignKey(User, null=False) date = models.DateField(auto_now_add=True) purchased = models.BooleanField(default=False) def __str__(self): return self.name class Delivery(models.Model): address = models.CharField(max_length=256) city = models.CharField(max_length=128) country = models.CharField(max_length=128) zip_code = models.IntegerField() #gotta change that one to charfield phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'." " Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=16, blank=False) delivered = models.BooleanField(default=False) product = models.ForeignKey(Product) my serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ( "name", "price", ) class ProductDeliverySerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = Delivery fields = ( "address", "city", "country", "zip_code", "phone_number", "product", ) def create(self, validated_data): product_data = validated_data.pop('product') print(validated_data, product_data) product = Product.objects.create(**product_data) delivery = Delivery.objects.create(product=product, **validated_data) return delivery When i do print/test validated data it actually shows that 'form'/POST is complete {'address': 'address here', 'city': 'City is β¦ -
Move POST parameters to query parameters before processing request
I need to move the request.POST parameters to the request.query_params QueryDict. Is there an accepted way of doing this? Background I am using datatables, with a DRF backend, which is working fine. I am moving the application to integration and ... it stops working. Why? Request URL too big (on the 7000 characters range) - which was not a problem in my dev host ... So, I am looking for a solution to that problem. The first solution is to use POST instead of GET. That works, but the library integrating DRF with datatables is not processing the form parameters of the POST request. Because of that, filtering, pagination and so on have stopped working. The easiest thing to solve this would be to put the form parameters into the query parameters, and let the backend process the request as if it was a normal GET request. This is what I am doing at the moment: class DataViewSet(viewsets.ModelViewSet): queryset = Data.objects.all() serializer_class = DataSerializer def create(self, request, *args, **kwargs): # DataTable uses a lot of parameters which do not fit into a normal URL. To get the data we need to do POST, # so that the parameters are sent β¦