Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
fields.E304 Reverse accessor clashes in Django
I am trying to migrate these two models: # models.py from django.db import models class Person(models.Model): name = models.CharField(max_length=64) class Person2Person(models.Model): person = models.ForeignKey(Person) friend = models.ForeignKey(Person) But I have got this error: SystemCheckError: System check identified some issues: ERRORS: website.Person2Person.friend: (fields.E304) Reverse accessor for 'Person2Person.friend' clashes with reverse accessor for 'Person2Person.person'. HINT: Add or change a related_name argument to the definition for 'Person2Person.friend' or 'Person2Person.person'. website.Person2Person.person: (fields.E304) Reverse accessor for 'Person2Person.person' clashes with reverse accessor for 'Person2Person.friend'. HINT: Add or change a related_name argument to the definition for 'Person2Person.person' or 'Person2Person.friend'. I want to make a relationship many-to-many in the model Person. Why is my code wrong? And how should I fix it? -
Wrapping a Django ModelForm with a Div in Crispy Forms
I have the following form: class CreateAssignedTestForm(forms.ModelForm): class Meta: model = AssignedTest fields = ['due_date'] That essentially just takes a date field. I would like to leverage some of teh template I am using's built in form helpers but, as I render this with Crispy forms (below), am having trouble over riding the div. Essentially I would like to give it the id (date picker) as below. Current (non assigned html): <form method="POST" action=""> {% csrf_token %} {{ form|crispy}} </br> <input type='submit' value='Create' class='btn'> </form> Attempt at wrapping a DIV (what I would like to achieve): <div class="input-group date"> <div class="input-group-addon"> <i class="fa fa-calendar"></i> </div> <input type="text" class="form-control pull-right" id="datepicker">{{ form|crispy}}</input </div> My question then is: How does one override the ID (or other div class) of a field in Django before its passed to the view? -
I want to get username and email from user not backend when i use Django python-social-auth
There. I want to use Django python-social-auth to get login information from backend('kakao') the kakao give me only username look like : 123124153 it didn't give email address. so I want to change username looks normally and get email address by user. this is setting.py SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.user.create_user', 'authentication.social.require_info', 'social.pipeline.mail.mail_validation', 'social.pipeline.social_auth.associate_by_email', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details', ) this is social.py from django.shortcuts import redirect from social.pipeline.partial import partial from social.pipeline.user import USER_FIELDS @partial def require_info(strategy, details, user=None, is_new=False, *args, **kwargs): backend = kwargs.get('backend') if user and user.email: return elif is_new and not details.get('email'): userEmail = strategy.request_data().get('email') if userEmail: details['email'] = userEmail else: return redirect('acquire_email') this is view.py def acquire_email(request, template_name="registration/getuser.html"): backend = request.session['partial_pipeline']['kakao'] return render(request, template_name, {"backend": backend}) this is template: getuser.html {% extends "base.html" %} {% block title %}Wrong Answer NOTE{% endblock %} {% block content %} <div class="container"> <div class="center-form panel"> <div class="panel-body"> <h4 class="text-center"><i class="ion-person-add"></i> Get user information</h4> <form method="post" role = "form" action="{% url 'social:complete' 'kakao' %}"> {% csrf_token %} <div class="form-group has-feedback"> {{ form.username }} <span class="ion-person form-control-feedback"></span> </div> <div class="form-group has-feedback" > {{ form.email }} <span class="ion-at form-control-feedback"></span> </div> <button type="submit" class="btn btn-block btn-primary">Submit</button> <br/> </form> </div> </div> </div> {% … -
celery parameters has correct number of arguments
I am using celery 4.0 and was following this site. http://docs.celeryproject.org/en/latest/userguide/tasks.html#blog-tasks-py views.py task = test2.delay(document.name, document.id) Tasks.py @shared_task(name="test2") def test2(param, job_id): return 'The test task executed with argument "%s" ' % param However, it throws an exception TypeError: test2() takes exactly 1 argument (2 given). This is funny since i have 2 arguments and it works in the site i shown. -
Asyncio with Django
I'm trying to use asyncio in my Django post processing like: query : # a query to my model tasks = [] for record in query: tasks.append(do_something_with_google_calendar(record)) loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks)) loop.close() But I just get an error while executing: loop = asyncio.get_event_loop() RuntimeError: There is no current event loop in thread 'Thread-17'. Any ideas? Thank you in advance -
How do i change choices in a DjangoAdmin field if i change another field?
Im creating a db for an hotel and i want to be able to have a field listing all Seasons related (FK) to the hotel selected in the previous field. class PriceTable(models.Model): client = models.ForeignKey(Cliente, on_delete=models.CASCADE) year = models.ForeignKey(Ano, on_delete=models.CASCADE) hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) season_price = models.ForeignKey(SeasonPrice, on_delete=models.CASCADE) class SeasonPrice(models.Model): season = models.ForeignKey(Season, on_delete=models.CASCADE) class Season(models.Model): name = models.CharField(max_length=200) date_in = models.DateField() date_end = models.DateField() hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) In django admin page how can i list in season_price all the seasons that have a foreign key of the hotel i just choose? Here is an image to better understand what i want to acomplish: [Django admin interface explanation][1] -
What language should I use for an SQL database to make APIs for Android and Web apps
I want to create APIs for an SQL database for my Android App and also a Web app. Which language would be best to use for the back-end. I want security and speed both here. From some research which I have done on the internet, following are the most probable options for me: Java's Spring framework Python's Django framework Node.js - Express framework PHP's CodeIgniter framework (this is what we use currently) -
How do I reuse a snippet of HTML in django
I'm really new to Django and have been searching everywhere for an answer to this, but because of my novice level what I read in the docs is completely flying over my head. I would really appreciate if someone could explain the simplest steps how to achieve re-usabiity of a snippet of HTML in the most basic ways. I have a main template HTML for a view the lists all my diary entries. Within the view I have a snippet of HTML that represents a diary entry, which shows time and date of entry, title and description and then an option to delete it: <div class="entry-item"> <div class="item-time-date"> <p>TUE</p> <p>24 Nov</p> <p>16:00</p> </div> <div class="item-detail"> <p class="item-detail-title"></p> <div class="divider"></div> <p class="item-detail-text"></p> </div> <div class="item-options"> <button class="diaryBtn">X</button> </div> </div> Now I want to be able to iterate over my Entry objects from the database and render each Entry using the above HTML code. Obviously I will put {{variable}} tags in the relevant places to allow for data to be populated. What's the most elegant way that Django provides to do this? Thanks Francis -
Django: Include Media (css/js) in Class-Based Views
I am updating old django code from method-based views to class-based views. I know how to include media (css/js) in forms via the Media class How can I use the media class if my class based view does not use a single form? -
Get system time w/timezone in Django bypassing default timezone
As long as I'm using plain ol' Python shell, the datetime.datetime.now() command works fine to get system's local (non-UTC) time. But I'm working on a Django project where the time zone is changed in settings.py with TIME_ZONE = 'UTC'. I've tried many solutions from django.utils timezone to tzlocal module, but none of them works. All of them return either incorrect or UTC time. All of the solutions work if I change the timezone in settings.py to my local timezone. But I can't do that, so is there any way to bypass the default timezone option in settings.py? Thanks. -
How to save a form with javascript
I'm using a form for a template but then I use javascript to save the data in the database. What should I write in the view? I did something (see below) and it's working but I'm not sure if it is good a practice. Also I don't know how to render a context_dict AND a form. I need data for the base template, so I must call the data in the context with {{ user.username }} without other prefix My views.py: def myview(request): context_dict=services.get_advanced_data_for_views(request) if request.method == 'POST': #nothing, I don't need this else: form = form.myformForm() return render(request, 'core/conoscenze_rapporti.html', {'form': form , 'context_dict': context_dict}) #called by javascript def save_data(request): if request.method == 'POST' and request.is_ajax(): data1 = request.POST.get('mydata1', None) ... s = mymodel.objects.get_or_create(myfield=data, etc) s.myattribute = etc s.save() My context_dict: context_dict = {} u = request.user context_dict['user'] = u ... My form.py: class myformForm(forms.Form): myfield1 = forms.ChoiceField(choices=mychoice, label='my field 1', required=True, initial='r') myfield2 = ... My template.html: <form class='form-horizontal form-inline' role='form' id='myform_form' enctype='multipart/form-data' method='post' action='../myurl/'> {% csrf_token %} {{ form.myfield1.errors }} {{ form.myfield1.label }} {{ form.myfield1 }} {{ form.myfield1.help_text }} ... </form> <div> <button id='btn-save' class='btn btn-success' style='display: none'>Save the change</button> </div> My javascript: document.getElementById('btn-save').addEventListener('click', function() { $.ajax({type: 'POST', … -
Django with legacy database - how to work with DB sequences?
Given a database table that was created using this SQL query: CREATE TABLE Bill ( Time DATE NOT NULL , Address VARCHAR2 (60) NOT NULL , ID NUMBER NOT NULL ) ; ALTER TABLE Bill ADD CONSTRAINT Bill_PK PRIMARY KEY ( ID ) ; CREATE SEQUENCE Bill_ID_SEQ START WITH 1 NOCACHE ORDER ; CREATE OR REPLACE TRIGGER Bill_ID_TRG BEFORE INSERT ON Paragony FOR EACH ROW BEGIN :NEW.ID := Bill_ID_SEQ.NEXTVAL; END; I have to use it with Django ORM so I have run inspectdb command. It is the autogenerated code: class Bill(models.Model): time = models.DateField() address = models.CharField(max_length=60) id = models.IntegerField(primary_key=True) class Meta: managed = False db_table = 'bill' After saving it to app' models.py file and running migrations everything was fine. I could read DB like it was created using ORM. However there was a problem with creating rows in Bill table. It is simple form for Bill model: class BillForm(ModelForm): class Meta: model = Bill fields = ('time', 'address') The problem is that I can't retrieve the ID generated with the DB sequence. Adding id field to Form won't work because we have to generate it with code and then pass as a argument. Even than database will create … -
Django - Mysql Integrity error 1048, “Column 'id_fleet_id' cannot be null” while getting data from ajax
--------------------------Forms.py------------------- class PostForm(forms.ModelForm): text = forms.CharField(widget=forms.TextInput(attrs={'id': 'post-text', 'placeholder': 'Say something...'})) class Meta: model = Post fields = ['text'] -------------Views.py---------------------- def create_post(request): if request.method == 'POST': post_text = request.POST.get('the_post') response_data = {} post = Post(text=post_text, author=request.user) post.save() response_data['result'] = 'Create post successful!' response_data['postpk'] = post.pk response_data['text'] = post.text response_data['created'] = post.created.strftime('%B %d, %Y %I:%M %p') response_data['author'] = post.author.username return HttpResponse( json.dumps(response_data), content_type="application/json" ) else: return HttpResponse( json.dumps({"nothing to see": "this isn't happening"}), content_type="application/json" ) --------------Main.js----------------------- $(function() { $('#post-form').on('submit', function(event){ event.preventDefault(); console.log("form submitted!") }); function create_post() { console.log("create post is working!") url : "create_post/", type : "POST", data : { the_post : $('#post-text').val() }, success : function(json) { $('#post-text').val(''); console.log(json); $("#talk").prepend("<li><strong>"+json.text+"</strong> - <em> "+json.author+"</em> - <span> "+json.created+ "</span> - <a id='delete-post-"+json.postpk+"'>delete me</a></li>"); console.log("success"); }, error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+ " <a href='#' class='close'>&times;</a></div>"); console.log(xhr.status + ": " + xhr.responseText); } /*});*/ }; function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } … -
Changing Database in run time and making the changes reflect in Django in run time
I am developing a Cloud based data analysis tool, and I am using Django(1.10) for that. I have to add columns to the existing tables, create new tables, change data-type of columns(part of data-cleaning activity) at the run time and can't figure out a way to update/reflect those changes, in run time, in the Django model, because those changes will be required in further analysis process. I have looked into 'inspectdb' and 'syncdb', but all of these options would require taking the portal offline and then making those changes, which I don't want. Please can you suggest a solution or a work-around of how to achieve this. -
Django site- administrator user is 'not defined'
I am responsible for the development of my company's internal website- used for managing projects/ calendars/ client information, placing orders with suppliers, etc. The site has been written in Python/ Django (it was originally written by someone else, and I took over the development when they left the company). I am the 'administrator' of the site, and when I browse to www.mysite.co.uk/admin, I have full access to all of the admin features that Django provides. However, if I try to browse to www.mysite.co.uk (i.e. the actual website that everyone else is using, not the admin part of it), I get a NameError page that says that the user is not defined... this seems a bit weird given that I am the administrator... If I clear my browsing history (so that my login details for the site are forgotten), and then go to www.mysite.co.uk, I am taken to the login page for the site. However, as soon as I enter my login details, and click "Log in", I get the same NameError page... so it seems that my authentication is going through successfully, but that Django then thinks that my user profile is not defined. Why is this? Has my user … -
Django Admin override UserAmin
I used this admin code, to adjust my class CustomUserAdmin(UserAdmin): list_display = UserAdmin.list_display + ('show_url', 'date_joined') def show_url(self, obj): return format_html("<a href='{url}'>Link</a>", url=obj.extendeduser.get_link()) admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) But the admin just seems to ignore this and displays the old admin page. What could i have missed? -
Django dynamic to display formfields by context
I am pretty much a long time beginner with Django, so sorry for this question if it is too broad, misplaced or even obvious. I have read several posts on here, and a few examples such as this or this, but none describe achieving what I need to do. Imagine I have the form below for submitting a project and I want to display fields and add them or reveal them in the form client side, but only if certain input criteria are met in the form - eg. if the project to be submitted is part of a series of projects (is_project_series), then I might want to display a number of form fields for eg. how many projects should be in the series or how they should be named or numbered, maybe even generate further dynamic input based on the input of these dynamic fields also - otherwise by default the project form might only display the most simple fields for projectname, path etc. and a boolean for 'Is Project Series' which would reveal the hidden fields dynamically when True. I was wondering what skilled Django users do to get this sort of functionality and if there are any … -
Can't update the model instance in Django?
I am trying to make a Q/A website in Django and I have trouble in the creating the question's update view for the app. Here is the QuestionUpdateView class class QuestionUpdateView(UpdateView): model = models.Question form_class = forms.QuestionForm template_name = 'Questionnaire/form.html' success_url = 'question:details' def get_success_url(self, **kwargs): return redirect(self.success_url, self.kwargs['slug']) def post(self, request, *args, **kwargs): filled_form = self.form_class(request.POST) if self.form_class.is_valid(filled_form): model = filled_form.save(commit=False) model.clean() model.save() return self.get_success_url(slug=model.slug) And here is the Question model class Question(models.Model): title = models.CharField(max_length=250) body = models.TextField() asked_by = models.ForeignKey(User) pub_date = models.DateTimeField(auto_now_add=timezone.now) slug = models.SlugField(max_length=250, unique=True, default=None) likes = models.PositiveIntegerField(editable=False, default=0) dislikes = models.PositiveIntegerField(editable=False, default=0) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if self.slug is None: self.slug = slugify(self.title)+'-'+str(self.id) super(Question, self).save(force_insert, force_update, using, update_fields) def get_absolute_url(self): return reverse('question:details', kwargs={'slug': self.slug}) def __str__(self): return self.title What is the problem with the code? Whenever i update the question it create's a new instance instead of saving the one got from the form class. -
Unit tests fail to load with Django in Visual Studio
I am using Django 1.10.5 with Visual Studio 2015. My project is running in a virtual environment. I am following the beginner tutorial here. The project runs fine, but when I try to run unit tests from the Visual Studio "Test Explorer" they fail with to error: "django.core.exceptions.AppRegistryNotReady: App aren't loaded yet." This is my test class: import datetime from django.test import TestCase from django.utils import timezone from .models import Question class QuestionTestCase(TestCase): def test_wasPublishedRecently_FutureQuestion_FALSE(self): futureTime = timezone.now() + datetime.timedelta(days=30) futureQuestion = Question(datePublished=futureTime) self.assertIs(futureQuestion.wasPublishedRecently(), False) -
Django psycopg2 kills the Gunicorn eventlet worker.(Hangs on db access code)
I have a Django server, running on Gunicorn eventlet server. But with simultaneous requests, the server hangs(accepts new requests but doesn't process existing ones) for 30 seconds and restarts itself. Basically, psycopg2 kills it. I suspect that Django imports psycopg2 before monkey_patch() call, which I put in SETTINGS.py. The question is, where should I call eventlet.monkey_patch() when starting a Django project if that's the problem? If not, what can cause this? -
How to copy data between two django(1.3) models?
I would like to know where can I read about it. I have two very similar models, what I need to do is, select all alunos from a certain "ano" in 'Aluno' and than check if they exist in 'AlunoTemporario' comparing their "matriculas", if the aluno doesn't exist, I would copy data from one model to another, but I don't know how to do it. I'm using Django 1.3. class Aluno(models.Model): codigo = models.AutoField(primary_key=True) nome = models.CharField("Nome", max_length=55) matricula = models.CharField("Matrícula",max_length=15,unique = True) numero_pasta = models.CharField("Número da pasta", max_length=10) curso = models.CharField("Curso", max_length=100) turma = models.CharField("Turma", max_length=50) turno = models.CharField("Turno", max_length=10) ano = models.CharField("Ano", max_length=10, choices = Choices.ano) ativo = models.BooleanField(default=1) importado = models.BooleanField(default=1) def __unicode__(self): return self.nome class AlunoTemporario(models.Model): codigo = models.AutoField(primary_key=True) nome = models.CharField("Nome", max_length=55) matricula = models.CharField("Matrícula",max_length=15) numero_pasta = models.CharField("Número da pasta", max_length=10) curso = models.CharField("Curso", max_length=100) turma = models.CharField("Turma", max_length=50) turno = models.CharField("Turno", max_length=10) ano = models.CharField("Ano", max_length=10, choices = Choices.ano) datahoraImportacao = models.DateTimeField("Data e Hora Importação", blank = True, null = True) ativo = models.BooleanField(default=1) -
Django proxy model to different database
Situation We have a few different applications which use tickets from a ticket support system for different kinds of functionality. First of all we have an application which has a few models that represent the models of our ticket support system Kayako. This application should not know anything about other applications that make use of it and should remain as generic as possible. Since this application is using existing tables of Kayako we have it running on the same database. Let's call this application kayakodb. One application links customers from our customer database to tickets in the ticket support system. Previously this system had it's own representation of the tickets inside our ticket support system, querying for tickets by using an API provided by kayakodb. It then used this representation of tickets to link customers and domains to. This however was too complex and not very logical. So we opted to switch it to a proxy model and move the models that represent the links to customers and domains to kayakodb. Let's call this application sidebar. Another, new application, shows the tickets from the ticket support system in a clear overview alongside calls so our support department can easily see … -
How to implement websocket for push message using django-rest-framework as backend and angular2 as frontend?
I want to implement websocket to send push notification to client. I am using django-rest framework as backend and angular2 as frontend. I know that django support HTTP protocol only. And I am unable to get any such links,blogs or resource which helps me to achieve websocket completely. Currently I am using pooling from frontend. There are some third party apps which I found and may be useful for implementing push message. They are... pywebsocket tornado Django Channels I don't think showing some code is significant here because i have no code relevent to implementation of websocket. So can you people suggest me the best way to implement this thing.Any link,any blog or any code which may help. -
Django CBV - change FBV to CBV
Writing my first "real" django project I realized that my views are really huge. I try to convert it into CBV (as additional django training). Here are my fbv views: def index(request): context = {} categories = Category.objects.select_related() subcategories = SubCategory.objects.all() context['categories'] = categories context['subcategories'] = subcategories return render(request, 'mainapp/index.html', context) def category(request, category_name_slug): context = {} try: category = Category.objects.get(slug=category_name_slug) subcategory = SubCategory.objects.filter(category=category) context['subcategories'] = subcategory context['category'] = category except Category.DoesNotExist: raise Http404("Category doesn't exist") return render(request, 'mainapp/category.html', context) def subcategory(request, category_name_slug, subcategory_name_slug): context = {} form = SiteAddForm(initial={'url': 'http://'}) context['form'] = form try: category = Category.objects.get(slug=category_name_slug) subcategory = SubCategory.objects.filter(category=category ).get(slug=subcategory_name_slug) sites = Site.objects.filter(subcategory=subcategory, is_active=True) context['subcategory'] = subcategory context['category'] = category context['sites'] = sites except (SubCategory.DoesNotExist, Category.DoesNotExist): raise Http404("Nie ma takiej strony") if request.method == 'POST': form = SiteAddForm(request.POST) if form.is_valid(): siteurl = form.cleaned_data['url'] context['siteurl'] = siteurl try: page = AddNewSite(siteurl) except: print('ERRROR') context['Error'] = "URL is not responding" return render(request, 'mainapp/subcategory.html', context) title = page.title() description = page.description() keywords = page.keywords() if page.check_url_in_database(): context['Error'] = "Site already in database" return render(request, 'mainapp/subcategory.html', context) else: form_extended = SiteAddFormFull(initial={'url': siteurl, 'name': title, 'description': description, 'keywords': keywords}) context['form_extended'] = form_extended if request.method == 'POST': form_extended = SiteAddFormFull(request.POST) if form_extended.is_valid(): keywords = … -
DRF 3 generate model field from multiple request params
How to generate a model instance field from two request parameters that are not part of the model instance ? E.g. Generate a geohash model field from latitude, longitude in request parameters