Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Updating Model Instance with Django
I am initiating an instance of Estate with CreateView1. It works fine, even though it is a template view!! Now I want to be redirected to UpdateView2 and update those fields (I have a good reason for that). How can I pass the pk of instance 1 to the second view, and how to edit those fields? Any help would be much appreciated!! views.py class CreateView1 (TemplateView): template_name = 'estate_form1.html' def get(self,request): form = RegisterForm() args = {'form': form,} return render(request, self.template_name, args) def post(self,request): form = RegisterForm(request.POST) if form.is_valid(): estate = form.save(commit=False) estate.save() form = RegisterForm() return redirect('register:update2') args = {'form': form,} return render(request, self.template_name, args) class UpdateView2(UpdateView): template_name = 'estate_form2.html' model = Estate fields = ["price", "area"] estate_form1.html and estate_form2.html <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> forms.py class RegisterForm(forms.ModelForm): price = forms.IntegerField(label="Price:") area = forms.IntegerField(label="Area:") Class Meta: model = Estate fields = ('price', 'area') Thanks already for the support! -
can i import django.template.defaultfilters inside a python file
this might be a foolish question. I am learning python from an udemy course. In the course video,the instructor was using print(upper("NEW")) and then import django.template.defaultfilters but i can't import this.we both are using python 3.6. Do i need to change any settings,please help me. Thanks in Advance -
Django Channels/Daphne Internal Server Error "'dict' object is not callable"
I have received this Error when connecting to my site as it is running channels. 2018-03-25 20:59:19,049 - ERROR - http_protocol - Traceback (most recent call last): File "/home/.virtualenvs/blog/lib/python3.5/site-packages/daphne/http_protocol.py", line 158, in process "server": self.server_addr, File "/home/.virtualenvs/blog/lib/python3.5/site-packages/daphne/server.py", line 184, in create_application application_instance = self.application(scope=scope) File "/home/.virtualenvs/blog/lib/python3.5/site-packages/channels/staticfiles.py", line 42, in __call__ return self.application(scope) TypeError: 'dict' object is not callable I have no idea where to start decoding the error. The channels server managed to start with this Starting ASGI/Channels development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. 2018-03-25 20:57:45,400 - INFO - server - HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2018-03-25 20:57:45,400 - INFO - server - Configuring endpoint tcp:port=8000:interface=0.0.0.0 2018-03-25 20:57:45,401 - INFO - server - Listening on TCP address 0.0.0.0:8000 -
Django server RW access to self owned google calendar?
In a django application, I try to have RW access to a google calendar which I own myself. Tried several ways with a service account & client secrets, but all resulting in authentication errors. The API explorer works, but it requests consent in a popup window, which is obviously not acceptable. Documentation on google OAuth2 describes several scenarios. Probably "web server application" applies here? It says: "The authorization sequence begins when your application redirects a browser to a Google URL; the URL includes query parameters that indicate the type of access being requested. Google handles the user authentication, session selection, and user consent. The result is an authorization code, which the application can exchange for an access token and a refresh token." Again, we do not want a browser redirection, we want direct access to the google calendar. So question is: how can a django server access a google calendar, on which I have full rights, view events and add events using a simple server stored key or similar mechanism? -
Django, how to get new id during save
I have this code: class Unit(Location): Name = models.CharField(max_length=100, unique=True) Hull = models.CharField(max_length=25, unique=True) Type = models.CharField(max_length=5, CHOICES=UNIT_TYPE_CHOICE) Precomm = models.BooleanField(default=True) Email = models.CharField(max_length=250, verbose_name="Email") Phone = models.CharField(max_length=20, verbose_name="Primary Phone") def __self__(self): return self.Name + ' (' + self.Hull + ')' def save(self, *args, **kwargs): if not self.pk: co = Position(Name='Commanding Officer', Description='Position in command of chapter.', Unit=self.pk) co.save() xo = Position(Name='Executive Officer', Description='Second in Command of Chapter', Unit=self.pk) xo.save() cob = Position(Name='Chief of the Boat', Description='Senior Enlisted Adviser in charge of cadet affairs', Unit=self.pk) cob.save() super(Unit, self).save(args, kwargs) class Position(models.Model): Name = models.CharField(max_length=100) Description = models.TextField() Unit = models.ForeignKey(Unit) The idea is to auto-create three Positions when a Unit is saved. The positions are set in the save process. My concern is that self.pk is not created at the point of the save definition. How do I get the id so I can create the three records? Thanks -
Different IPs are for different apps
At first, I am learning Python and Django only... So I'm a noobie yet. I need to build a microservice architecture to I could run each my service on a separate server machine. In the Django I need to create an environment, project and apps. So, can I run these apps after on different servers? If no, how can I make it with Django? Do I need to create a separate project for each service? P.S. If my question is stupid, pls, explain where am I wrong. I am from Java Spring world where I was need to create just new app for each service. -
Django setting BooleanField not required
I have two classes in models.py and do not want every fields are required for the form.py. models.py class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, related_name='topics', on_delete=models.DO_NOTHING) starter = models.ForeignKey(User, related_name='topics', on_delete=models.DO_NOTHING) is_seller = models.BooleanField(default=True) def __str__(self): return self.subject class Thread(models.Model): items = models.CharField(max_length=300) message = models.CharField(max_length=1000, default="Message") topic = models.ForeignKey(Topic, related_name='threads', on_delete=models.DO_NOTHING) forms.py class NewTopicForm(forms.ModelForm): message = forms.CharField( max_length=1000, widget=forms.Textarea( attrs={'rows':5, 'placeholder': "Short description"}, ) ) items = forms.CharField( max_length=300, widget=forms.Textarea( attrs={'rows':1, 'placeholder':"ex)phone, tablet"} ), help_text="Write down your item" ) is_seller = forms.BooleanField( help_text="Check if you are a seller" ) class Meta: model = Topic fields = ['subject','message', 'items', 'is_seller'] form.html {% for each in form %} <div class="form-group"> {{ each.label_tag }} {% if form.is_bound %} {% if each == form.is_seller %} pass {% else %} {% if each.errors %} {% render_field each class="form-control is-invalid" %} {% for e in each.errors %} <div class="invalid-feedback">{{e}}</div> {% endfor %} {% else %} {% render_field each class="form-control is-valid" %} {% endif %} {% endif %} {% else %} {% render_field each class="form-control" %} {% endif %} {% if each.help_text %} <small class="form-text text-muted">{{each.help_text|safe}}</small> {% endif %} </div> {% endfor %} What I am trying to do is, filter … -
Django filter and custom data validation
Good afternoon. I am new to Django. I am working on validating data that my user has entered to checkout equipment. User has entered a name ('associate') and equipment name ('equipment'). I have most of it working. In fact I have an error condition that works but my inexperience with Django is tripping me up a bit on what I want to do: class Equipment(models.Model): eq_name = models.CharField(max_length=8,unique=True, verbose_name="Unique Equipment Name", help_text="FANV###,RAD##, ##LF, ##RT, CALC##") category = models.ForeignKey('category', on_delete=models.PROTECT) AVAILABLE = 'AVAILABLE' LOST = 'LOST' REPAIR = 'REPAIR' RETIRED = 'RETIRED' STATUS_CHOICES = ( (AVAILABLE, 'available'), (LOST, 'lost'), (REPAIR, 'repair'), (RETIRED, 'retired'), ) status = models.CharField(max_length=10,choices=STATUS_CHOICES) def __str__(self): return self.eq_name def get_absolute__url(self): return reverse('equipment-detail-view', args=[str(self.id)]) class Meta: db_table='equipment' ordering = ["category", "eq_name"] verbose_name_plural='equipment' class Checkout(models.Model): associate = models.ForeignKey('employee',on_delete=models.PROTECT) equipment = models.ForeignKey('equipment',on_delete=models.PROTECT) ck_out = models.DateTimeField(auto_now_add=True, verbose_name='Check Out Time') ck_in = models.DateTimeField(blank=True,null=True, verbose_name='Check In Time') def __str__(self): return self.id def get_absolute__url(self): return reverse('checkout-detail-view', args=[str(self.id)]) class Meta: db_table = 'checkout' The following works and prevents users from checking out more than one equipment type(category) at a time: alreadyhas = Checkout.objects.filter(ck_in__isnull=True,associate=associate, equipment__category=equipment.category) The question is, how can I print the offending equipment name to my user; the name of the equipment that my user … -
vue js + django app architecture
I've found a few posts about this. But I'm still confused. I want to use django rest framework api to be consumed by vue. My questions: Should I use django templates at all? I guess not, cause the django templates syntax clashes with vue. But still I need to serve templates - should I just use static templates with apache? Assuming I do use static templates, how can I prerender pages like with django templates? I mean, with django I have a url like /resource?id=5, But with rest api, it will be vue responsibility to fetch the id=5 resource from the url and to do the rendering, But I don't like the need for extra xhr. It seems that all the docs assume I use node.js, I don't. Do I have to use another node.js server in addition to the django apache server? Does vue.js with webpack/npm force a specific app folder structure? How that works with the normal django project structure? -
Django SECRET KEY error
I'm building a little Django REST API. I've configured a separate settings module for local and production but I'm having an annoying error which is: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. This error doesn't make sense because I have the SECRET_KEY variable set. Here are my base.py (which is my base settings for the API) and the local.py. Also, here are my wsgi.py and manage.py. base.py https://docs.djangoproject.com/en/2.0/ref/settings/ """ import datetime import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) from django.conf import settings BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) SECRET_KEY = os.environ.get('SECRET_KEY', 'mmglfamx3n927*93$ks#r)h%*a(@))vb7*=2q$&z(=6@q&*ghj') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api', 'drf_yasg', ] REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ) } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'petevip.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR, os.path.join(BASE_DIR, 'templates')], '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 = 'petevip.wsgi.application' # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N … -
Django styling multichoicefield checkboxes
I was able to include multi select checkboxes however, I am having trouble to provide styling to the forms. I can can correctly displaying the options but they appear with a dot in front. When I add a class to the template adding attributes to the widget it adds the class but its not allowing style changes. I try to do it with django widget tweeks and it does not do it either. I think to style the label of the checkbox the class should be inserted to the checkbox label and not to the input. forms.py CHOICES = ( ('a', 'A'), ('b', 'b'), ('c', 'c'), ) class Modalities(forms.Form): multicheck = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple( attrs={'class': 'check_label'} ), choices=CHOICES) HTML <div class="col-md-6"> <div class="form-group"> <h3>Options</h3> </div> {% for field in form %} {{ field }} {% endfor %} </div> CSS label { font: bold 15px "Helvetica Neue"; text-transform: lowercase; } .check_label { font: 12px "Helvetica Neue" !important; text-transform: initial !important; } Output: -
ERROR Too Many Connections Redis, RabbitMQ, Celery, and Django
Taking my first crack at asynchronous tasks with Celery. Using Redis as backend store, RabbitMQ as the broker, and Django for the webapp. Plus its all done using Docker containers/images. I have it structured so that a task will run from a view. Here's the view: from django.shortcuts import render from django.http import HttpResponse from .tasks import add def index(request): task = add.delay(4,4) return HttpResponse("Run task") Here's the task: from celery import shared_task from composeexample.celeryconf import app from .models import AddStore @shared_task def add(x, y): value = x + y new = AddStore(value=value) new.save() return value So I can run the task from the view and from the django manage.py shell, for example: from polls.tasks import add task = add.delay(4,4) print (task) >> <AsyncResult: 8a91a9c0-c01e-45fc-850b-f5e42ef5a1a1> but I can't access the result. When I run task.get(), I get a response redis.exceptions.ConnectionError: Too many connections Not sure if this is Redis or Django or Docker related. Happy to share any other info that someone thinks is necessary. I would really appreciate help. Also, the task does not update the model AddStore. -
Creating a new entry using the Django admin interfaces replaces previous entry
I have a model in Django that looks like this: class Video(models.Model): id = models.CharField(primary_key=True, default=uuid.uuid4().hex[:8], editable=False, max_length=8) title = models.TextField(max_length=100, help_text='Insert video title here', verbose_name='Title') I have a superuser that can create new Videos. I go into the admin view and create a new Video. Lets say I create a Video titled "Video 1". It shows up correctly. Then, if I create another video called Video 2, I can only see Video 2 in the list of Videos. I looked at the history of Video 2, and here is what it said: March 25, 2018, 3:37 p.m. superuser Added. March 25, 2018, 3:37 p.m. superuser Changed title. Which means that Video 1 is just being updated to Video 2. However, if I restart my server, I'm able to see Video 2, and then I'm able to create a different Video. But then the problem persists with this new video. The way I understand it is that with each server session, I'm only allowed to create a single entry. -
How to change NumberInput widget width in Django?
I try to change the width of NumberInput and TextInput widgets: class MyModelAdmin(admin.ModelAdmin): formfield_overrides = { models.FloatField: {'widget': NumberInput(attrs={'size':'10'})}, models.CharField: {'widget': TextInput(attrs={'size':'10'})}, } It works good with TextInput widget but does not work with NumberInput widget. How can I do it? -
How to fetch json data without the json array name in android from django rest api ?
private void jsonParse() { String url = "http://127.0.0.1:8000/products/products/"; JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray jsonArray = response.getJSONArray(""); for (int i = 0; i < jsonArray.length(); i++) { JSONObject o = jsonArray.getJSONObject(i); int id = o.getInt("id"); String title = o.getString("title"); String description = o.getString("description"); String price = o.getString("price"); mTextViewResult.append(title + ", " + String.valueOf(id) + ", "+price +"," + description + "\n\n"); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); mQueue.add(request);} This is my android code [ { "id": 1, "title": "t-shirt", "description": "this is a good t-shirt", "price": "39.99" }, { "id": 2, "title": "Jeans", "description": "this is a jean", "price": "89.99"}] This is my json data How can i fetch the json data which don't have a json array name. In my android i need to have json array name to parse the json data.But my django rest api produce json data without json array name. -
Go for ajax, websockets or something else for asynchronous page loading on django
I am working on a django web-app. I have a query that takes quite some time to get fetched and I want the output to be visible to my user. I am doubting about going for Ajax or Websockets for asynchronous loading of the data. Or might there be something else to use in this case. Websockets: I know Websockets can do realtime stuff and update the page. However, they can only process serialised content. So does this means when I go for websockets that I am stuck with Json files in my HTML-environment, no easy pagination, no easy use of django templates? Ajax: Ajax can do requests from the page in an "asynchronous" way, so no reload of the page required. But: if my query takes longer then the timeout of my app (heroku timeout of 30 seconds, not changeable), will the ajax request also timeout in 30 seconds of have more time to get completed? alternatives? Any alternatives to deal with this asynchronous page loading behaviour? Thanks! -
How to Access Static file logs inside an view in Django
I want to log every Static Files request and the request IP address in Django. In Console I am able to check the Static File Log, But I want access those logs inside an Django View with IP address of the request Can Suggest an solution or any work around. I am planning to server static files manually and perform logging. -
How to let the django pass an instance of HttpRequest to views using POST method
Hi could you help me solve the following problem. In the Django tutorial it says When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object. Now I have written a view as follows and it renders the first form in my application. It looks like it has been passed with GET instead of POST as I get that "Method is not post" in the application. Can I change this? Since this is the first view loaded, so the response is not returned by another view. I am not sure where to change it. def intro(request): if request.method == 'GET': return HttpResponse("Method is not post") .... -
Django: manipulating database with script; importation error
I'm going through the Django tutorial and wanted to try out database manipulating with a python script but encounter a problem My script: from polls.models import Question, Choice from django.utils import timezone import numpy as np #Questions nquestions=3 q=np.empty([nquestions, 10], dtype=object) qtext=q qtext[0]="What's up?" qtext[1]="What's new?" qtext[2]="What's old?" #Choices q[0,1]="Not much" q[0,2]="The sky" q[1,1]="This question" q[1,2]="This answer" q[2,1]="No more originality" q[2,2]="xxxxxxx" #Check if exists and apply for i in range(0, len(q)): q[i,0]=Question(question_text=qtext[i], pub_date=timezone.now()) if Question.objects.filter(question_text=qtext[i]).exists(): pass else: q[i,0].question_text=qtext[i] q[i,0].save() alen=len(q[i][q[i] != np.array(None)]) for ii in range(0, alen-1): q[i,0].choice_set.create(choice_text=q[i,ii+1], votes=0) I get the error django.core.exceptions.appregistrynotready apps aren't loaded yet. I'm running the script from terminal and it's places in the folder that contains the polls-folder (One level over modules.py, which I'm trying to import). Writing the contents of my script works if i first run in terminal : python manage.py shell. Is there a way for me to run a script to manipulate the database through Djangos API, or do I have to enter information manually or send requests thŕough post? -
Python Django How to save choice using model class "CHOICE"?
In my models.py, I have class with LEVEL_CHOICES and Level. First I builded my project with a textfield Level and it worked. Then I decided to change my Level in order to give users only certain choices. Therefore I edited my models.py and I have now: class Eleve(models.Model): FIRST = 'FIRST' SECOND = 'SECOND' THIRD = 'THIRD' LEVEL_CHOICES = ( ('FIRST', 'School'), ('SECOND', 'HighSchool'), ('THIRD', 'University'), ) Level = models.CharField(max_length=3, choices=LEVEL_CHOICES, default='FIRST') I think that there is a problem in my views.py because I'am able to save class Eleve through Admin app. I'm also using a decorator in order to have REcaptchaV2. def Form(request): form = ResgisterStud(request.POST) if request.recaptcha_is_valid and form.is_valid(): form.save(commit=False) form.save() return render(request, 'form.html', {'form': form}) else: return render(request, 'form.html', {'form': form}) -
Counting related objects on a model that match a propery value un django
I have an MultipleChoiceAnswer Model with a M2M relation to a choice model: class MultipleChoiceAnswer(Answer): choices = models.ManyToManyField(QuestionChoice) and this is the QuestionChoice model: class QuestionChoice(models.Model): name = models.CharField(max_length=300) question = models.ForeignKey(MultipleChoiceQuestion) explanation_needed = models.BooleanField(default=False) is_correct = models.BooleanField(default=False) ordinal = models.IntegerField(blank=True, null=True) select_all = models.BooleanField(default=False) no_answer = models.BooleanField(default=False) def __unicode__(self): """Return a human readable representation of the model instance.""" return (u"%s - %s" % (self.question.name, self.name)) What I want to do i to get all the MultipleChoiceAnswers that have the count of QuestionChoices with is_correct=True greater than 1 (i.e All the answers that have more than one correct choice). What I was doing is getting them all first and the iterating to filter the ones that does not macth my criteria: multiplechoices = MultipleChoiceAnswer.objects.prefetch_related("choices").all() for answer in multiplechoices: if answer.choices.filter(is_correct=True).count() > 2: myanswers.append(answer) But I think this is really slow since I make a lot of queries when putting the filter inside the for loop and this model could potentially have hundreds of thousands of rows. Is there a way where I can get this with less queries o even better with just one query? -
How to integrate google map into an website such that it shows location based on by entering pincode
i am involved in a project in which i have to use google map integration in such a way that by entering the pin code of a city it should show the location . I don't know how to start and i want do do this with django frame work . So , please give me a idea on how to approach it. Thanks in advance. -
Django OneToOneField default value
Recently I added an OneToOneField in django model , I set None as default value in this field . then i got this error : django.db.utils.IntegrityError: NOT NULL constraint failed: user_myuser.album_id model : class MyUser(models.Model): username = models.CharField(unique=True, max_length=25) first_name = models.CharField(max_length=50, default='') last_name = models.CharField(max_length=70, default='') register_date = models.DateTimeField(default=timezone.now) update_at = models.DateTimeField(auto_now=True) # the default value problem is here album = models.OneToOneField(Album, auto_created=True, on_delete=models.CASCADE, default=None) And Here is Album Model : class Album(models.Model): name = models.CharField(max_length=100, null=True) author = models.CharField(max_length=100, null=True) picture_address = models.ImageField(upload_to=album_upload_destination, null=True) creation_year = models.IntegerField(default=-1) rate = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True) -
Hosting django website on Cpanel
My django project is complete and ready to be hosted as this is my first project and first web hosting I don't know how should I do it please some one help me in this and I Am Using MYSQL as database in my project.. -
get_queryset and get_context_data combine functions
I am new to django i can not distinguish functions get_queryset and get_context_data in generic views. So writed this piece code: class NodesDetailView(DetailView): model = Platform template_name = 'project/nodes_detail.html' def get_queryset(self): queryset = super().get_queryset() child = self.request.GET.get('child') if child is True: queryset = queryset.get_family().get_descendants(include_self=True) elif child is False: queryset = queryset.get_descendants(include_self=True) else: pass return queryset def get_context_data(self, **kwargs): context = super(NodesDetailView, self).get_context_data(**kwargs) context['nodes'] = When in GET request child=False i call one function in queryset when child=False call second function. That's okay get_queryset logic is good. But i need show results in my template. Forloop results of queryset. So i need call function get_context_data and don't what to do next. Problem is how to forloop results of queryset, use it inside get_context_data function Thanks