Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User permisssino in django vs Boolean field
I want to add extra features in website who have logged themselves in and have taken a subscription. How can I achieve it, I am confused. If I use custom permission they are model specific and I have a lot of app and many models in the project. I can use boolean field stating is_subcripted. But which way is perfect. Is there any other way to achieve it. I have three types of users one is not-logged-in, only logged in and logged in with subscribed version. -
django-allauth include twitter email on sociallogin extra_data
I was able to look at this feature and they say in order to include the email of a user from twitter i need to set SOCIALACCOUNT_QUERY_EMAIL = True Still not working, then i did SOCIALACCOUNT_PROVIDERS = { ... 'twitter': { 'SCOPE': ['email'], }, } Still got sociallogin.account.extra_data['email'] KeyError on twitter account login. This logic is done in pre_social_login signal @receiver(pre_social_login) def pre_social_login_(sender, request, sociallogin, **kwargs): email = sociallogin.account.extra_data['email'] -
How to access specific index in list in jinja2
Suppose there is list a=[1,2,3,4] in jinja2 and i want to access only 3rd index of list .In other languages we write a[2] but it shows error in jinja2. -
Load javascript files outside Django project
Today, I'm trying to add web pack to my Django project. I got webpack working fine. My goal is to load the new compiled javascript into my project's template/base.html. This is the static section for my setting.py file of my project. STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ #'django.core.context_processors.csrf' 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'debug': DEBUG, }, }, ] This is my webpack configuration: const path = require("path"); const webpack = require('webpack'); const BundleTracker = require('webpack-bundle-tracker'); const config = { context: __dirname, entry: { app: './webpack/assets/javascript/entry/app.js' }, output: { path: path.join(__dirname, 'public', 'assets'), publicPath: '/assets/', filename: "[name].js", }, module: { rules: [ { use: 'babel-loader', test: /\.js$/, exclude: /node_modules/ }, ] }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), ], resolve: { extensions: ['.js', '.json'], modules: ['./webpack/assets/javascript/', './vendor/assets/javascript', 'node_modules'] } }; module.exports = config; As you can tell from my web pack.config, I'm creating an app.js file inside Public/assets on my root directory folder. How can I add my public/assets folder to my static files, so I can add the following script on my project's folder templates/base.html? <script src="app.js"></script> The help … -
Django: validate integrity of model taking into account the order of fields?
This is my Symbol model for cryptocurrency: class Symbol(models.Model): currency = models.CharField(max_length=10) name_quote = models.CharField(max_length=10) class Meta: unique_together = ('currency', 'name_quote', ) The problem is that there are two kind symbols, one for BTC-ETH and ETH-BTC. The first one means, currency is BTC and the name of coin is ETH. Second one, vice versa. In this case, django recognizes both coins as the same one(because unique_together doesn't consider the order of field) so it occurs the IntegrityError. How can I implement this taking into account the order of fields? -
Django Multivaluefield Optional Fields
I have searched all over and all I can find is stuff from years ago and/or stuff that doesn't apply. I'm trying to add a MultiValueField to my form so people can easily type in one to three inputs. Only the first of these fields should be required, but the form validator is still requiring all three unless I make the whole thing optional (which it shouldn't be). Below is the code for my MultiWidget, MultiValueField, and form. I've tried removing everything from the field attributes except for required=False and it still required all of them. I tried setting require_all_fields=False in the form when I call the field instead of in the field __init__ and it still required all of them. I feel like I've read and read and read and there's very little information on how to implement this sort of thing. class ThreeNumFields(forms.MultiWidget): def __init__(self, attrs=None): self.widgets = [ forms.TextInput(), forms.TextInput(), forms.TextInput() ] super().__init__(self.widgets, attrs) def decompress(self, value): if value: return value.split(' ') return [None, None] class LocationMultiField(forms.MultiValueField): widget = ThreeNumFields() validators = [RegexValidator] def __init__(self): fields = ( forms.CharField( error_messages={'incomplete': 'Please enter at least one valid zip code.'}, validators=[ RegexValidator(r'^[0-9]{5}$', 'Enter a valid US zip code.'), ], … -
xmlrpclib.py with infusionsoft TypeError: cannot marshal None unless allow_none is enabled
Here is the error: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, callback_args, *callback_kwargs) File "/data/vhosts/nutritionfactors.com/nfi/user/views.py", line 199, in Register i.addTag(user) File "/data/vhosts/nutritionfactors.com/nfi/user/infusionsoftAPI.py", line 64, in addTag return self.infusionsoft.ContactService('addToGroup', user.infusionId, tag) File "/data/vhosts/nutritionfactors.com/nfi/libs/infusionsoft/library.py", line 17, in function return call(self.key, *args) File "/usr/lib/python2.7/xmlrpclib.py", line 1233, in call return self.__send(self.__name, args) File "/usr/lib/python2.7/xmlrpclib.py", line 1581, in __request allow_none=self.__allow_none) File "/usr/lib/python2.7/xmlrpclib.py", line 1086, in dumps data = m.dumps(params) File "/usr/lib/python2.7/xmlrpclib.py", line 633, in dumps dump(v, write) File "/usr/lib/python2.7/xmlrpclib.py", line 655, in __dump f(self, value, write) File "/usr/lib/python2.7/xmlrpclib.py", line 715, in dump_array dump(v, write) File "/usr/lib/python2.7/xmlrpclib.py", line 655, in __dump f(self, value, write) File "/usr/lib/python2.7/xmlrpclib.py", line 757, in dump_instance self.dump_struct(value.__dict__, write) File "/usr/lib/python2.7/xmlrpclib.py", line 736, in dump_struct dump(v, write) File "/usr/lib/python2.7/xmlrpclib.py", line 655, in __dump f(self, value, write) File "/usr/lib/python2.7/xmlrpclib.py", line 757, in dump_instance self.dump_struct(value.__dict__, write) File "/usr/lib/python2.7/xmlrpclib.py", line 736, in dump_struct dump(v, write) File "/usr/lib/python2.7/xmlrpclib.py", line 655, in __dump f(self, value, write) File "/usr/lib/python2.7/xmlrpclib.py", line 659, in dump_nil raise TypeError, "cannot marshal None unless allow_none is enabled" TypeError: cannot marshal None unless allow_none is enabled The code inside of infusionsoftAPI.py: import requests import json import hashlib from infusionsoft.library import * from django.conf import settings from django.core.mail import … -
How to maintain the get query param for all template page Django
I have written some adminview for request the data from user and based on that data i put query and populating the data on template. My question is how I have to request data from user once and render template. and till the next data asked. views.py class ReadView(AbstractAdminView): def get(self, request, *args, **kwargs): roll_no = request.GET['roll_no'] roll_obj1 = Roll.objects.get(student__profile=roll_no) return self.admin_render(request, template1, { 'roll_details':roll_obj1 }) class PlayView(AbstractAdminView): def get(self, request, *args, **kwargs): roll_no = request.GET['roll_no'] roll_obj2 = Sub.objects.get(sec__student=roll_no) return self.admin_render(request, template2, { 'roll_details':roll_obj2 }) urls.py {% if request.path == roll_detail %}{% endif %}<a href="{% url 'roll_detail'%}?roll_no={{roll_no}}">ROll Detail</a> {% if request.path == sub_detail %}{% endif %}<a href="{% url 'sub_detail'%}?roll_no={{roll_no}}">Sub Detail</a> SO, what I want, That I have request roll_no once and that should work for both urls template, and when moving from one url/tab to another then it should maintain the data of current roll_no till next roll_no to be entered. -
Django Fixtures: Importing Nested Models
New to Python and Django and trying to import a .json file. The JSON file is structured in such a way that each root-level object has a nested object within it. For example, the JSON is structured as: [ { "model": "testapp.Person", "pk": 1, "fields": { "firstName":"Jane", "lastname":"Doe", "haircolor":"black", "mailingaddress": { "streetaddress": "1214 Example St.", "city": "Silver Spring", "state": "MD", "zipcode": "20910" } } } ] And the python model definition is as follows: from django.db import models # Create your models here. class address(models.Model): streetaddress = models.CharField(max_length=200) city = models.CharField(max_length=200) state = models.CharField(max_length=5) zipcode = models.CharField(max_length=10) def __init__(self, streetaddress, city, state, zipcode): self.streetaddress = streetaddress self.city = city self.state = state self.zipcode = zipcode class Person(models.Model): firstName = models.CharField(max_length=200) lastname = models.CharField(max_length=200) haircolor = models.CharField(max_length=200) mailingaddress = address(streetaddress, city, state, zipcode) Getting an error when running python manage.py loaddata because, obviously, the init parameters streetaddress, city, state, zipcode don't exist in that context. How do I construct my model to dynamically generate those other objects? -
How to upload file to django 2.0 server via django-restframwork using Volley library in android?
my goal is create an app like whasapp or telegram(image only - no chats) i want to send a picture to my django server this is my model: class exchange(models.Model): sender=models.CharField(verbose_name="sender",max_length=11) reciever=models.CharField(verbose_name="reciever",max_length=11) img=models.CharField(verbose_name="imageAddress",max_length=150) createTime=models.TimeField( auto_now_add=True,auto_now=False) class users(models.Model): number=models.CharField(verbose_name="userNumber",max_length=11) name=models.CharField(verbose_name="name",max_length=40) createTime=models.TimeField( auto_now_add=True,auto_now=False) status=models.BooleanField(default=False) class SMS(models.Model): users_id=models.ForeignKey(users,on_delete=models.CASCADE,default=0) code=models.PositiveSmallIntegerField(verbose_name="randomCode") createTime=models.TimeField( auto_now_add=True,auto_now=False) status=models.BooleanField(default=False) exchange class ==> to store sender and reciever (phone number) img store image path on django server .image store in directory on server users class ==> for register users SMS class ==> for sms verificaion users like whatsup my serializer api : class exchangeSerializer(ModelSerializer): class Meta: model=exchange fields="__all__" class SMSSerializer(ModelSerializer): class Meta: models=SMS fields="__all__" class usersSerializer(ModelSerializer): class Meta: model=users fields="__all__" my views api : class exchangeShow(generics.ListAPIView): queryset=exchange.objects.all() serializer_class=exchangeSerializer class SMSShow(generics.ListAPIView): queryset=SMS.objects.all() serializer_class=SMSSerializer class usersShow(generics.ListAPIView): queryset=users.objects.all() serializer_class=usersSerializer class exchangeDetailShow(generics.RetrieveAPIView): queryset=exchange.objects.all() serializer_class=exchangeSerializer lookup_field='id' class exchangeDelete(generics.DestroyAPIView): queryset=exchange.objects.all() serializer_class=exchangeSerializer lookup_field='id' class exchangeCreate(generics.CreateAPIView): queryset=exchange.objects.all() serializer_class=exchangeSerializer class SMSCreate(generics.CreateAPIView): queryset=SMS.objects.all(); serializer_class=SMSSerializer; class usersCreate(generics.CreateAPIView): queryset=users.objects.all() serializer_class=usersSerializer and urls api: urlpatterns=[ path('exchange/',views.exchangeShow.as_view()), path('sms/',views.SMSShow.as_view()), path('users/',views.usersShow.as_view()), path('exchange/<int:id>/delete',views.exchangeDelete.as_view()), path('exchange/create',views.exchangeCreate.as_view()), path('sms/create',views.SMSCreate.as_view()), path('users/create',views.usersCreate.as_view()), ] in volley library how can i implement sms vertificaion in django-restframework how can i send image from android device to django and save it in a directory in server and store path it in exchange table (img) and show it in … -
Django ajax redirecting on form submission
I'm trying to return data with an ajax request on a form submission. My goal was too use two views, one too handle the template loading and the other to handle the POST request from the form. In the current state, the form is redirecting to the JSON that is in the callback. That makes sense as it's for the form action url is pointing, however, i want to just pass the data to the current page and not reload the page or be redirected to another page. Here is the code: user.html <form action="{% url 'ajax-user-post' %}" method="post"> {% csrf_token %} {% for user in users %} <input type="submit" name="name" value="{{ user }}"> {% endfor %} views.py def ajax_user(request): # get some data.. if request.METHOD == 'POST': user = request.POST['user'] user_data = User.objects.get(user=user) data = {'user_data': 'user_data'} return JsonResponse(data) def user(request): return render(request, 'user.html', context) urls.py url(r'^success/', user, name="user"), url(r'^ajax/user/', ajax_user, name="ajax-user-post") .js $('form').on('submit', function(){ var name = // the name of the user selected $.ajax({ type: "POST", dataType: "json", url: 'ajax/user/', data: { 'csrfmiddlewaretoken': csrftoken, 'name': name, 'form': $form.serialize() }, success:function(data) { // hide the current data console.log(data); displayUserData(data) } }) }); Thanks for the help in advance! -
Django model field verbose name in template
How would you approach getting a Field verbose name to show up in a template when you are iterating over the fields via a custom array? Suppose you have #models.py class Letter (models.Model): a = models.CharField(max_length=1, verbose_name=u'The Letter and Vowel A') b = models.CharField(verbose_name=u'The Letter and Consonant B') ... y = models.CharField(verbose_name=u'The Letter, Consonant, and sometimes Vowel Y') def vowel_array(self): return [self.a,self.e,self.i,self.o,self.u,self.y,] nothing special in the view: ... return render(request, 'app/view.html', { 'language' : language, 'letters' : letters, }) and in the template {% for letter in letters.vowel_array %} <div>{{letter.verbose_name}}</div> <!-- for 'a' => The Letter and Vowel A --> {% endfor %} My current implementation seems problematic? def vowel_array(self): return [ [self.a, self._meta.get_field('a').verbose_name.title()], [self.e, self._meta.get_field('e').verbose_name.title()], [self.i, self._meta.get_field('i').verbose_name.title()], [self.o, self._meta.get_field('o').verbose_name.title()], [self.u, self._meta.get_field('u').verbose_name.title()], [self.y, self._meta.get_field('y').verbose_name.title()] ] and {% for letter in letters.vowel_array %} <div>{{letter.1}}</div> <!-- for 'a' => The Letter and Vowel A --> {% endfor %} -
Anonymous User - Displaying User Information
I am trying to display my users information but I am getting anonymous user as my output; Anonymous User My code in my views.py is as follows; def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/account') else: form = RegistrationForm() args = {'form' : form} return render(request, 'accounts/register.html', args) def view_profile(request): args = {'user': request.user} return render (request, 'accounts/profile.html',args) I am over-riding the UserCreationForm, my code in forms.py is; class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = { 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' } def save(self,commit=True): user = super(RegistrationForm,self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user My profile.html where I want my profile information to be displayed is; {% block head %} <title> User Profile </title> {% endblock %} {% block body %} <div class="container"> <p> <h1> {{user}}</h1> <h3>First Name: {{user.first_name}}</h3> <h3>Last Name: {{user.last_name}}</h3> <h3>Email: {{user.email}}</h3> </p> </div> {% endblock %} Really not sure where I am going wrong any help is greatly appreciated. -
Not autocomplete django-autocomplete-light (Django)
I have my model called DetalleVenta: class DetalleVenta(models.Model): producto = models.ForeignKey(Producto,on_delete=models.CASCADE,verbose_name='Producto') cantidad = models.IntegerField(verbose_name='Cantidad') preciounit = models.DecimalField(decimal_places=2, max_digits=7, verbose_name='Precio unitario') subtotal = models.DecimalField(decimal_places=2, max_digits=7, verbose_name='Subtotal') venta = models.ForeignKey(Venta,on_delete=models.CASCADE, related_name='detalleventa', verbose_name='Venta') def __str__(self): return '{} - {}'.format(self.venta,self.producto) It has as a foreign key to the Producto model class Producto(models.Model): nombre = models.CharField(max_length=30,unique=True,verbose_name='Nombre de Producto:') precio = models.DecimalField(decimal_places=2, max_digits=7, verbose_name='Precio de Producto:') categoria = models.ForeignKey(Categoria,on_delete=models.CASCADE,verbose_name='Categoría:') def __str__(self): return self.nombre My view class ProductoAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Producto.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs My Url url(r'^producto-autocomplete/$',ProductoAutocomplete.as_view(),name='producto-autocomplete'), My form class DetalleForm(forms.ModelForm): class Meta: model = DetalleVenta fields = [ 'producto', 'cantidad', 'preciounit', 'subtotal', ] labels = { 'producto':'Producto', 'cantidad':'Cantidad', 'preciounit':'Prec.Unit.', 'subtotal':'Subtotal', } widgets = { 'producto':autocomplete.ModelSelect2(url='producto-autocomplete/', attrs={'class': 'form-control'}), 'cantidad':forms.NumberInput(attrs={'class':'form-control cantidad'}), 'preciounit':forms.NumberInput(attrs={'class':'form-control'}), 'subtotal':forms.NumberInput(attrs={'class':'form-control subtotal', 'readonly':True}), } DetalleFormSet = inlineformset_factory(Venta, DetalleVenta, form=DetalleForm, extra=1) These are the steps that the official documentation says, but I can not see the autocomplete field. Something missing? Excuse the ignorance. But it's the first time I use this library. My template {% extends 'base/base.html' %} {% load static %} {% block titulo%} Registrar venta {%endblock%} {% block contenido %} <div class="col-md-12"> <form method="post">{% csrf_token %} <div class="col-md-4 form-group"> <label class="font-weight-bold" for="{{form.cliente.name}}">{{form.cliente.label}}</label> {{form.cliente}} </div> <h4 class="text-left">Detalle de venta: </h4> … -
add data to my Json in django
This is how my JSON data looks like {"id": 50, "first_digit": "2", "second_digit": "1", "calculate": "Addition"} I want to add extra data "result":"3" to my JSON this is my view def calc(request): if request.method == 'POST': first_number = request.POST['first number'] second_number = request.POST['second number'] operation = request.POST['operation'] result = do_calc(operation, first_number, second_number) # how to pass the result to my tempelate value = Calculation.objects.create( first_digit=first_number, second_digit=second_number, calculate=operation ) data = model_to_dict(value) return JsonResponse(data) Can anyone help me with it -
Docker + Gunicorn + Nginx + Django: redirect non-www to www on AWS Route 53
I have a Docker + Gunicorn + Nginx + Django setup on AWS EC2 and Route 53. Right now I want to redirect mydomain.com to www.mydomain.com. Is it appropriate to do a redirect in a Nginx configuration? Or are there are better solutions. Here is docker-compose-yml, using gunicorn to start the Django server. version: '2' services: nginx: image: nginx:latest container_name: dj_nginx ports: - "80:8000" - "443:443" volumes: - ./src/my_project/static:/static - ./src:/src - ./config/nginx:/etc/nginx/conf.d depends_on: - web web: build: . container_name: dj_web command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn my_project.wsgi -b 0.0.0.0:8000" depends_on: - db volumes: - ./src:/src - ./apps/django_rapid:/src/my_project/django_rapid expose: - "8000" db: image: postgres:latest container_name: dj_db Here is my Nginx Conf upstream web { ip_hash; server web:8000; } # portal server { listen 8000; location / { proxy_pass http://web/; } location /media { alias /media; # your Django project media files - amend as required } location /static { alias /static; # your Django project static files - amend as required } server_name localhost; } # portal (https) server { listen 443; server_name localhost; ssl on; ssl_certificate /etc/nginx/conf.d/mynginx.crt; ssl_certificate_key /etc/nginx/conf.d/mynginx.key; location /media { alias /media; # your Django project media files - amend as … -
How to make field unique with other models
I have 3 different models, and they all have index field (small positive integer number). How to make them unique with each other? I was trying to override save model in models.py, and this is work pretty good, except ValidationError exception. It redirect me to the error page, and if i turn Debug=False, it will nothing show me at all, just "error 500" or something like that. It would be great if this validation show message in admin's page, without refreshing. Maybe someone know how to validate this properly, or how to make this in other way? -
Python + Django: Trouble with setting up mkvirtualenv on macOS
I’m trying to dabble around with Python and Django and am getting stuck on what is probably a dumb issue. I’m using macOS and have installed Python v 3.6.4 I'm trying to follow the instructions per this Mozilla article: [https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/development_environment][1] I only know enough terminal commands to be dangerous (which is why I'm learning) and I'm very much a Python n00b, so please be nice. :) My process: 1 which python » /usr/local/bin/python note, somewhere along the way I did a Symlink ln -s /usr/local/bin/python3 /usr/local/bin/python 2 python3 -V » Python 3.6.4 3 sudo -H pip3 install virtualenvwrapper » Requirement already satisfied: virtualenvwrapper in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages Requirement already satisfied: stevedore in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from virtualenvwrapper) Requirement already satisfied: virtualenv in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from virtualenvwrapper) Requirement already satisfied: virtualenv-clone in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from virtualenvwrapper) Requirement already satisfied: pbr!=2.1.0,>=2.0.0 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from stevedore->virtualenvwrapper) Requirement already satisfied: six>=1.10.0 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from stevedore->virtualenvwrapper) 4 nano .bash_profile » Add following: » export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3 ## is this the issue? export PROJECT_HOME=$HOME/Devel source /usr/local/bin/virtualenvwrapper.sh 5 mkvirtualenv my_django_environment » Running virtualenv with interpreter /usr/local/bin/python Using base prefix '/usr/local/bin/../../../Library/Frameworks/Python.framework/Versions/3.6' New python executable in /Users/myuser/.virtualenvs/my_django_environment/bin/python ERROR: The executable /Users/myuser/.virtualenvs/my_django_environment/bin/python is not functioning ERROR: It thinks sys.prefix is '/Library/Frameworks/Python.framework/Versions/3.6' (should be '/Users/myuser/.virtualenvs/my_django_environment') ERROR: … -
python virtual environment change
I am a beginner for django framework. I am working on multiple tutorial projects. According to best practices , I use different virtual environments for different projects. I have a problem. When I want to switch to another project , even through I deactivate virtual environment of closed project , my browser still looks to the virtual environment that I deactivated. So , I can not display my new project at http://127.0.0.1:8000/ . It still display the older one. Can you please show me the way? Thanks. -
How to make related dropdown search filter with Django
So for a while I had trouble with this... I have more models like: Faculty, Department, Study Programme and Courses. Now, based on these models I want to show specific courses. Like for faculty of biology, department of sciences, study programme of science, I want to list all courses in that study programme, specific to the department, specific to faculty. I want to make each of this in a dropdown and then to display results on page. I did some research and found something about using Ajax, but I don't know how to use that thing. Considering the attached models, how should I do this ? class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default='') name = models.CharField(max_length=50) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) slug = models.SlugField(max_length=140, unique=True) class StudyProgramme(models.Model): department = models.ForeignKey('Department', on_delete=models.CASCADE) name = models.CharField(max_length=50) studies_type = models.IntegerField(choices=((0, "Bachelor Studies"), (1, "Master Studies"), (2, "PhD Studies"), (3, "Integrated Studies")), default=0) duration = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) class Department(models.Model): faculty = models.ForeignKey('Faculty', on_delete=models.CASCADE) name = models.CharField(max_length=50) class Faculty(models.Model): name = models.CharField(max_length=50) -
Data intensive application with Django?
I am trying to build a data intensive web application in Django. When I start this django application, I want it load a large amount of data (a few Gigabytes) into memory, and then whenever I receive a request, I will use the preloaded data to do some computation and generate a response based on the complicated calculations. I am wondering what might be the best way to organize this application. What will be the best way to build another layer that running purely on Python and Django can interact with the isolated running Python program for the calculation results. -
Django forms not sh
For some reason, my forms.py doesn't view any of the fields, instead, it only shows the 'Add' button and I don't know what to do anymore. I'd really appreciate if someone who knows what they're doing could tell me what I did, or didn't do. Please note that I'm new to Django, thank you. Here's my views.py: from django.shortcuts import render from django.utils import timezone from .models import Measurement from .forms import MeasurementForm from django.views import generic class IndexView(generic.ListView): model = Measurement context_object_name = 'measurement_list' template_name = 'index.html' queryset = Measurement.objects.all() def new_measurement(request): if request.method == "POST": form = MeasurementForm(request.POST) if form.is_valid(): measurement = form.save(commit=False) measurement.measurement_date = timezone.now() measurement.save() else: form = MeasurementForm() return render(request, 'index.html', {'form': form}) urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), ] forms.py: from django import forms from .models import Measurement class MeasurementForm(forms.ModelForm): class Meta: model = Measurement fields = ('measurement_value', 'measurement_unit') index.html: {% extends "base.html" %} {% block content %} <h1>Climate Measurement Tool</h1> <h2>Add a new measurement</h2> <form method="POST" class="post-form"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save">Add</button> </form> <h2>Measurements</h2> {% if measurement_list %} <ul> {% for measurement in measurement_list %} <li> <p>{{ measurement }}</p> </li> … -
How do I insert or create data with Django ORM programmatically? Or how do I specific Model field name with a string?
If I have: class Tag(models.Model): number = models.IntegerField() config = { "data": 1, "field": "number" } How do I do the following? record = Tag(config["field"], config["data"]) record.save() -
Django REST Framework- how can I create or update a foreign key object when POSTing parent
I am currently working on an API view, for a Job Planning system. Each Job, has a single JobPlan (which has a start and end date) and each JobPlan, may have several JobPlanManagers, users assigned to manage said Job. User one might be in charge of one month, and User two might overlap User 1, but extend the job by a couple of weeks. Thus, when User 2 POSTS their new JobPlanManager instance, they need to either create a new JobPlan (if no plan yet exists) or update the existing JobPlan, to extend the start and end appropriately. The user's POST data would include their user ID, the Job ID, and a start and end date, something like: { "manager": (User ID), "job_plan": { "id": null, "job": { "id": (existing Job ID) }, "start": "2018-02-01", "end": "2018-02-28" } } Additionally, I would like the return of this POST call to include all fields for JobPlan and Job, nested: e.g.: { "id": (created JobPlanManager instance ID) "manager": (User ID), "job_plan": { "id": (New or existing JobPlan ID) "job": { "id": (Existing Job ID), "name": "Existing Job Name" } "start": "2018-01-02", "end": "2018-02-28" } } My models look like: class Job(models.Model) name … -
How to use bootstrap styling in django project
I have downloaded bootstrap files (css, js) and put in the static folder of my project and made changes in header section of index.html as shown in the below code. But still django can't locate bootstrap.min.css as shown in the error "GET /static/css/bootstrap.min.css HTTP/1.1" 404 1687 Project Structure Project |---Project |---static |---css |---js |---templates |---index.html |---manage.py index.html <head> {% load staticfiles %} <link rel='stylesheet' href="{% static 'css/bootstrap.min.css' %}" type='text/css' /> </head> I followed tutorials and read documentation But could not locate the problem can anybody help, thanks in advance.