Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using supervisord for Celery for duplicate django projects
Goal On my server, I have two "identical" Django projects: one for staging and one for production (they both have their own MySQL database). I am trying to set up Celery using supervisord for both of these projects but I can't manage to do it. What I currently have Production: project-production/project/settings.py # Celery BROKER_URL = 'redis://localhost:6379/0' CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE CELERY_DEFAULT_QUEUE = 'production' CELERY_DEFAULT_ROUTING_KEY = 'production' Production: project-production/project/celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project', broker='redis://localhost:6379/0') app.config_from_object('project.settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) Production: project-production/supervisord.conf [program:celeryd0] directory=/absolute/path/to/project-production command=/absolute/path/to/project-production-virtualenv/bin/celery worker --app=project -l info stdout_logfile=/absolute/path/to/project-production-logs/celeryd.log stderr_logfile=/absolute/path/to/project-production-logs/celeryd.log autostart=true autorestart=true startsecs=10 stopwaitsecs=600 Staging: project-staging/project/settings.py # Celery BROKER_URL = 'redis://localhost:6379/1' CELERY_BROKER_URL = 'redis://localhost:6379/1' CELERY_RESULT_BACKEND = 'redis://localhost:6379/1' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE CELERY_DEFAULT_QUEUE = 'staging' CELERY_DEFAULT_ROUTING_KEY = 'staging' Staging: project-staging/project/celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project', broker='redis://localhost:6379/1') app.config_from_object('project.settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) Staging: project-staging/supervisord.conf [program:celeryd1] directory=/absolute/path/to/project-production command=/absolute/path/to/project-production-virtualenv/bin/celery worker --app=project -l info stdout_logfile=/absolute/path/to/project-staging-logs/celeryd.log stderr_logfile=/absolute/path/to/project-staging-logs/celeryd.log autostart=true autorestart=true startsecs=10 stopwaitsecs=600 What I tried Using different BROKER_URL for redis (/0 & /1), setting different CELERY_DEFAULT_QUEUE and CELERY_DEFAULT_ROUTING_KEY for each project, launching celery with or without supervisord. The problem Everything works fine when I use the supervisord command for … -
How to customize the "description" of the manytomany inline in the admin panel
I have those extremely simple models: class Activity(BaseModel): name = models.CharField(max_length=200, blank=True, null=True) class Person(BaseModel): activities = models.ManyToManyField('Activity', related_name='persons') In the admin.py I've made an inline for this and it works, like this: class PersonActivitiesInlineAdmin(admin.StackedInline): model = Profession.persons.through fk_name = 'person' class PersonAdmin(admin.ModelAdmin): inlines = (PersonActivitiesInlineAdmin, ) My problem is that the string describing the inline, in the admin interface, is like Profession: Person_activities object (831) Profession: Person_activities object (832) Profession: Person_activities object (835) Profession: Person_activities object (838) So how to customize the "description" of the manytomany inline in the admin panel? -
form is not valid to django why
the model: class authentifier(models.Model): matricule =models.CharField(max_length=254, blank=True, null=True) password = models.CharField(max_length=254, blank=True, null=True) nom =models.CharField(max_length=254, blank=True, null=True) prenom=models.CharField(max_length=254, blank=True, null=True) statut = models.CharField(max_length=254, blank=True, null=True) the code forms.py for authentification : from django import forms class UserLoginForm(forms.Form): print(666) matricule = forms.CharField(required=True , widget=forms.TextInput) password = forms.CharField(required=True , widget= forms.PasswordInput) template html : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width , initial- scales=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> </head> <body> <form> <form method="POST"> {% csrf_token %} <tr><th><label for="id_matricule">Matricule:</label></th><td><input type="text" name="matricule" id="Matricule"></td></tr> <tr><th><label for="id_password">Password:</label></th><td><input type="password" name="password" id="password"></td></tr> <input type="submit" value="Se Connecter"> </form> </body> </html> I found that form.is_valid() = false - but i have no idea how to get the reason WHY... i need to do authentification with matricule and password -
Django - dynamic form from Model with choices
I'm trying to implement dynamic form which displays a few option from database's choices. The form should display names of CASES (i.e. "Option 1") for given lawyer_id. For example: user selects lawyer with ID = 6 and this lawyer_id has "Option 1" and "Option 2" in LawyersSpec model. In the form I want to display only "Option 1" and "Option 2" as possible options. How can I achieve that? I have tried dynamic forms with overriding the queryset in init def __init__(self, *args, lawyer_id, **kwargs): super().__init__(*args, **kwargs) lawyer_spec = LawyersSpec.objects.filter(lawyer_id=lawyer_id) but it returns the whole name of the record from the database, not only the choice value. models.py class LawyersSpec(models.Model): lawyer_id = models.ForeignKey('MyUser', on_delete=models.PROTECT) lawyer_spec = models.SmallIntegerField(choices=CASES) CASES = ( (1, 'Option 1'), (2, 'Option 2'), (3, 'Option 3'), (4, 'Option 4'), ) -
VSCode debug Celery worker
After some frustrating days of running this, I'm needing to look at debugging a celery worker process in VSCode. This is following the suggested process in the Celery docs for creating a message handler, rather than pub/sub from the same application. The celery.py file: from __future__ import absolute_import, unicode_literals import os import json from celery import Celery, bootsteps from kombu import Consumer, Exchange, Queue dataFeedQueue = Queue('statistical_forecasting', Exchange('forecasting_event_bus', 'direct', durable=False), 'DataFeedUpdatedIntegrationEvent') # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') app = Celery('statistical_forecasting') app.config_from_object('django.conf:settings', namespace='CELERY') # Not required yet as handler is within this file #app.autodiscover_tasks() class DataFeedUpdatedHandler(bootsteps.ConsumerStep): def get_consumers(self, channel): return [Consumer(channel, queues=[dataFeedQueue], callbacks=[self.handle_message], accept=['json'])] def handle_message(self, body, message): event = json.loads(body) # removed for brevity, but at present echo's message content with print message.ack() app.steps['consumer'].add(DataFeedUpdatedHandler) My abbreviated project structure is: workspace - vscode - - launch.json config - __init__.py settings - local.py venv - celery.exe statistical_forecasting - __init__.py celery.py farms - __init__.py handlers.py # ultimately handler code should live here... From terminal with venv enable I'm running celery -A statistical_forecasting worker -l info which does appear to succeed in setting up and running the basic message handler. What I've tried thus far with VSCode … -
How to update ordering in a model
I have a model that sets the display order of books. I want users to be able to change the order books are displayed in, so I am not using book.id: class Books(models.Model): title = models.CharField(max_length=30) order = models.IntegerField(max_length=255, unique=True) This works ok, but say I have 3 books with order values 4, 5, 6 and I want to move the first book from position 4 to 5, pushing the second book from 5 to 4. If I try to do this in steps, then I trigger an error on changing the value of the first book to 5 because value 5 already exists for the second book (before it is changed to 4). How do I handle this use case? Is there some way to update records together, or a better way to handle ordering like this? -
Django how to display list users with some data in template
I want to display the list of users with some objects in 2 modelapps created. these are the models. first model: class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) indirizzo = models.CharField(max_length=50) citta = models.CharField(max_length=50) paese = models.CharField(max_length=50) ecap = models.CharField(max_length=4) descrizione = models.CharField(max_length=100, default='') image = models.ImageField(upload_to='profile_image', blank=True,null=True) second model: class Ore(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ore",null=True,) data = models.DateField(default=timezone.now) oret = models.CharField(max_length=3,) contrattiok = models.PositiveSmallIntegerField() contrattiko = models.PositiveSmallIntegerField(default=0,) nomecognome = models.CharField(max_length=100,blank=True) my view: def inizio(request): users = User.objects.all() return render (request, "base.html", {"users":users}) my template: {% for users in users %} <tbody> <tr> <td> <img src="{{ users.userprofile.image.url }}"class="thumbnail"> <h4 class="small font-weight-bold">{{users}}</h4> </td> <td><h4 class="small font-weight-bold">{{users.last_name}}</h4></td> <td class="text-center"> <h4 class="small font-weight-bold" class="btn btn-primary btn-circle">{{ users.ore.contrattiok }}</h4> <<<<<(does not work) </td> </tr> {% endfor %} -
How many Apps can i use in one Django Project
i have a Django Project which i'm working on. Now the Project gets bigger. I think there will be in the end approximately 40 Apps. I'm not sure if this is too much Apps for one Django project? Maybe one of you have some Experience with large Projects? Thank you -
How to update code in dist folder in pyarmor?
I deployed a project using Pyarmor. I took a reference from the below link https://pyarmor.readthedocs.io/en/latest/project.html#managing-obfuscated-scripts-with-project. It is working fine.But,if i do any changes in my script file i'm unable to update the code. How can i update the code? -
Google Calendar API: writer access error when setting up events on someone's calendar
HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/some-domain.com/events?sendNotifications=true&alt=json returned "You need to have writer access to this calendar."> Hi. I'm getting this error when I try to set a calendar event from my service account via the calendar api. Can someone help figure what it means? Is it due to some access issues on end user's calendars? Or is it due to some limitation on my own service account? Please help. -
NoReverseMatchError 'Reverse for 'password_reset_confirm' not found.' In Django
I was following a Django tutorial series on youtube when I was stuck at a part where we can send an email to the user's email address to reset the password. I was using mostly Django's included functionality for it. I have created a url path in which the user can reset his password but Django somehow don't recognize it. Error: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. I'm guessing there is something wrong with my urls.py My Urls.py from django.conf.urls import url from django.contrib.auth import views as auth_view from django.urls import path app_name = "blog" urlpatterns = [ # for /blog/password-reset/ path('password-reset/', auth_view.PasswordResetView.as_view(template_name='blog/password_reset.html'), name="password_reset"), # for /blog/password-reset/done/ path('password-reset/done/', auth_view.PasswordResetDoneView.as_view(template_name='blog/password_reset_done.html'), name="password_reset_done"), # For /blog/password-reset-confirm/<uidb64>/<token>/ path('password-reset-confirm/<uidb64>/<token>/', auth_view.PasswordResetConfirmView.as_view(template_name='blog/password_reset_confirm.html'), name='password_reset_confirm'), ] My password_reset_confirm.html {% extends 'blog/base_for_log.html' %} {% load crispy_forms_tags %} {% block title %}Reset Password{% endblock %} {% block body %} <div class = "container"> <div class="content-section py-5"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Password Reset </legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type ="submit">Reset Password</button> </div> </form> </div> </div> {% endblock %} I expect the output to be ConnectionRefusedError But It's Showing A NoReserve Error. Thanks … -
Styling errors in the form
There is the following form. <form id="contact_form" class="get-in-touch-form" method="post" enctype="multipart/form-data"> {% csrf_token %} <h1 class="title {% if component.css_title_style %}{{ component.css_title_style }}{% endif %}"> {{ component.title }} </h1> <p class="subtitle {% if component.css_subtitle_style %}{{ component.css_subtitle_style }}{% endif %}"> {{ component.description }} </p> <div class="row"> <div class="col-sm-6"> <div class="input-wrapper"> {{ contact_form.name }} </div> <div class="input-wrapper"> {{ contact_form.email }} </div> <div class="input-wrapper"> {{ contact_form.phone }} </div> <div class="input-wrapper" style="position: relative;"> {{ contact_form.text }} <img id="clip" src="{% static 'images/clip.png' %}" style="position: absolute; left: 95%; top: 5%;" onclick="document.querySelector('#id_file').click()"> </div> <div class="input-wrapper" style="display: none"> {{ contact_form.file }} </div> <div class="input-wrapper"> <div class="col-md-5"> <div class="custom-checkbox"> {{ contact_form.nda }} <label for="checkbox1">Send me an NDA</label> </div> </div> <img src="/static/images/loader.svg" height="65" alt="Loading..." style="display: none;"> <input type="submit" value="Send" class="green-button"> </div> </div> <div class="col-sm-6"> <img src="{% static 'images/map_all.png' %}"> </div> </div> </form> When I submit it and errors occur, text is displayed near the field that generates the error in its usual form. How can I style this text? For example, to highlight this field somehow? I tried to do this through ajax, but it didn’t work. When I try to send a form containing errors to the server, I immediately get an error (for example, this field is required) and accordingly … -
How to fix 'ImportError: No module named search' error in django 1.8
I'm get an error when running "python manage.py makemigrations" Command in putty. please Help!!! thanks o lot from dslam.views import * File "/opt/PortMan/portman_web/dslam/views.py", line 16, in from django.contrib.postgres.search import SearchVector ImportError: No module named search when running "pip install django-contrib-postgres" Command, I,m Get This Message: "Requirement already satisfied: equirement already satisfied: /usr/local/lib/python2.7/dist-packages (0.0.1)" -
How to properly use django apphooks
below is my django cms apphook, its showing the app on the drop down but it doesn't hook the application to a page. the project is in django 2.1.11, python3.7.1 and django cms 3.6.0 I have tried to change the apphook file to cms_apps.py and cms_app.py . I I have tried this tutorial https://www.youtube.com/watch?v=Dj8dhgmzlFM&t=2903s. i would be happy if one can share a working manual for this procedure. from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool @apphook_pool.register # register the application class PeoplemanagerApphook(CMSApp): app_name = "peoplemanager" name = "People Application" def get_urls(self, page=None, language=None, **kwargs): return ["peoplemanager.urls"] the page loads but does not display the contents of the model -
Django Cookie Prefix to pass securityheaders.com
securityheaders.com fails my configurations with the following error: Set-Cookie There is no Cookie Prefix on this cookie. And this is the value of the cookie: Set-Cookie sessionid=123456789123456789123456789; expires=Thu, 12 Sep 2019 06:51:38 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Strict; Secure I have tried to add the cookie prefix with in settings.py: CSRF_COOKIE_NAME = '__Secure-csrftoken' But it seems to be a different paramater. I have search the documentation and that is all I could find, and seems to not be applicable. securityheaders.com on cookie prefixes states that it needs to start with __Secure- or __Host- -
Django FileField's upload_to not being called during tests
I have a models.py module that looks like this: def get_path(instance, filename): try: # Something except Exception: raise ValidationError("A very specific error message.") return f"path/to/{instance.pk}_{filename}" class FinalDocument(models.Model): # ... file = models.FileField(upload_to=get_path) class TempDocument(models.Model): # ... file = models.FileField() I have an endpoint that, among other things, grabs a file from a TempDocument instance and assigns it to an existing FinalDocument instance. In real life, this endpoint is failing with "A very specific error message". During tests, however, I cannot for the life of me reproduce this error. I have placed a breakpoint in the upload_to function and it is simply not called. I am assuming this has something to do with different testing vs production settings, but I haven't been able to figure out what. Any idea what I could be missing? -
Django raw query - connection.cursor() data is not showed
When I use Table.objects.raw(raw query), I can see data. When I use connection.cursor(), cursor.execute(same raw query), data is not showed in a HTML page. What's the cause? oracle 11g cx-Oracle 7.2.2 Django 1.11.22 #ORM raw query - It's OK. class UserList(ListView): query = 'select user_id, user_name from user' queryset = USER.objects.raw(query) context_object_name = 'user_list' template_name = 'user_list.html' # Problem - data is not showed in screen. class UserList(ListView): with connection.cursor() as cursor: cursor.execute('select user_id, user_name from user') queryset = cursor.fetchall() context_object_name = 'user_list' template_name = 'user_list.html' #user_list.html <h2>User List(ListView Sample)</h2> <table border="1" align="center"> <tr> <th scope="col">User ID</th> <th scope="col">User Name</th> </tr> {% for user in user_list %} <tr> <th width="200"><a href="http://127.0.0.1:8000/sec/userlist/{{ user.id }}/">{{ user.user_id }}</a></th> <th width="200">{{ user.user_name }}</th> </tr> {% endfor %} </table> No error messages. But data is not showed in a HTML page -
Adding extra field from other Model into Modelform along with giving attr
I'm making Modelform for custom doors ordering platform and i would like to insert additional field from different Model into my Modelform in order to use it's value to insert it as new attribute. So, this is how it looks like: Models.py from django.db import models class Door(models.Model): title = models.CharField(max_length=200, blank=False, null=False) excluded = models.CharField(max_length=50, default="", blank=True, null=False) class Order(models.Model): title = models.CharField(max_length=200, blank=False, null=False) door = models.ForeignKey('Door', verbose_name=u"Type", on_delete=models.CASCADE, default=1, blank=False, null=True) ... forms.py from .models import Door, Order class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['door',] #adding additional class using widgets widgets = { 'door': forms.RadioSelect(attrs={ 'class': 'radioselect' }), ... index.html <form id="d_form" method="POST"> {% csrf_token %} {{ ord_form.as_p }} <input type="submit" value="Order" class="btn btn-danger"> </form> Rendered output: <li> <label for="id_door_1"><input type="radio" name="door" value="2" class="radioselect" required id="id_door_1">some option </label> </li> Everything renders properly, hovewer i would like to add extra new attr into radio input containing it's value, based on field excluded=ITS VALUE from Door model. Expected render: <li> <label for="id_door_1"><input type="radio" excluded='ITS VALUE' name="door" value="2" class="radioselect" required id="id_door_1">some option </label> </li> How to insert it? -
How to integrate voice with django
I wrote a program in python which converts from speech to text and text to speech it was working fine in the console but how to integrate with a Django application instead of writing in a todo app I need speech powered, How to do? -
Failed to connect django with MS sql Server database
i have a django project that need to connect with MS SQL server database the problem is that once i runs the server it display this error : djago.db.utils.operationalError:('08001','[08001] [microsoft][odbc sql server driver]neither dsn nor server keyword supplied (0) (sqldriverconnect); [08001] [microsoft][odbc sql server driver] Invalid connection string attribute (0)') that what i did in settings.py: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'testDB', 'HOST': 'DESKTOP-LPD1575\\SQLEXPRESS', 'OPTIONS': { 'driver':'ODBC Driver 13 for SQL Server', } } } views.py from django.shortcuts import render import pyodbc from .models import Artist Create your views here. def connect(request): conn = pyodbc.connect( 'Driver={ODBC Driver 13 for SQL Server};' 'Server=ip address;' 'Database=testDB;' 'Trusted_Connection=no;' 'UID=test;' 'PWD=test;' ) cursor = conn.cursor() c = cursor.execute('SELECT "first name" FROM t1 WHERE id = 3 ') return render (request,'connect.html',{"c":c}) -
How to call a API Auth function from templates in Django
Im new in django, but i know that if u have a function you have to set it up in the models.py(correct me if wrong), and then for it to show it you have to call it from the templates. Im trying to make a django cms that connect to the Google Analytics API and export information. The first step is the authentification which the code is provided by google in HelloAnalytics.py : import argparse from apiclient.discovery import build import httplib2 from oauth2client import client from oauth2client import file from oauth2client import tools def get_service(api_name, api_version, scope, client_secrets_path): .... def get_first_profile_id(service): ... def get_results(service, profile_id): ... def print_results(results): ... def main(): service = get_service('analytics', 'v3', scope, 'client_secrets.json') profile = get_first_profile_id(service) print_results(get_results(service, profile)) if __name__ == '__main__': main() So basically i want to call the main() function , that takes no parameters, from a template so i can retrieve the information, i dont know if it is necesary to create a Class or not. I have tried to set it in the views.py but i dont have any results. Thanks in advance i tried creating a random class Main(models.Model): that have all these functions inside and from the views.py create an … -
Unable to display login user full details?
I'm new to django i unable to display current login user full details by username. when i will try with Exam.objects.get(username=username) i will get error query not exist and i will try with Exam.objects.all() it will display username only.Please tell me how can i display current login user profile details forms.py -------- from django import forms from testapp.models import Exam from django.contrib.auth.models import User from django.core import validators class ExamForm(forms.ModelForm): password = forms.CharField(max_length=32, widget=forms.PasswordInput) rpassword=forms.CharField(label='Re Enter Password',widget=forms.PasswordInput) first_name = forms.CharField(max_length=40, required=True) last_name = forms.CharField(max_length=40, required=True) phone = forms.IntegerField() date_of_birth=forms.DateTimeField(help_text='DD/MM/YYYY H:M',input_formats=['%d/%m/%Y %H:%M']) gender = forms.CharField(max_length=10, required=True) location = forms.CharField(max_length=40, required=True) photo = forms.ImageField(help_text="Upload image: ", required=False) class Meta: model = Exam fields = ('username','password','rpassword','first_name','last_name', 'email','date_of_birth','gender','photo','location','phone') views.py -------- def maas(request,maas_username_slug): context_dict = {} try: maas = Exam.objects.get(slug=maas_username_slug) context_dict['maas_username'] = maas.username context_dict['maas_username_slug'] = maas_username_slug context_dict['maas_phone'] = maas.phone context_dict['maas_firstname'] = maas.firstname context_dict['maas_lastname'] = maas.lastname context_dict['maas_location'] = maas.location context_dict['date_of_birth'] = maas.date_of_birth context_dict['maas_gender'] = maas.gender context_dict['photo'] = maas.photo context_dict['maas'] = maas except Exam.DoesNotExist: pass print(context_dict) return render(request, 'testapp/profile.html', {'context_dict':context_dict}) urls.py ------- urlpatterns = [ url(r'(?P<maas_username_slug>\w+)/$', views.maas, name='profile'), ] profile.html ------------ {%extends 'testApp/base.html'%} {%block body_block%} <h1>Profile page:</h1> <h1>{{maas_lastname}}</h1> <h1>{{maas_username}}</h1> {%endblock%} -
Django. Rest Framework. Nested relationships empty result
Need some advice. I set up seralization. There are no errors. But at the output I get empty tags. I broke my head, what am I doing wrong? models.py: class kv(models.Model): title = models.CharField(max_length=200) price = models.IntegerField() address = models.CharField(max_length=200) property_type = models.CharField(choices=realty_type_choices_admin, default='kv', max_length=200, blank=True) country = models.CharField(default='Россия', max_length=200) region = models.CharField(max_length=200) state = models.CharField(choices=state_choices_admin, default='DGO', max_length=200, blank=True, null=True) locality_name = models.CharField(max_length=200, blank=True, null=True) address_xml = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) serializers.py from rest_framework import serializers from listings.models import kv class kvSerializerLocation(serializers.ModelSerializer): class Meta: model = kv fields = ['country', 'region', 'state', 'locality_name', 'address_xml', 'city'] class kvSerializer(serializers.ModelSerializer): category = serializers.CharField(source='get_property_type_display') url = serializers.CharField(source='get_absolute_url', read_only=True) country = kvSerializerLocation() class Meta: model = kv fields = ['title', 'price', 'address', 'category', 'url', 'country'] views.py from listings.models import * from rest_framework import viewsets from rest_framework_xml.renderers import XMLRenderer from .serializers import kvSerializer class KvXMLRenderer(XMLRenderer): root_tag_name = 'feed' item_tag_name = 'offer' def _to_xml(self, xml, data): super()._to_xml(xml, data) class kvViewSet(viewsets.ModelViewSet): queryset = Kvartiry.objects.all().filter(is_published=True) serializer_class = kvSerializer renderer_classes = [KvXMLRenderer] Result: <country> <state/> <locality_name/> <address_xml/> <city/> </country> It’s strange. Tags are empty, there is no region tag at all Thank! -
Django form data isn't saving to database
i'm trying to allow a user to update their user profile with a city, description, website address etc. Using Django 2.0, I have two forms in one view: EditProfileForm (EPF) = Form for email, first and last name and password The EditProfileForm seems to be able to save data. However, EditUserProfile seems to not. EditUserProfile (EUP) = Form for further user info such as city, description, website address etc. When entering the data and submitting the form, the data for EUP form doesn't appear to save or update the user information I've also tried methods such as: if form_EUP.is_valid(): obj = form_EUP.save(commit=False) obj.user = request.user obj.save() and trying to create a similar custom save method to the format used in RegistrationForm but i've had no luck I'm a bit of a beginner to the django framework so any ideas would be much appreciated, cheers. views.py def edit_profile(request): if request.method == 'POST': form_EPF = EditProfileForm(request.POST, instance=request.user) form_EUP = EditUserProfile(request.POST, instance=request.user) if form_EPF.is_valid(): form_EPF.save() return redirect(reverse('accounts:view_profile')) if form_EUP.is_valid(): form_EUP.save() return redirect(reverse('accounts:view_profile')) else: form_EPF = EditProfileForm(instance=request.user) form_EUP = EditUserProfile(instance=request.user) args = {'form_EPF': form_EPF, "form_EUP": form_EUP} return render(request, 'accounts/edit_profile.html', args) forms.py class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ( … -
Clear the page section link from url after redirect
I'm getting deeper into a django, and I've come across an issue I'm not sure how to solve. I've managed to make a popup box using just html and css for my forms, so both the create and update form load onto one page, and i can access them using page section links. The issue i have is that when I create a new post, or update a post, the page section link stays in the URL and the popup form remains visible. I've tried adding action="." to the form but that seems to break my update form, and stops working; it just redirects back to my list view with the create form filled in with the updated information. my views.py def list_view(request): block_query = Block.objects.all() new_form_query = BlockForm(request.POST or None) if request.method == 'POST': if new_form_query.is_valid(): new_block = new_form_query.save() new_form_query = BlockForm() return redirect('bulkapp:one_view', slug_id=new_block.slug) return render(request, 'bulkapp/list.html', {'block_list': block_query, 'new_form': new_form_query}) def single_view(request, slug_id): single_block_query = get_object_or_404(Block, slug=slug_id) new_form_query = BlockForm(request.POST or None) update_form_query = BlockForm(request.POST or None, instance=single_block_query) if request.method == 'POST': if new_form_query.is_valid(): new_block = new_form_query.save() new_form_query = BlockForm() return redirect('bulkapp:one_block', slug_id=new_block.slug) if update_form_query.is_valid(): update_form_query.save() update_form_query = BlockForm() return redirect('bulkapp:one_view', slug_id=slug_id) return render(request, 'bulkapp/single.html', {'one_block': single_block_query, …