Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pass additional data via POST from django template submit
Using Django template to display a table of input text. But in the view only input out of this table are present in the request.POST. Dynamically created input are not available in the POST. test.html <form class="form-horizontal" method="post" enctype='multipart/form-data' id="subscription-form"> .... .... <tbody class="draggable-column"> {% for product in products %} <tr> <td class="hidden-xs">{{forloop.counter}}</td> <td class="hidden-xs">{{product.title}}</td> <td class="hidden-xs">{{product.weight}}</td> <td class="" >{{product.yearly_consumption}}</td> <td><input type="text" id="{{product.id}}_jan" data-id="{{product.id}}_jan" class="user-action"></td> <td><input type="text" id="{{product.id}}_feb" data-id="{{product.id}}_feb" class="user-action"></td> <td><input type="text" id="{{product.id}}_mar" data-id="{{product.id}}_mar" class="user-action"></td> ...... ...... <td><input type="text" id="{{product.id}}_total" data-id="{{product.id}}_total" readonly="readonly" class="total-quantity"></td> </tr> <input type="hidden" value="{{product.weight}}" id="{{product.id}}_weight"> <input type="hidden" value="{{product.is_winter}}" id="{{product.id}}_winter"> {% endfor %} </tbody> .... .... </form> This table input are not avalable in the POST of django view. How could make this available in the POST? -
How to use inheritance in Django Templates
Respected All: I want to use the feature of reusability of the Django templates As i wrote in base.html <title>{% block title %}{% trans 'Main Page title' %}{% endblock %}</title> And my otherfile.html is this {% block title %}Other file Title{% endblock %} I want to Set the title without useing tags in otherfile.html is it possible? -
Q: Django Channels on Elastic Beanstalk (aws)
I have a Django(2.0.2) app I deployed successfully to ebs. I implemented websockets with Channels(2.0.2) + Redis(4) and swapped to an Application Load Balancer following this guide: https://medium.com/@abhishek.mv1995/setting-up-django-channels-on-aws-elastic-beanstalk-716fd5a49c4a. Up until recently everything was working just fine but a few days ago I started getting 502 errors when trying to connect to my websockets. failed: Error during WebSocket handshake: Unexpected response code: 502 My supervisor config: [program:daphne] command=/opt/python/run/venv/bin/daphne -b 0.0.0.0 -p 5000 bang.asgi:application directory=/opt/python/current/app user=ec2-user numprocs=1 stdout_logfile=/var/log/stdout_daphne.log stderr_logfile=/var/log/stderr_daphne.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 environment=$djangoenv [program:worker] command=/opt/python/run/venv/bin/python manage.py runworker websocket directory=/opt/python/current/app/src user=ec2-user process_name=%(program_name)s_%(process_num)02d numprocs=4 stdout_logfile=/var/log/stdout_worker.log stderr_logfile=/var/log/stderr_worker.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 environment=$djangoenv Load Balancer config: option_settings: aws:elbv2:listener:80: DefaultProcess: http ListenerEnabled: 'true' Protocol: HTTP aws:elasticbeanstalk:environment:process:http: Port: '5000' Protocol: HTTP On localhost everything works fine but currently on aws I can't figure out how to get the websockets to work again. I read that in Channels 2 you no longer need to runworker so I have it removed currently. When I ssh into my eb instance and run sudo /usr/local/bin/supervisorctl -c /opt/python/etc/supervisord.conf status and netstat -antpl I seem to confirm everything is working fine: daphne RUNNING pid 4760, uptime 1:10:11 httpd RUNNING pid 4582, uptime 1:10:17 Proto Recv-Q … -
Getting web session from last.fm api
I'm trying to get web session from last.fm API using method auth.getSession in Django but it is giving me invalid method signature supplied . I don't know what I'm doing wrong. I'm receiving token correctly. {"Error":13,"message":"Invalid method signature supplied"} This is my code: token = request.GET["token"] session="api_key%smethodauth.getSessiontoken%s" %(API_KEY.encode('utf-8'),token.encode('utf-8')) api_signa=hashlib.md5(session.encode()).hexdigest() url="http://ws.audioscrobbler.com/2.0/?method=auth.getSession&api_key=%s &token=%s &api_sig=%s" %(API_KEY,token,api_signa) return HttpResponseRedirect(url) -
How to maintain form parameters when new url is called
I have a form shown in the first picture below and a set of navpills shown in the second picture. When I click the navpill it calls a url that either ends with 'charts' or 'tables'. Whenever I press the navpill though all the values in the form are cleared to the original template. I need them to stay so when I switch from charts to tables I get the same information. i.e. if there is a fund type selected I want it to still be their if I click on tables when I was previously on charts. I tried using "GET" as such: min_year = request.GET.get('year_min', None) if not min_year: min_year = '2013' But that only works if I submit the form. As soon as I click on one of the values it resets. Here is the html for the "Start Year" box: <h6>Start Year</h6> <div class="form-group"> {{form.year_min|attr:"class:form-control"}} </div> And here is the form: CHOICES = ( ('1998', '1998'), ('1999', '1999'), ('2001', '2001'), ('2002', '2002'), ('2003', '2003'), ('2004', '2004'), ('2005', '2005'), ('2006', '2006'), ('2007', '2007'), ('2008', '2008'), ('2009', '2009'), ('2010', '2010'), ('2011', '2011'), ('2012', '2012'), ('2013', '2013'), ('2014', '2014'), ('2015', '2015'), ('2016', '2016'), ('2017', '2017'), ('2018', '2018'), ) year_min … -
django celery,something wrong with shared_task
i use django-rest-framework and celery this ims my views.py # GET /server/test/<para>/ class Testcelery(APIView): def test(self): print(celery_test()) def get(self, request, para, format=None): print('test') self.test() # result = add.delay(4, 4) # print(result.id) result = OrderedDict() result['result'] = 'taskid' result['code'] = status.HTTP_200_OK result['message'] = 'success' return Response(result, status=status.HTTP_200_OK) this is a simple celery task @shared_task() def celery_test(): print('celerytest') return True i debug the django it can goes to the test method but the program stuck at the next step in call in local.py where the error happens the debug stops there,and shows like this debug result -
Pycharm Import Error
guys. I'm trying to develop a program to create excel file with using xlwt. I have used pip install xlwt to install it. In Terminal, it can be imported with no error. And the Django project could be run correctly. But in pycharm, it shows import error when running the Django project. The error code shows below: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/checks/urls.py", line 19, in check_resolver for pattern in resolver.url_patterns: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/motion/Documents/GitHub/motion-op/motion/urls.py", line 4, in <module> from product.views import home File "/Users/motion/Documents/GitHub/motion-op/product/views.py", line 22, in <module> from .ProductService import ProductService File "/Users/motion/Documents/GitHub/motion-op/product/ProductService.py", line 13, in <module> from method import ProductServicePO,send_email, SaveImg, create_excel_file File "/Users/motion/Documents/GitHub/motion-op/product/method/create_excel_file.py", line 2, in <module> import xlwt ImportError: … -
Django chain multiple queries in view
I have three models: Course Assignment Term A course has a ManyToManyField which accesses Django's default User in a field called student, and a ForeignKey with term An assignment has a ForeignKey with course When a user logs in to the page, I would like to show them something like this bootstrap collapse card where I can display each term and the corresponding classes with which the student is enrolled. I am able to access all of the courses in which the student is enrolled, I'm just having difficulty with figuring out the query to select the terms. I've tried using 'select_related' with no luck although I may be using it incorrectly. So far I've got course_list = Course.objects.filter(students = request.user).select_related('term'). Is there a way to acquire all of the terms and their corresponding courses so that I can display them in the way I'd like? If not, should I be modeling my database in a different way? -
Database not storing JSON variable
I have an django app in which I am trying to store the gridster widget configuration in the form of JSON variable to database.But when I click"Update" button on my webpage my database does not stores any value. My JS Code which sends serial value to database var gridster; var $color_picker = $('#color_picker'); var URL = "{% url 'save-grid' %}"; gridster = $(".gridster ul").gridster({ widget_base_dimensions: [80, 80], widget_margins: [5, 5], helper: 'clone', resize: { enabled: true } }).data('gridster'); $(".add-button").on("click", function() { $('#test').click(); $('#test').on('change', function(e) { var test = document.getElementById('test'); if (!test) { alert("Um, couldn't find the fileinput element."); } else if (!test.files) { alert("This browser doesn't seem to support the `files` property of file inputs."); } else if (!test.files[0]) { alert("Please select a file before clicking 'Load'"); } else { file = test.files[0]; console.log(file); fr = new FileReader(); fr.readAsDataURL(file); fr.onload = function() { var data = fr.result; // data <-- in this var you have the file data in Base64 format callbackAddButton(data); test.value = ''; $('#test').replaceWith($('#test').clone()) }; } }) }); function callbackAddButton(file) { // get selected color value var color = $color_picker.val(); // build the widget, including a class for the selected color value var $widget = $('<li>', { 'class': … -
HTML in django widgets?
I'm creating a project in Django. I use ModelForms quite a bit to get user data. I'd like to add help text to each of my fields. How I'd like those to appear is like this: A tiny "?" image to the right of the input, then a popup that appears when the "?" is hovered over. I have this working in CSS and HTML. What I need to do is put in an tag before every instance of help_text being displayed, along with some other HTML. From my understanding I can do this by subclassing widgets, but I've seen in several places that I shouldn't add HTML to widgets? It seems much less elegant to stop using the ModelForm auto-rendering in all my templates and instead re-write it using loops and then put the HTML in there. The help_text is never going to be controlled by anyone except me, so I don't believe XSS is a concern. Am I missing something? Is there an easier/better way to do this? Also, if someone could point me to a guide on this with an explanation, it would be much appreciated. -
Why do I get an operational error, saying a database is read-only?
I'm using SQLite with Django, have been for a few months. Today I was about to do replace a table with an updated version, which I regarded as tricky so I took a full backup of my entire project. At a certain point, I started getting this error -- with subtext "attempt to write a readonly database." This made no sense to me, but after trying and failing to fix it, I renamed the entire directory and restored the morning backup. No help. I tried a different browser. No help. I logged in with an incognito session. No help. I logged in with an incognito session and a different Django user account. No help. In all cases, it's the login that fails. And it fails just after I enter the password. The site is still in debug mode, and I've pasted the error info to http://dpaste.com/2NS9ZMJ.txt I have no idea how to get my site working again, if a complete restore of the project directory won't do it. -
Modifying a field in serializers.ModelSerializer Class imported from an external library
I'm trying to override/modify a class XXXSerializer(serializers.ModelSerializer) object defined in an external library that I am including in the installed_apps configuration of my settings.py. class XXXSerializer(serializers.ModelSerializer): username = serializers.CharField(validators=[UniqueValidator(queryset=User.objects.all())]) email = serializers.CharField(validators=[UniqueValidator(queryset=User.objects.all())],default='') class Meta: model = User exclude = [ 'is_superuser', 'is_staff', 'is_active', 'content_type', 'groups', 'user_permissions', 'account_id', ] As shown above, the email is required to be unique in their definition. However, I do not want to require it to be unique. My question is therefore, what is the best way to override this field? Some thoughts/attempts: Copy the entire library directly into my project, and take out the validator there. I think this would definitely work but may not be an optimal solution? Somehow override it by defining another YYYSerializer with my desired property, and use import external_library sys.module['external_library.XXXSerializer'] = YYYSerializer. However, I'm not exactly sure about 1. where to put this piece of code, 2. the proper syntax, 3. whether this would even work in an ideal situation. When I put it in settings.py or some __init__ files, it returns Apps aren't loaded yet error - probably because the external_library hasn't been loaded yet. Any suggestions would be appreciated! -
How do I change the url back to mysite.com in django after loging in the user?
I have two apps in my django project. After loging the user in through "visit" app I redirect to "mainapp". How ever my url patter becomes something like this : mysite/accounts/profile/ If I try specifying in urls.py I get redirected to "visit" app. How do I reset my url visit/views.py def profile(request): return HttpResponseRedirect(reverse("main:home")) main/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'accounts/profile', views.home, name='home'), ] main/views.py def home(request): return render(request, 'main/home.html') -
django import csv in several related models
For a web application of naturalistic data for the study of bats (http://www.dbchiro.org), I need to be able to propose a view allowing to import files from spreadsheets (csv, ods files , xls) into database. To import this data into a single table, no problem, several extensions exist (django-import-export or django-csvimport in particular). On the other hand, my need is more particular because my naturalistic data is distributed in several distinct tables (not counting the tables of dictionaries). Here is the schematic diagram: Model Place Place (a locality is a site with unique x / y coordinates as a building). 1-n Model Session (one data = one date and one inventory method by locality) 1-n Model Sighting (one data = one species per session) 1-n Model CountDetail (one data = 1 detail for a species: eg number of males, number of females, etc.) What I would like to get is the ability to import the data of a session with a single csv file that would populate the last two models: Observations (Sighting) and for each observation (each species observed), its detailed data (CountDetail). Is there one or more simple solutions (I'm doing well but I'm not a great python … -
Django save rows of html table selected by checkbox in the database
I have a table in my models which the stocks are saving in it and its name is Stocks this table is desplayed in a template and i want to put a checkbox beside each row to save the checked row in another table of the model here ismy model.py : class Stocks(models.Model): user=models.ForeignKey(User, null=True) name=models.CharField(max_length=128,verbose_name=_('stockname')) number=models.CharField(blank=True,null=True,max_length=64,verbose_name=_('number')) brand=models.CharField(max_length=64, validators=[ RegexValidator(regex='^[A-Z]*$',message=_(u'brand must be in Capital letter'),)] ,verbose_name=_('brand')) comment=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('comment')) price=models.PositiveIntegerField(blank=True,null=True,verbose_name=_('price')) date=models.DateTimeField(auto_now_add = True,verbose_name=_('date')) confirm=models.CharField(choices=checking,max_length=12,verbose_name=_('confirmation'), default=_('pending')) def __str__(self): return str(self.id) class Meta: verbose_name=_('Stock') verbose_name_plural=_('Stocks') def get_absolute_url(self): return reverse('BallbearingSite:mystocks' ) class SellerDesktop(models.Model): seller=models.OneToOneField(User, related_name='seller', blank=True, null=True) buyer=models.OneToOneField(User, related_name='buyer', blank=True, null=True) stock=models.ForeignKey(Stocks, related_name='stocktoseller', blank=True, null=True) def __str__(self): return str(self.seller) + '-' + str(self.buyer) class Meta: verbose_name=_('SellerDesktop') verbose_name_plural=_('SellerDesktop') and the Template : <form method="post"> {% csrf_token %} <table id="example" class="table table-list-search table-responsive table-hover table-striped" width="100%"> {% for item in myst %} <td><input type="checkbox" name="sendtoseller" value="{{ item.id }}"></td> <td>{{ item.user.profile.companyname}}</td> <td>{{ item.name }}</td> <td>{{ item.brand }}</td> <td>{{ item.number }}</td> <td>{{ item.pasvand }}</td> <td>{{ item.comment }}</td> <td>{{ item.price }}</td> <td>{{ item.date|timesince }}</td> </tr> {% endfor %} </table> <div style="text-align: center; margin-top:0.5cm; margin-bottom:1cm;"> <input type="submit" name="toseller" value="Submit to seller " style="color:red; width:100%;"/> </div> </form> and the view : def allstocks_view(request): if request.method=='POST': tosave = request.POST.getlist('sendtoseller') stockid=Stocks.objects.filter(id=tosave) SellerDesktop.objects.create(buyer=request.user,stock=stockid) stocks_list=Stocks.objects.all().filter(confirm=_('approved') ).order_by('-date') … -
How to redirect to another app directory after loging in django?
I have two app directories in my django project named "visit" and "main". After Loging the user in through visit app, how do I change the app directory to another main i;e how to display templates from another app (excuse my english) ? visit/views.py : from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect from django import forms from .forms import UserRegistrationForm def index(request): return render(request, 'visit/index.html', context=None) def profile(request): # I need to change directory form here return render(request, 'main/templates/main/profile.html') def registration(request): if request.method == "POST": form = UserRegistrationForm(request.POST) if form.is_valid(): formObj = form.cleaned_data username = formObj["username"] name = formObj["name"] email = formObj["email"] password = formObj["password"] if not (User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists()): User.objects.create_user(username, email, password) user = authenticate(username=username, name=name, password=password) login(request, user) return HttpResponseRedirect('/profile/') else: form = UserRegistrationForm() return render(request, 'visit/registration/register.html', {'form': form}) -
No module named 'django.urls'
I'm trying to set up django-registration-redux, but when I set up the url (r '^ accounts /', include ('registration.backends.default.urls')) in the urls.py file and I try to access any page I get the following error message: ModuleNotFoundError No module named 'django.urls' I have checked the manual several times and everything is in order. What is missing? Where is my mistake? urls.py file """p110 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls.static import static from django.conf.urls import include, url from django.contrib import admin from boletin import views from .views import about urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', views.index, name='index'), url(r'^contact/$', views.contact, name='contact'), url(r'^about/$', about, name='about'), url(r'^accounts/', include('registration.backends.default.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) -
Django queryset result is wrong for the test
My model is: class AndroidOffer(models.Model): name = models.CharField(max_length=128, db_index=True) # ... countries = models.ManyToManyField(Country) And the following code (I skipped previous filtering): active_offers = active_offers.filter(countries__in=[country]) It generates this SQL query: SELECT "offers_androidoffer"."id", "offers_androidoffer"."name", "offers_androidoffer"."title", "offers_androidoffer"."is_for_android", "offers_androidoffer"."is_for_ios", "offers_androidoffer"."url", "offers_androidoffer"."icon", "offers_androidoffer"."cost", "offers_androidoffer"."quantity", "offers_androidoffer"."hourly_completions", "offers_androidoffer"."is_active", "offers_androidoffer"."description", "offers_androidoffer"."comment", "offers_androidoffer"."priority", "offers_androidoffer"."offer_type", "offers_androidoffer"."package_name", "offers_androidoffer"."is_search_install", "offers_androidoffer"."search_query", "offers_androidoffer"."launches" FROM "offers_androidoffer" INNER JOIN "offers_androidoffer_platform_versions" ON ("offers_androidoffer"."id" = "offers_androidoffer_platform_versions"."androidoffer_id") INNER JOIN "offers_androidoffer_countries" ON ("offers_androidoffer"."id" = "offers_androidoffer_countries"."androidoffer_id") WHERE ("offers_androidoffer"."is_active" = True AND "offers_androidoffer"."quantity" > 0 AND NOT ("offers_androidoffer"."id" IN (SELECT U0."offer_id" FROM "offers_androidofferstate" U0 WHERE (U0."device_id" = 1 AND (U0."state" = 3 OR U0."state" = 4)))) AND NOT ("offers_androidoffer"."package_name" IN (SELECT V0."package_name" FROM "applications_app" V0 INNER JOIN "applications_deviceapp" V1 ON (V0."id" = V1."app_id") WHERE (V1."device_id" IN (SELECT U0."device_id" FROM "users_userdevice" U0 WHERE U0."user_id" = 2) AND NOT (V0."package_name" IN (SELECT U2."package_name" FROM "offers_androidofferstate" U0 INNER JOIN "offers_androidoffer" U2 ON (U0."offer_id" = U2."id") WHERE (U0."device_id" = 1 AND (U0."state" = 0 OR U0."state" = 1 OR U0."state" = 2))))))) AND "offers_androidoffer_platform_versions"."platformversion_id" IN (14) AND "offers_androidoffer_countries"."country_id" IN (6252001)) ORDER BY "offers_androidoffer"."priority" DESC; If I run this query in Postgresql console, it will return 0 rows, but active_offers has 4 results (all rows in table), like if I remove AND "offers_androidoffer_countries"."country_id" IN (6252001) statement. … -
How to pull a html template on a $.post call, and include data?
I have the following code on one Django HTML template that when it runs it pulls the html from another template and loads it into the #container element. $.get('/form/', function(form){ $('#container').html(form); }); So if I was to follow the same thought process I have this code on another page in which I need to use a POST request instead of GET. $.post( '/form/results/', {item: $('#item-selector').val(), csrfmiddlewaretoken: csrftoken}, function(data){ $('#container').html(data) } ) So what I'm trying to get the post request to do is to pull the html from the url and insert it into the #container element but I can't get it to work. If you need any more information just comment below and I will add it. -
What is an example use case of using primaryfieldserializer in django rest framework?
I had a goal, to link cities and their neighborhoods together in a request response in a nested serializer. Neighborhoods have a Foriegn key to cities. for clarity here are my models and serializer originally used. class SearchCity(models.Model): city = models.CharField(max_length=200) class SearchNeighborhood(models.Model): city = models.ForeignKey(SearchCity, on_delete=models.CASCADE) neighborhood = models.CharField(max_length=200) class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer): searchneighborhood_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = SearchCity fields = ('city','searchneighborhood_set') read_only_fields =('city', 'searchneighborhood_set') but that returned only the neighborhood primary keys with the cities not a full city object. This: city: "Chicago" searchneighborhood_set: 0: 5 1: 4 2: 3 city: "New York" searchneighborhood_set: 0: 8 1: 7 2: 6 instead of what it should be, this: city: Chicago searchneighborhood_set: 0: {pk: 5, neighborhood: 'River North} .... I got the above request, not by using primarykeyrelatedserializer but by using the serializer used for seralizing neighborhood objects which looks like this: class SearchNeighborhoodSerializer(serializers.ModelSerializer): class Meta: model = SearchNeighborhood fields = ('pk','neighborhood') so now replace the primarykeyrealatedserializer with my neighborhood one and the proper nested serailzer is this: class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer): searchneighborhood_set = SearchNeighborhoodSerializer(many=True, read_only=True) class Meta: model = SearchCity fields = ('city','searchneighborhood_set') read_only_fields =('city', 'searchneighborhood_set') so this begs the question, what is an actual use case for the primarykeyrelated … -
relation "django_admin_log" already exists
when i try to run python manage.py migrate i run into following error Upon running python manage.py run migrations it says no changes detected. and when i runserver it gives me warning that i have unapplied migrations as well.i have been searching internet for two hours but got not solution. Someone knowing the solution please share :) -
How to add django Group field to a Customer User Register
i used this Code in serializer.py group = Group.objects.get() group.user_set.add(self.object) it work fine when the Group Field have just one item and added in DB with no problem. But when i add more than one item in The Group List Field i am getting an Error: get() returned more than one Group -- it returned 2! what can i do ? Image:For one item Work Fine Image:With More than one i am getting This Error This is My Full Code: from rest_framework import serializers from . import models from django.contrib.auth import get_user_model from django.contrib.auth.models import Group User = get_user_model() class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) confirm_password = serializers.CharField(write_only=True) def validate(self, data): if not data.get('password') or not data.get('confirm_password'): raise serializers.ValidationError("Please enter a password and ""confirm it.") if data.get('password') != data.get('confirm_password'): raise serializers.ValidationError("Those passwords don't match.") return data def create(self, validated_data): user = get_user_model().objects.create( username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], email=validated_data['email'] ) group = Group.objects.get() group.user_set.add(self.object) user.set_password(validated_data['password']) user.save() return user class Meta: model = get_user_model() fields = ( 'username', 'password', 'confirm_password', 'first_name', 'last_name', 'email', 'groups', ) -
Django middleware for consuming an external api
Here's the deal, I need to consume an API and every time I perform a request a header needs to be appended, I've checked the middleware documentation but this is only working for incoming requests, is there anything that can be used in this situation. -
What is main use of queryset.in_bulk in Django framework?
I'm curious, what is use cases for queryset's in_bulk method? -
django/python logging with gunicorn: how does django logging work with gunicorn
I have a Django/Python application deployed(using gunicorn) with 9 workers with 5 thread each. Let's say if on a given time 45 requests are getting processed, Each thread is writing a lot of logs. How Django avoids writing logs for multiple threads at the same time? And how the file open and close works for each request(does this happen at each request, if yes, any other efficient way of logging)?