Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
modelformset_factory Raising ImproperlyConfigured Despite Appearing Correct
I'm using python 3.6 and Django 2.0. I have the following model defined: class IncidentInvolvedParty(models.Model): incident = models.ForeignKey(Incident, on_delete=models.CASCADE) officer_signed = models.ForeignKey(Officer, null=True, on_delete=models.CASCADE) party_type = models.CharField(max_length=7, choices=PARTY_TYPE_CHOICES) juvenile = models.BooleanField(default=False) home_address = models.ForeignKey(Address, null=True, on_delete=models.CASCADE, related_name="incident_party_address", blank=True) date_of_birth = models.DateField(null=True, blank=True) sex = models.CharField(max_length=1, choices=SEX_CHOICES) race = models.CharField(max_length=50, choices=RACE_CHOICES) height = models.IntegerField(null=True, blank=True) weight = models.IntegerField(null=True, blank=True) hair_color = models.CharField(max_length=20, null=True, choices=HAIR_COLOR_CHOICES, blank=True) eye_color = models.CharField(max_length=20, null=True, choices=EYE_COLOR_CHOICES, blank=True) drivers_license = models.CharField(max_length=100, null=True, blank=True) drivers_license_state = models.CharField(max_length=2, null=True, choices=STATE_CHOICES, blank=True) employer = models.CharField(max_length=200, null=True, blank=True) employer_address = models.ForeignKey(Address, null=True, on_delete=models.CASCADE, related_name="incident_employer_address", blank=True) build = models.CharField(max_length=25, null=True, blank=True) tattoos = models.TextField(null=True, blank=True) scars = models.TextField(null=True, blank=True) hairstyle = models.CharField(max_length=30, null=True, blank=True) and this view function: def create_incident(request, *args, **kwargs): VictimFormset = modelformset_factory(IncidentInvolvedParty, exclude=('id', 'incident', 'party_type')) SuspectFormset = modelformset_factory(IncidentInvolvedParty, exclude=['id', 'incident', 'party_type']) if request.method == 'POST': print(f"request.POST: {request.POST}") victim_formset = VictimFormset(request.POST, prefix="victims") suspect_formset = SuspectFormset(request.POST, prefix="suspects") incident_form = IncidentForm(request.POST) print(f"Victim formset: {victim_formset}") print(f"Suspect formset: {suspect_formset}") print(f"Incident Form: {incident_form}") if incident_form.is_valid() and victim_formset.is_valid() and suspect_formset.is_valid(): incident = incident_form.save() victims = victim_formset.save() suspects = suspect_formset.save() return redirect(f"/cases/{incident.id}") else: print(incident_form.errors) else: incident_form = IncidentForm() victim_formset = VictimFormset(prefix="victims") suspect_formset = SuspectFormset(prefix="suspects") context = {'form': incident_form, 'victim_formset': victim_formset, 'suspect_formset': suspect_formset} return render(request, "cases/create_incident.html", context=context) and this … -
Django Postgresql Heroku : Operational Error - 'FATAL too many connections for role "usename"'
I am running a web application using Django and Django Rest Framework on Heroku with a postgresql and redis datastore. I am on the free postgresql tier which is limited to 20 connections. This hasn't been an issue in the past, but recently I started using django channels 2.0 and the daphne server (switched my Procfile from gunicorn to daphne like this tutorial) and now I have been running into all sort of weird problems. The most critical is that connections to the database are being left open so as the app runs, the number of connections keep increasing until it reaches 20 and gives me the following error message: Operational Error - 'FATAL too many connections for role "usename"' Then I have to manually go to shell and type heroku pg:killall each time, this is obviously not a feasible solution and this is production so my users cant get access to site and get 500 errors. Would really appreciate any help. I have tried: Adding this to my different views in different places from django.db import connections conections.close_all() for con in connections: con.close() I also tried doing SELECT * from pg_activity and saw a bunch of stuff but have … -
Dynamically object creation Django get_or_create()
I am new to Django. So I was exploring it a little bit where I find a method get_or_create() for a model. I am wondering if it is possible like in the Django form. I have a field name category and it is just an input field like Charfield. So whenever user writes a new article I want the suggestions from the previous categories and if it is not there then it should make a new one on the basis of current one. Can anyone suggest me some logic or example. -
Get a list of users along with there group membership?
I want to get a queryset along with their group membership to avoid expensive additional database hits and to make managing stuff in the template much easier. Initially I tried to prefetch the groups a user belongs to: def get_queryset(self): User.objects.filter(is_active=True).prefetch_related('groups') But then it makes it difficult to show and hide things in the template based on the groups: {{ user.groups.all }} gives <QuerySet [<Group: Managers>]> Then I though perhaps an annotation may be better with a is_manager and is_head eg: def get_queryset(self): '''Return both active and inactive users for managers Annotate with is_manager = True/False ''' query = When(groups__name__in=[MANAGER_GROUP_NAME, ], then=Value(1)) return self.model.objects.all().annotate( is_manager=Case( query, default=Value(0), output_field=BooleanField() ) ) Which worked okay but gave me an error: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'my_site.auth_group.name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by But would be easy to use in the template with: {% if user.is_manager %} Manager {% else %} Normal user {% endif %} Is there an easier way to do it? -
how to runserver django in window10 subsystem ubuntu?
I command this way. (ubuntu bash in window10 subsystem) $ pip install virtualenv $ cd ~ $ virtual venv $ source venv/bin/activate (venv) $ pip install django (venv) $ django-admin startproject mysite (venv) $ cd mysite (venv) $ python managy.py makemigrations (venv) $ python managy.py migrate (venv) $ python managy.py runserver ... Starting development server at http://127.0.0.1:8000/ ... (in window10) open web-brower enter code here typed in url : http://127.0.0.1:8000/ ... no response.... Is there I miss something? this video show success. https://godjango.com/123-django-with-bash-for-windows/ but my case, Is not work..] -
Form's initial data not being passed through correctly
The form is a single BooleanField, and it lives on a ProfileDetailView, but is split off into its own FormView. I believe I'm passing the initial data by overriding the get_initial method, but it isn't passing through. What am I doing wrong? The field in the Profile model: class Profile(models.Model): public = models.BooleanField(default=False, verbose_name='Public') Here's the DetailView that passes the form through its context: class ProfileDetailView(DetailView): template_name = 'user_profile/profile_detail.html' def get_context_data(self, **kwargs): context = super(ProfileDetailView, self).get_context_data(**kwargs) context['public_toggle_form'] = PublicToggleForm return context And the related FormView which overrides the initial data(the booleanField is the public var): class PublicToggleFormView(AjaxFormMixin, FormView): form_class = PublicToggleForm success_url = '/form-success/' template_name = 'user_profile/profile_detail.html' def get_initial(self): profile = Profile.objects.get(user__username=self.request.user) public = profile.public initial = super(PublicToggleFormView, self).get_initial() initial['public'] = public return initial Here's my forms.py: class PublicToggleForm(forms.Form): public_toggle = forms.BooleanField(required=False) def clean_public_toggle(self): public_toggle = self.cleaned_data.get("public_toggle") if public_toggle is True: print("im True") else: print("public is false here") return public_toggle the profile_detail.html template which includes the form: {% if request.user == object.user %} Make your profile public? <form class="ajax-public-toggle-form" method="POST" action='{% url "profile:public_toggle" %}' data-url='{% url "profile:public_toggle" %}'> {% include 'includes/bs4_form.html' with form=public_toggle_form %} </form> {% endif %} I have since tried changing the form to a modelForm: class PublicToggleForm(ModelForm): … -
Django atomic block don't roll back all changes
I've probably misunderstood how rollback works when using with transaction.atomic() context manager in Django (1.11). In the following example the operation2 method raise an IntegrityError, but being operation2 called from an atomic transaction block all changes performed within the block should be rolled back. See the example (largely simplified from my actual code): class MyClass(object): def operation1(self, items): for item in items: item.ohlala = True def operation2(self, items, value): for item in items: item.value = value item.compute_other_value() # Create association. This block can raise Integrity Error line = item.line # OTO rel. line.net_amount = item.other_value line.save() def do_things(self, form): items = get_items() try: with transaction.atomic(): self.operation1(items) self.operation2(items, 200) except IntegrityError as e: return False What happens instead is that all changes performed in operation2 are rolled back but not those performed in operation1. I would have expected all operations updating the db to be rolled back. In the django documentation it once says that when raising from within an atomic block then all changes will be rolled back. But later on in the same section it says "You may need to manually revert model state when rolling back a transaction." Am I misinterpreting what Django should do or am I … -
how to create hook from python to send data to mixpanel using dev token
I want to create a hook from my python code to send user data to mixpanel from signals.py in login and logout. Seen examples using api key and secret keys but I have only the dev auth token. Also i want to retrieve data from that hook later on -
Edit profile for 2 different user types in Django
I have 2 user types, teacher and student. I have built the view to be able to edit a student profile. But I also needed a different one for teacher. I didn't want 2 views, because that would be pointless. Now, for teacher it works as intended, but for some reason for student, the same form as for teacher is displayed... a student has different attributes so it has a different form I need to show. @login_required def profile_edit(request): user = request.user student = request.user.student teacher = request.user.teacher if user == teacher.user: if request.method != 'POST': form = TeacherEditForm(instance=teacher) else: form = TeacherEditForm(request.POST, instance=teacher) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') elif user == student.user: if request.method != 'POST': form = StudentEditForm(instance=student) else: form = StudentEditForm(request.POST, instance=student) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') context = { "form": form, } return render(request, "registration/profile_edit.html", context) -
Using RESTful API and Django: how to temporarily add data into backend?
I am currently building a webapp (that will be presented as a single site eventually) using django and sqlite - the goal is to present an interactive front end where the user is able to see a randomized sample of the data I am storing. At this point I have a working connection between the sql database and what is presented in the views, but the way I have it set up I must enter the data manually. I would like to use an API (NYTimes) to automatically be called upon a few times a day, store what is given from the API, and present it on a basic JavaScript page. I was thinking the best method would be to call GET from the API in the JavaScript file of the view, and then load it into the backend --- and this is where I get a bit lost. (As you can tell I am new at this) I have tried searching for a method like this, but nothing seems to do quite what I need. If I am missing anything big or if you have any suggestions/solutions, I would love to hear! -- Thanks in advance -
Django: How should I structure models for this?
I am trying to make my first website. I am using Django for it. I have these models right now related to which I have question: class Clinic(models.Model): name = models.CharField(max_length=100) DOC_DAYS_CHOICES = ( 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ) DOC_DAYS_SHIFTS = ( 'Morning', 'Afternoon', 'Evening' ) class ClinicDoctor(models.Model): doctor = models.ForeignKey('User', related_name='doctorsF') clinic = models.ForeignKey(Clinic, related_name='clinicsF') days = models.CharField(max_length=200) time = models.TimeField() shift = models.CharField(max_length=15) I am stuck with this thing. I have been modifying the models as I go along. Now I don't know how to achieve what I want. I have attached two images. One shows how my data will be and another shows how I would like it to appear on page. I would like to structure the models such that code is efficient that what I want display should make a lesser DB hits anything I can achieve with prefect? As the image shows. Each doctor has multiple clinics. Then 7 days of week he can have 3 shifts per day for each clinic. -
Django models design
I am working on a quiz app on Django and have the following models - User, Test, Question and Answer. The Test model acts as a wrapper for the Questions model. This is what my models looks like at present - models.py class Test(models.Model): def id_count(): current_count = Test.objects.count() current_count += 1 return current_count test_id = models.PositiveIntegerField(default=id_count,primary_key=True) test_description = models.CharField(max_length=255) class Question(models.Model): def id_count(): current_count = Question.objects.count() current_count += 1 return current_count test = models.ForeignKey(Test,on_delete=models.CASCADE) question_id = models.PositiveIntegerField(default=id_count,primary_key=True) question_text = models.CharField(max_length=255) option_one = models.CharField(max_length=12,default="Always") option_two = models.CharField(max_length=12,default="Never") class Answer(models.Model): question = models.ForeignKey(Question,on_delete=models.CASCADE) customuser = models.ForeignKey(CustomUser,on_delete=models.CASCADE,blank=True, null=True) original_answer_score = models.IntegerField(default=-1) The current models basically allow every user to answer the same question multiple times. How can I design my models to allow every user to answer one question only once? Thanks. -
Django is it written good?
I have a question to u guys. Is the href in code written good without url? html template <div class="panel-body anime-list text-center"> <div class="btn-group btn-group-xs"> {% for i in alphabet %} <a href="{{i}}" class="btn">{{i}}</a> {%endfor%} </div> </div> urls urlpatterns = [ path('', views.list, name='list'), re_path(r'^[A-Z]{1}/', views.list_detail, name='list_detail')] views from django.shortcuts import render import string from django.http import HttpResponse alphabet = string.ascii_uppercase def list(request): context = {'alphabet': alphabet} return render(request, 'list/list.html', context) def list_detail(request): return HttpResponse('Something') -
Check if locale is in languages list in settings Django
is there a way to check if locale = 'some locale' is in settings.LANGUAGES I do like this: lang ='en' languages = settings.LANGUAGES lang_found = False for language in languages: if lang in language: lang_found = True break I think it is not a good way. -
How to import RegistrationForm from forms.py?
I have created two classes in forms.py class RegistrationForm(UserCreationForm): class EditProfileForm(UserChangeForm): And, I have to import them in views.py. Do help. -
2 Rows and 3 columns using bootstrap in Django
Trying to iterate multiple posts through a loop, into 2 rows of 3 items. Currently my code looks like this {% for post in post.all %} <div class="row"> <div class="col-md-4"> <div class="thumbnail"> <div class="caption"> <h3>{{ post.title }} - {{post.assignment_level}}</h3> <p>by {{post.author}} from {{post.pub_date}}</p> <h4>{{post.assignment_body}}</h4> <p><a href="#" class="btn btn-primary" role="button">Read...</a></p> </div> </div> </div> </div> {% endfor %} {% endblock%} this gives me one column of 6 posts. How do I split them in to 2 rows of three posts. Really been googling this. Thank you in advance -
Using CAS server/client within Django to log into two sites concurrently
I've got a working example of a CAS server using django-mama-cas and two CAS clients using django-cas-ng. Both clients can authenticate via the server, but when I log into one I'm logged out of the other. I need to have access to both at the same time so I can redirect to website B to store the OAuth codes and seamlessly pass back to Website A. Does anyone know of config options in either the server or client software that would allow me to pass the current user between sites? Reason for this need: We have two Django-based websites - Website A deals with data visualisation, website B handles data collection and shares it via an API. The flow I need is: Login to Website A Authorise via 3rd party website and gain OAuth tokens OAuth redirect URL to Website B to store OAuth tokens in data warehouse / API Finally, redirect from Website B back to Website A to visualise data. My thinking is that a CAS setup could handle the shared authentication. I hope someone who has experience of these Python libraries or CAS in general could provide some pointers. I have a working version of the three … -
Celery task to write file in subprocess call
dene is a celery task to call subprocess and in the subprocess script, I want to write some text in file (auth_path) when each function in script done. The problem is, if I call python3 apt.py from shell, text written in the file. but when i call subprocess in task, progress works correctly, all functions works in apt.py but nothing written in aut_path. Why I cannot write some texts when I call script from subprocess. @task(name="dene") def dene(): cmd = ['timeout', '240', 'python3', "apt.py"] output = check_output(cmd) in apt.py there is a write func and calling it again and again. def write_out_auto(msg): with open(aut_path, 'a') as the_file: the_file.write(msg +'\n') write_out_auto("Finished the section 2") -
How to use scrapy with django and upload it to heroku
I am using scrapy to scrape some data. But I want to use it with django for user interface and to save the data to database. Also I want to know how can I upload it to heroku -
when i am adding new product or modifying the record it is not showing the result set in search after building index in django oscar
As I used Solr for search backend, and once my product get index and now the second time when I add new products and change price after index created that product not being search in and sorting of price also not worked for new change ( i need to rebuild index then start the java server then will work properly ), is there any other solution for the same . I am using Solr 4.7.2. -
Django - admin.get_urls not actually getting my new urls
I am working on an existing codebase and stumbled on a admin mixin that uses the get_urls method. class MPTTEditAdminMixin(object): def get_urls(self): info = self.model._meta.app_label, self.model._meta.model_name remove_view = "%s_%s_change" % info original = super(MPTTEditAdminMixin, self).get_urls() filtered = [p for p in original if p.name != remove_view] return [ url(r'^(?P<object_id>\d+)/edit/$', self.admin_site.admin_view(self.change_view), name='%s_%s_real_change' % info), url(r'^(?P<object_id>\d+)/$', self.admin_site.admin_view(self.readonly_view), name='%s_%s_change' % info), ] + filtered def readonly_view(self, request, object_id, form_url='', extra_content=None): (...) It is used on multiple admin classes (hence the somewhat convoluted use of the 'info' variable), however, I am encountering the following bug: Links to the '%s_%s_real_change' url are not working, instead the code always seems to refer to the '%s_%s_change' url link. I have moved the 'real_change' code above the 'change' code yet the problem persists. Its almost as if it stops parsing the url as soons as it completes the 'r'^(?P\d+)' part. Does anyone know why this is / what we are doing wrong? -
Django - form object has no attribute '_errors'
Im trying to create a form that will show a list of checkboxes based on a models items. Then also to be able to filter this list if required. However I am getting the below error and am not sure as to why? error: File "/usr/local/lib/python3.6/site-packages/django/forms/forms.py" in errors 174. if self._errors is None: Exception Type: AttributeError at /sites/site/auto_gen_subnets/7 Exception Value: 'AutoSubnetForm' object has no attribute '_errors' forms.py class AutoSubnetForm(forms.Form): subnet_type_data = SiteTypes.objects.all() def __init__(self, *args, **kwargs): self.site_type = kwargs.pop("site_type") # get site type if set and filter against it if self.site_type: subnet_type_data = SiteTypes.objects.filter(site_type=self.site_type) # create list for types subnet_types = [] for stype in subnet_type_data: # add tuple for each type subnet_types.append((stype.id,stype.site_type)) subnets = forms.ChoiceField( choices=subnet_types, widget = forms.Select( attrs = {'class': 'form-control'} ) ) views.py: @login_required @user_passes_test(lambda u: u.has_perm('config.add_subnet')) def auto_gen_subnets(request, site_id): #generate_subnets(site_id) from config.models import SubnetTypes site_data = get_object_or_404(SiteData.objects.select_related('site_type'),pk=site_id) subnets = None if request.method == 'GET': form = AutoSubnetForm(site_type=site_data.site_type) else: # A POST request: Handle Form Upload form = AutoSubnetForm(request.POST) # If data is valid, proceeds to create a new post and redirect the user if form.is_valid(): subnets = form.cleaned_data['subnets'] return render(request, 'sites/generate_subnets.html', { 'data': subnets, 'subnet_form': form, 'SiteName' : site_data.location, 'SiteID' : site_id, } ) -
How does Workers work in Django Channels
Im using django channels for a project, it normaly starts 3 workers when I run the django server using: manage.py runserver What I understood is the workers are running separate each but still sharing their variable values? How is that achieved using the inmemory solution without redis? I need to change variable independent from the worker that is running the function, I tried thread locking, but didnt solve since it seems to be 3 times the python script loaded, and not multithreading one script. Thank you in advance -
Return all objects that are referenced exactly twice by a related model
I have the following models: class Person(...): name = CharField(...) class Address(...): person = ForeignKey(Person) address = CharField(...) I need to select all persons that have exactly two addresses. So if my Address table looks like this: ------------------------- | id | person | address | ------------------------- | 1 | 1 | xyz | | 2 | 1 | xyz | | 3 | 2 | xyz | | 4 | 3 | xyz | | 5 | 3 | xyz | | 6 | 4 | xyz | | 7 | 5 | xyz | | 8 | 5 | xyz | | 9 | 5 | xyz | ------------------------- The resulting queryset should be <QuerySet [<Person: 1>, <Person: 3>]> I tried a lot, but just don't seem to get it right. I would be glad for a quick fix. -
Django Model: Display only corresponding values from Model DB by user selection
I want to create an Application in Django that displays oil parameter from a model to calculate with. My Model.py look like: #models.py class OilModels(models.Model): oil_name = models.CharField(max_length = 200, default = '') oil_density = models.DecimalField(max_digits = 9, decimal_places = 2, default = '') oil_temperature_1 = models.DecimalField(max_digits = 9, decimal_places = 2, default = '') ... The oils are added in the admin.py view: #admin.py admin.site.register(OilModels) I want to display the oil_name in a html select option like: #index.html <select> {% for oil in objectlist %} <option value="{{ oil.pk }}">{{ oil.oil_name }}</option> {% endfor %} </select> And then if the user selects an oil from the html select, I want to display only the corresponding values from the model like: #index.html <input type="number" value="{{oil_density}}" readonly /> <input type="number" value="{{oil_temperature_1}}" readonly /> ... Sadly I don't get it to work. I hope one of you has an idea and can help me. Thank you in advance.