Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - creaing a custom model admin form field, passing the model instance to set a read only attribute
I know you can set readonly_fields in a model's admin.py but I am trying to make a field read only dependent upon it's (saved) value in the database. I can create a custom field Class, but am unable to pass the value of the model instance so I can achieve the above. Eg class MytypeField(models.CharField): def __init__(self,*args,**kwargs): PAGE_LAYOUT_CHOICES = ( ('column1','One Column'), ('column2','Two Columns') ) kwargs['max_length'] = 7 kwargs['choices'] = PAGE_LAYOUT_CHOICES kwargs['default'] = 'column1' super(MytypeField,self).__init__(*args,**kwargs) And in the model layout = MytypeField() Is there a way to do this in admin.py rather than in the model itself? I can't pass the model instance to this custom class, and I'm sure that's not the way to do it anyway! Many thanks! -
How to send customized response if the unauthroized credentials were provided in django rest
How to send customized response if the unauthroized credentials were provided in django rest class StockList(APIView): permission_classes = [IsAuthenticated] def get(self,request): stocks = Stock.objects.all() serializer = StockSerializer(stocks,many=True) return Response({'user': serializer.data,'post': serializer.data}) def post(self): pass Here when I Hit url by invalid credentials i get 401 error on deveploment server. But i want to send customized response on client using json. any suggestions are welcomed. Thank you.. -
Django Formsets with ModelBase Not rendering the Checkbox default but a drop down list instead
I need to create a required checkbox option if no_new_item exists. I am using the model.NullBoolean field, which, according to Django docs should render the checkbox widget. Instead I am getting a drop down list with 'Yes' and 'No.' How would I go about creating the checkbox in the Base model.Models? /models.py class StoreNightlyReport(models.Model): store_number = models.ForeignKey('Stores', verbose_name='Store Number', max_length=20, null=True) date = models.DateField(null=True) #managers = models.ManyToManyField('auth.User', blank=True, null=True) def __str__(self): return self.store_number.store_number class StoreNightlyReportsBase(models.Model): store_nightly_report = models.ForeignKey(StoreNightlyReport) no_new_item = models.NullBooleanField(verbose_name='No New Items', default=True) customer = models.CharField(verbose_name='Customer Name', max_length=20, null=True) class Meta: abstract = True /forms.py class StoreNightlyReportsForm(ModelForm): class Meta: model = StoreNightlyReport widgets = {'date': SelectDateWidget()} exclude = () def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(StoreNightlyReportsForm, self).__init__(*args, **kwargs) if 'store_number' in self.fields: if not user.is_superuser: self.fields['store_number'].queryset = Stores.objects.filter(managers=user) /views.py class StoresNightlyReportsNewLoansCreate(CreateView): template_name = 'reports/storenightlyreport_form.html' model = StoreNightlyReport form_class = forms.StoreNightlyReportsForm success_url = reverse_lazy('reports:storenightlyreports') def get_form(self, form_class=None): form_class = self.get_form_class() form = form_class(self.request.POST or None, user=self.request.user) self.formsets = {} StoreNightlyReportsNewLoanFormSet = inlineformset_factory(StoreNightlyReport, StoreNightlyReportsNewLoan, exclude=[], extra=1) self.formsets['new_loan'] = StoreNightlyReportsNewLoanFormSet(self.request.POST or None) def get_context_data(self, **kwargs): data = super(StoresNightlyReportsNewLoansCreate, self).get_context_data(**kwargs) data['formset_new_loan'] = self.formsets['new_loan'] return data def get_context_data(self, **kwargs): data = super(StoresNightlyReportsNewLoansCreate, self).get_context_data(**kwargs) #formset_renewal = StoreNightlyReportsRenewalFormSet() data['formset_new_loan'] = self.formsets['new_loan'] return super(StoresNightlyReportsNewLoansCreate, self).form_invalid(form) /template.html … -
Removing reference to BaseClass in Django Migrations
I have the following models. class ReservedSlug(models.Model): slug = models.SlugField( max_length=80, unique=True, ) class SubClass(ReservedSlug): name = models.CharField( max_length=100, ) Now what happens in the database is that the SubClass has a foreign key relation to the ReservedSlug Base class of the following: CONSTRAINT reservedslug_ptr_id_f48f6b16_fk_utils_reservedslug_id FOREIGN KEY (reservedslug_ptr_id) REFERENCES public.utils_reservedslug (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED And at the same time, it is setting the primary key to the following: CONSTRAINT subclass_newsubclass_pkey PRIMARY KEY (reservedslug_ptr_id), My goal is to remove the reference to Reserved slug all together and just have reservedslug_ptr_id be an IntegerField in SubClass model. This is one of the ways I have tried inside the migrations: database_operations = [ migrations.AlterField( model_name="subclass", name="reservedslug_ptr_id", field = models.ForeignKey('reservedslug_ptr_id', db_constraint=False, db_index=True, null=False) ) ] state_operations = [ migrations.AlterField( model_name='subclass', name='reservedslug_ptr', field=models.IntegerField(db_index=True, null=False), ) ] operations = [ migrations.SeparateDatabaseAndState( database_operations=database_operations, state_operations=state_operations And no matter what I do, I cannot get it to the way I want to get it. I keep getting this error: django.core.exceptions.FieldError: Auto-generated field 'reservedslug_ptr' in class 'SubClass' for parent_link to base class 'ReservedSlug' clashes with declared field of the same name. I have been at this for the past 2 … -
how to configure nginx to indicate ’/‘ to my main page
i have a django project and my web static files are at 'web/' directory here is the structure: ➜ web git:(ycw.alpha) tree -L 4 . └── forward ├── asserts │ ├── img │ │ ├── background │ │ ├── qr │ │ └── thumb │ └── style │ ├── css │ └── sass ├── index.html ├── package.json ├── script.js ├── source └── unit i have configured Nginx conf and i want nginx to directly indicate to 'web/forward/index.html' when i request my own website 'http://example.com' i do the thing above like this: location / { index index.html root /path/to/my/django/project/; } location /index.html { alias /path/to/my/django/project/web/forward/index.html; } it indeed directly redirects to 'index.html', but the question is there are some references in 'index.html' to some static files such as img or css and the paths are relative paths like './asserts/style/css/index.css' so consequently these files are not found as 404 how can i configure it correctly? -
Expanding the list of relationship field arguments
I’m looking for a way to expand the list of relationship field arguments, e.g. to add a predicate for each direction of the relation. My first guess was to define a subclass of models.ForeignKey class NewForeignKey(models.ForeignKey): def __init__(self, parent, pred='', reverse_pred='', **kwargs): self.pred = pred, self.reverse_pred = reverse_pred super(NewForeignKey, self).__init__(parent, **kwargs) Then use this subclass in my models as in the following example: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = NewForeignKey (Question, pred="refers to", reverse_pred="includes", on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) Initially, this seemed to work fine, however, when I tried to pass it through makemigrations it failed with the following error message: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 445, in execute output = self.handle(*args, **options) File "C:\Python27\lib\site-packages\django\core\management\commands\makemigrations.py", line 99, in handle ProjectState.from_apps(apps), File "C:\Python27\lib\site-packages\django\db\migrations\state.py", line 178, in from_apps model_state = ModelState.from_model(model) File "C:\Python27\lib\site-packages\django\db\migrations\state.py", line 354, in from_model e, TypeError: Couldn't reconstruct field question on polls.Choice: __init__() takes at least 2 arguments (1 given) Digging deeper, I couldn’t find an explanation why … -
Django is not redirecting after receiving a POST request
I'm trying to send some values from the front-end to a Django app. I want to manipulate those values and then redirect to another view, but it seems that Django is not redirecting nor rendering nothing. This is my urls.py from django.conf.urls import url from . import settings from personality_form import views urlpatterns = [ url(r'^$', views.home, name="home"), url(r'^apiLogin/(?P<_id>\d+)$', views.apiLogin,name="apiLogin"), url(r'^formulario/(?P<_id>\d+)$', views.formulario, name="formulario"), ] This is my views.py from django.shortcuts import render, redirect from personality_form.models import * from personality_form.forms import * from django.views.decorators.csrf import csrf_exempt def home(request): return render(request, 'index.html') def formulario(request, _id): if (request.method == 'POST'): form = personalityForm(request.POST) else: form = personalityForm() return render(request, 'formulario.html', {'form': form}) @csrf_exempt def apiLogin(request, _id): if (request.method == 'POST'): return redirect('formulario/'+_id) And this is the javascript function that I'm using to send the POST request from the front. function test() { var http = new XMLHttpRequest(); http.open('POST', '/apiLogin/1234', true); http.setRequestHeader('Content-type', 'application/json'); var payload = {userID: "1234", access: "4567"}; var params = JSON.stringify(payload); // Send request http.send(params); } I've tried to send the POST to apiLogin view. I check that it is entering on that view but when I try to redirect to formulario view, it enters on formulario code but don't seems … -
message is not shown
I am making a web site by seeing Django tutorial.But message in results.html is not shown. results.html is {% extends "polls/base.html" %} {% load bootstrap3 %} {% block contents %} <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'polls:polls_detail' question.id %}">Vote again?</a> {% endblock contents %} results.html inherits base.html. base.html is {% load staticfiles %} {% load bootstrap3 %} <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../../favicon.ico"> <title>Starter Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <style type="text/css"> body { padding-top: 50px; } </style> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{% url 'index' %}">Tutorial</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class="{% block nav_polls %}{% endblock %}"><a href="{% url 'polls:index' %}">polls</a></li> <li class=""><a href="{% url 'admin:index' %}">admin</a></li> </ul> </div><!--/.nav-collapse --> </div> </nav> <div class="container"> {% if messages %} {% bootstrap_messages messages %} {% endif %} {% … -
Django - How to get the maximum value after distinct on fields
I have those models: class Product(models.Model): name = CharField(max_length=128) other_fields... class Price(models.Model): product = ForeignKey(Product) store = CharField(max_length=128) price = DecimalField(max_digits=10, decimal_places=2) date = DateField() the products table contains some products (...) and the price table gets update each time a store change the product price. I want to get the latest price ("current price") from every store, and then get the maximum and the average price of each product. I tried it first for one product: Price.objects.filter(product__id=42).order_by('store','-date').distinct('store').annotate(Max('price')) but got: NotImplementedError: annotate() + distinct(fields) is not implemented. I also tried to add order_by('-price') to get the maximum, but it ordered first by date, so it's useless. Any suggestion how to do it without multiple queries and nasty loops? -
Retrofit Android miss some response from server(not all)
when I try to send some request in a for loop, log of the server is ok(all request recieved and all responses sent) but in Android Studio Emulator i have only some those responses not all. here My request code private void updateDatabase(JsonArray arrayJson) { final List<JsonObject> user_cars= new ArrayList<JsonObject>(); for(JsonElement a : arrayJson){ String carID = a.getAsString(); carID=carID.substring(0,carID.length()-1); int index = carID.lastIndexOf('/'); Integer id =Integer.parseInt(carID.substring(index+1)); Log.e("Index",id.toString()); AdaClient client = ServiceGenerator.createService(AdaClient.class); Call<JsonObject> call = client.retrieveCars(id); call.enqueue(new Callback<JsonObject>() { @Override public void onResponse(Call<JsonObject> call, retrofit2.Response<JsonObject> response) { Log.e("user_cars",response.body().toString()); user_cars.add(response.body()); } @Override public void onFailure(Call<JsonObject> call, Throwable t) { } }); } The request are 7 as you can see in my log id = 08-29 12:55:20.497 19654-19654/it.uniroma3.adateam.ada E/Index: 1 08-29 12:55:20.499 19654-19654/it.uniroma3.adateam.ada E/Index: 2 08-29 12:55:20.505 19654-19654/it.uniroma3.adateam.ada E/Index: 3 08-29 12:55:20.506 19654-19654/it.uniroma3.adateam.ada E/Index: 4 08-29 12:55:20.508 19654-19654/it.uniroma3.adateam.ada E/Index: 5 08-29 12:55:20.511 19654-19654/it.uniroma3.adateam.ada E/Index: 8 08-29 12:55:20.512 19654-19654/it.uniroma3.adateam.ada E/Index: 9 Here logcat 08-29 12:55:20.748 19654-19654/it.uniroma3.adateam.ada E/user_cars: {"id":1,"owner":"raul@raul.raul","car":"http://10.10.10.10:8080/cars/60546/","total_km":null,"tires_km":null,"oil_km":null,"breaks_km":null,"engine_km":null,"insurance_date":null,"vehicle_tax_date":null} 08-29 12:55:20.826 19654-19654/it.uniroma3.adateam.ada E/user_cars: {"id":3,"owner":"raul@raul.raul","car":"http://10.10.10.10:8080/cars/60550/","total_km":null,"tires_km":null,"oil_km":null,"breaks_km":null,"engine_km":null,"insurance_date":null,"vehicle_tax_date":null} 08-29 12:55:20.855 19654-19654/it.uniroma3.adateam.ada E/user_cars: {"id":4,"owner":"raul@raul.raul","car":"http://10.10.10.10:8080/cars/60551/","total_km":null,"tires_km":null,"oil_km":null,"breaks_km":null,"engine_km":null,"insurance_date":null,"vehicle_tax_date":null} 08-29 12:55:20.863 19654-19654/it.uniroma3.adateam.ada E/user_cars: {"id":2,"owner":"raul@raul.raul","car":"http://10.10.10.10:8080/cars/60548/","total_km":null,"tires_km":null,"oil_km":null,"breaks_km":null,"engine_km":null,"insurance_date":null,"vehicle_tax_date":null} 08-29 12:55:20.915 19654-19654/it.uniroma3.adateam.ada E/user_cars: {"id":8,"owner":"raul@raul.raul","car":"http://10.10.10.10:8080/cars/60550/","total_km":null,"tires_km":null,"oil_km":null,"breaks_km":null,"engine_km":null,"insurance_date":null,"vehicle_tax_date":null} 08-29 12:55:20.936 19654-19654/it.uniroma3.adateam.ada E/user_cars: {"id":9,"owner":"raul@raul.raul","car":"http://10.10.10.10:8080/cars/60547/","total_km":null,"tires_km":null,"oil_km":null,"breaks_km":null,"engine_km":null,"insurance_date":null,"vehicle_tax_date":null} Here my server response : [29/Aug/2017 12:55:36] "GET /user-cars/1/ HTTP/1.1" 200 [29/Aug/2017 12:55:36] "GET /user-cars/3/ HTTP/1.1" 200 [29/Aug/2017 12:55:36] "GET … -
Django send mail works locally but on server it's not sending mail
I have a normally working smpt mail working on localhost but when i put the app on server its not sending mails. I think there is some configuration problem. I am using apace2 ubuntu server 14.04 and i have placed my project in /var/www/ folder. I am forcing https connection by configuring 000-default.conf file Settings.py TEMPLATE_DEBUG =False SECRET_KEY = **key** DEBUG = False ALLOWED_HOSTS = [**allowed hosts**] import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = ( 'index', 'aboutus', 'aboutus.team', 'aboutus.careers', 'aboutus.locations', 'aboutus.board', 'domainsec', 'projects', 'downloads', 'contactus', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) X_FRAME_OPTIONS = 'DENY' ROOT_URLCONF = **urls** TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'antef.wsgi.application' # Email EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = **emailid** EMAIL_HOST_PASSWORD = **password** EMAIL_PORT = 587 EMAIL_USE_TLS = True apache_config file: <VirtualHost *:443> RewriteEngine On RewriteCond %{HTTP_HOST} ^www\. [NC] RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301] RewriteEngine on SetEnvIfNoCase User-Agent ^libwww-perl bad_bot BrowserMatchNoCase SpammerRobot bad_bot BrowserMatchNoCase SecurityHoleRobot bad_bot <Location /> Order allow,deny Allow from all Deny from env=bad_bot </Location> <IfModule mod_headers.c> Header set … -
Determine if an M2M field has a custom through model
With a custom through model for an M2M relationship, .add(), .create() and .remove() are disabled. At the moment, I attempt to use .add() (or whatever) and catch and deal with AttributeError for those custom M2M relationships. Is there an 'official' way to identify a custom through model, using the Meta API or otherwise? At this stage in my processing I would rather treat all custom through relationships as generically as possible (rather than lots of if m2m_field.related.through == FooBar statements) (Django 1.8, but if there's a solution for a later version we will be upgrading before long.) -
Django - getting list of values after annotating a queryset
I have a Django code like this: max_id_qs = qs1.values('parent__id').\ annotate(max_id = Max('id'),).\ values_list('max_id', flat = True) The problem is that when I use max_id_qs in a filter like this: rs = qs2.filter(id__in = max_id_qs) the query transforms into a MySQL query of the following structure: select ... from ... where ... and id in (select max(id) from ...) whereas the intended result should be select ... from ... where ... and id in [2342, 233, 663, ...] In other words, I get subquery instead of list of integers in the MySQL query which slows down the lookup dramatically. What surprises me is that I thought that Django's values_list returns a list of values. So the question, how should I rewrite the code to achieve the desired MySQL query with integers instead of id in (select ... from...) subquery -
Create instances of subclasses at application start
I need to create an instance for all subclasses of a given class, where __subclass__() is still empty due to application loading. tl; dr Is there a module (built-in or pypi) which finds all subclasses of a specified class before they are instantiated, probably by using static code inspection? Example There is one class that sets up a data structure at the very start of application loading, lets assume: autostart_this.py class Foo: """ Setup data structure, instances must be created at application start and before models.py is loaded. """ def __init__(module_name): print(module_name) def some_method(): raise NotImplementedError() Several modules define a specific data structure, extending from given class: some_module.py class CustomizedFoo(Foo): def some_method(): pass CustomizedFoo('some_module') My hook into the application start shows an empty list of subclasses for Foo, as autostart_this.py is loaded before any other module: Foo.__subclasses__() [] If the application is fully loaded, the subclasses are available - but then it's too late to add the data structure... Assumptions There is a naming convention for files implementing subclasses of Foo. I probably need to find all modules where Foo is imported, and need to do so in a more or less 'static' way (i.e. using https://docs.python.org/3/library/inspect.html or https://docs.python.org/3/library/pyclbr.html). Question … -
Django iterate over check boxes
Trying to dynamically create a list of checkboxes that when selected will perform an action. I have the checkboxes created as expected, and I have an action working as expected. I can't seem to get a hold of the correct box(s) to perform the action on. For example, when I click the third box, or the second and third box the action is always performed on the first box. I have verified that the POST data is correctly passing the checked boxes prefix's and form name's, but somehow I am telling the code that if a box is checked, perform the action on the first instance rather than on the checked box or boxes. Here is what I have: forms.py class remove_resource(forms.Form): active = forms.BooleanField(label_suffix='', label='', required=False) views.py def edit_project_resource (request, offset): list_resources = Allocation.objects.filter(project_id=offset).filter(active=True).order_by('user_id').distinct('user_id') display = {} for r in list_resources: check = remove_resource(prefix = r.pk) display[r.user_id] = (check, r.user_id) if request.method == 'POST': check = remove_resource(request.POST, prefix = r.pk) if check.is_valid(): if request.POST.get(check, True): Allocation.objects.filter(project_id=offset).filter(user_id = r.user_id).update(active=False) return HttpResponseRedirect('/project_profile/%s/' % offset) -
Django uploaded file in admin list
I've read several posts here on this problem and have tried many of the approaches - in the end I returned to the Django docs. I'm trying to get the uploaded image to appear in the admin list... My models.py (based on info from here: Django Docs) from django.db import models from django.contrib import admin from django.utils.html import format_html class File(models.Model): file = models.ImageField() description = models.CharField(max_length=200) def __str__(self): return self.description def image_tag(self): return format_html( '<img src="{}" />', self.file ) class FileAdmin(admin.ModelAdmin): list_display = ('image_tag', 'description') This, sadly, does nothing however... I have tried putting arbitrary HTML as well - just in case file url is bad...but nothing changes. Any ideas would be greatly appreciated - quite frustrated with this now. -
Fake JSONField using Factory Boy
I have a field in my model with JSONField Type(MYSQL Implementation). I want to fake the data for this field using FactoryBoy Faker. How can I achieve this? -
ProgrammingError when trying to add Keycloak authentication to OpenShift Django template
I am trying to add Keycloak authentication to the Django template code basis in OpenShift (https://github.com/openshift/django-ex) I have been following the blog post http://blog.jonharrington.org/static/integrate-django-with-keycloak/ and I am documenting my progress at: https://github.com/OpenRiskNet/home/blob/master/openshift/django_keycloak_example.md The thing is that I ahve made it almost all the way but when I try to view a page from Django that needs authentication I get an eror message about: relation "bossoidc_keycloak" does not exist LINE 1: INSERT INTO "bossoidc_keycloak" ("user_id", "UID") VALUES (1... which indicate that something is wrong in the database. When I look in the logs for stuff related to migrations I see: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, welcome Running migrations: No migrations to apply. Which first made me happy because it clearly states Apply all migrations and then made me worried because it doesn't list the bossoidc to be migrated. Why is it not migrating this stuff? -
Django annotate not working with two apps
I have two applications in my project. Models.py of first app has model: class repair(models.Model): site = models.ForeignKey('second.site') price = models.FloatField() … Models.py of second app has model: class site(models.Model): name = models.CharField(max_length = 250) When I do in shell: repair.objects.values('site__name').annotate(sum_site=Sum('summ')) i am getting all items of repair model with their prices: <QuerySet [{'site__name': 'Site-1', 'count_ss': 1500.0}, {'site__name': 'Site-2', 'count_ss': 1500.0}, {'site__name': 'Site-1', 'count_ss': 800.0}, {'site__name': 'Site-1', 'count_ss': 230.0}, {'site__name': 'Site-2', 'count_ss': 90.0}]> How I can group by site? -
Django Validating email address and username in forms.py
I am trying to check whether the entered in email address and username to form has ever been used. The code works fine for when the email address and username do not exist in the database however I get an invalid form in views.py otherwise. I would like a text validation error message to appear in the form when the user attempts to submit. forms.py class UpdateProfileForm(ModelForm): class Meta: model = UpdatedInformation fields = ('email', 'username',) def clean_email(self): username = self.cleaned_data.get('username') email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).exclude(username=username).count(): raise forms.ValidationError('This email address is already in use. Please supply a different email address.') return email def clean_username(self): username = self.cleaned_data.get('username') email = self.cleaned_data.get('email') if email and User.objects.filter(username=username).exclude(email=email).count(): raise forms.ValidationError( 'This username is already in use. Please supply a different username.') return username views.py @login_required def update_profile(request, slug): args = {} #Check that the correct user has requested if not slug == slugify(request.user.username): raise Http404 #Get the user object from the database by its username user = get_object_or_404(User, username=request.user.username) #Create a new updated information object to initialise the form with update_profile_obj = UpdatedInformation() update_profile_obj.username = user.username update_profile_obj.email = user.email if request.method == 'POST': form = UpdateProfileForm(request.POST) print(form.errors) if form.is_valid(): #Get the updated_info … -
immutable variable for unit tests
I have some test cases which rely on the same variable foo from unittest import TestCase class TestFoo(TestCase): def setUp(self): self.foo = {'key_a': aaa, 'key_b': bbb} def test_a(self): self.foo['key_a'] = 'ccc' self.assertEqual(self.foo['key_a'], 'ccc') def test_b(self): self.assertEqual(self.foo['key_a'], 'aaa') the issue I have is that once I change the value in test_a to self.foo['key_a'] = 'ccc' the value "stays" this way for all subsequent tests. the assert in test_b fails because the value of self.foo['key_a'] remains at 'ccc' how do I have to write the test case so foo is {'key_a': aaa, 'key_b': bbb} in all tests? -
In django models how to update a particular column after creating
I have models.py as below, class members(models.Model): id = models.AutoField(primary_key=True) HID = models.IntegerField(blank=False,unique=True) owner = models.ForeignKey(User) member_name = models.CharField(max_length=25, blank=False, default='') father_name = models.CharField(max_length=25, blank=False, default='') wife_name = models.CharField(max_length=25, blank=False, default='') Now in the above HID value is entered manually each time. When there is a new member is getting inserted I am planing to enter my previous member HID value after which the insertion should be done, so that all entries after that should be updated with HID + 1. I tried to implement this with linked list model like having one more with next_HID= , but here the issue is my insertion is very less like yearly one or 2 but query is more so then each time this list has to be created by doing query. so I thought to update the HID number each time after insert. Please let me know how can I run an update query after every insert in django models for the above purpose -
Validating data in bootstrap modal using JQuery not working
I have been stuck on this issue since a week. I am not able to validate bootstrap modal using jQuery validator function. I have searched lots of stuff, also I have used exactly the same method as mentioned in here: How to correctly validate a modal form . I have been using django framework. Here is my HTML code: <div class="modal fade" id="myModalHorizontal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <form class="form-horizontal" id="myForm" role="form" action="{% url 'apply:add' %}" method="POST"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">&times;</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title" id="myModalLabel"> Apply Leave </h4> </div> <!-- Modal Body --> <div class="modal-body"> <div class="form-group"> <label class="control-label col-sm-3" for="e_id">Employee-Id</label> <div class="col-sm-9"> <select class="form-control" id="e_id" name="e_id" class="required"> {% for entry in emp_data %} <option value="{{ entry.emp_id }}">{{ entry.emp_id }} - {{ entry.emp_name}} </option> {% endfor %} </select> </div> </div> <style> .datepicker { z-index: 1600 !important; border-color: black; } </style> <div class="form-group"> <label class=" control-label col-sm-3" for="s_dt">Start Date</label> <div class="col-sm-9" > <input type='text' class="form-control" id="s_dt" placeholder="Start Date" name="s_dt"/> </div> </div> <div class="form-group"> <label class="control-label col-sm-3" for="e_dt">End Date</label> <div class="col-sm-9" > <input type='text' class="form-control" id="e_dt" placeholder="End Date" name="e_dt" require/> </div> </div> <p class="col-sm-9 col-sm-offset-3" > … -
Building an app for all platforms
What is best? android studio or ionic or something else to build an app in less time and that can be easily built and also it should be available for all users -
how to use multiple settings files in django in live server
I am a beginner in django and i have a website which i have used the sites framework to make it use the same code and database for multiple sites but i can't handle this in the live server, i have a settings file with different SITE_ID for every instance of this site. This is my wsgi.py code which i have to point the DJANGO_SETTINGS_MODULE to the current site settings file but how can i make it dynamic with the current site settings file? import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() What am i missing ? Can any one help me ? thanks.