Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DjangoFilters Add filter from another model
I modified my DjangoTables class to this class Mark_Table(tables.Table): teacher = tables.Column(accessor='id_subject.id_teacher.name') group = tables.Column(accessor='id_student.id_group.name') course = tables.Column(accessor='id_student.id_group.id_course.course') curator = tables.Column(accessor='id_student.id_group.curator.name') class Meta: model = Mark fields = ['id_student', 'id_subject','mark' ,'teacher', 'group', 'course', 'curator',] attrs = {'class': 'paleblue'} I have filters for it class Mark_Filters(filters.FilterSet): class Meta: model = Mark fields = '__all__' but they work only for fields which are in model Mark. How can i add filters to another models, but in same view. I would like filters to this fields: Teacher. name, Group. name, Course. course, Curator. name, Is there any accessors for filters or something like this. didn`t find anything in DjangoFilters documentation. Thanks in advance My models -
How to enable WSGIPassAuthorization for Django?
I am testing my Django API endpoints but I need to enable WSGIPassAuthorization to let Authorization header be received. Where should I enable it? PS: I am on macOS, but any answer might be useful! -
connecting to mlabs MongoDB using Django fails
error while connecting to mlab mongodb database using django. tried many answers and modified settings.py file but it didn't work how to modify the settings.py file to connect to mlabs mongodb. -
How to submit form on button click and then run AJAX call assigned to the same button
I am wrtitng a simple Airbnb scraper. When the user submits a form with city name filled in, he will get a table with prices and links rendered by AJAX on the same page. The form is in my "index.html": <form action="" method="post"> {% csrf_token %} {{ form }} <input id="create_table" type="submit" value="View results" /> </form> I am using two views: "index" and "results". "Index" is just for collecting the city name and passing it to the "results" (which is called by AJAX, see below): def index(request): if request.method == 'POST': form = RoomForm(request.POST) if form.is_valid(): city = form.cleaned_data['city'].title() request.session['city'] = city else: form = RoomForm() context = {'form': form} return render(request, 'javascript/index.html', context) def results(request): if request.is_ajax(): city = request.session.get('city') url = 'https://www.airbnb.pl/s/' + str(city) +' # "results" scraping code continues... I need to pass the city variable from "index" to "results", hence the request.session part. However I think the variable never gets assigned because the AJAX call: function create_table() { $.ajax({ //method: "GET", //url: "/api/data/", success: function(data){ $('#table').load('http://127.0.0.1:8000/results', function(){ $('#go_back').remove(); }); }, error: function(error_data){ console.log("errorrr") console.log(error_data) } }) } document.getElementById("create_table").onclick = function() { create_table(); return false; , which is assigned to the same submit button, is launched first … -
1050, "Table 'dolaposcrumy_scrumygoals' already exists"
Thats my project When i run migrations i get this error: django.db.utils.OperationalError: (1050, "Table 'dolaposcrumy_scrumygoals' already exists") -
how to use googlefinance.client in django?
I want to develop an application where i want to use googlefinance.client as a python client library for google finance api. A little bit confused how can implement it on my django project. -
Django CACHALOT_INVALIDATE_RAW doesn't sem to work
I have 2 databases: one for storing entities only (users, managers, etc) - low volume of data. another for storing hundreds of entries per second. In order not to overkill the performance with django cachalot invalidations, all my queries to database 2. are made with raw SQL, and I've set the parameter : CACHALOT_INVALIDATE_RAW = True However, my webapp seems to completely freeze when I set CACHALOT_ENABLED = True My cachalot config: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': 'memcacheddb.aaaa.0001.euc1.cache.amazonaws.com:11211', } CACHALOT_ENABLED = False CACHALOT_TIMEOUT = 120 # 2 minutes CACHALOT_INVALIDATE_RAW = False # cachalot disabled for RAW SQL queries Does anyone know how to completely disable cachalot for all RAW SQL queries, or to completely disable it for a specific DB? Thanks! -
form.is_valid() always fails
I am trying to create a very basic form that allows the user to upload a txt file. the function form.is_valid() always fails and I don't know what to do. This is my code: (very similar to the example in the django documentation): views.py from django import forms from django.http import HttpResponse from django.shortcuts import render class UploadFileForm(forms.Form): # title = forms.CharField(max_length=50) file = forms.FileField() def handle_uploaded_file(f): with open('some/file/name.txt', 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) def home(request): if request.method == 'POST': print(1) form = UploadFileForm(request.POST, request.FILES) print(form.errors) print(2) if form.is_valid(): print(3) handle_uploaded_file(request.FILES['file']) return HttpResponse('thanks') else: form = UploadFileForm() return render(request, 'home.html', {'form': form}) home.html {% extends "base.html" %} {% block content %} <div> <div class="'chooseFile'"> <h3>Choose file to attache</h3> </div> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.file }} <button type="submit" class="save btn btn-default" value="Submit"></button> </form> </div> {% endblock %} url.py from django.urls import path from django.contrib import admin from django.conf.urls import url from adoptions import views urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', views.home, name='home'), url(r'^$', views.home, name='/success/url/'), ] -
create associated record with new object in Django
I'm using Django 2 I have two models class Chapter(models.Model): name = models.CharField(max_length=250, blank=False) def __str__(self): return self.name class ChapterQuestion(models.Model): chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE) word = models.CharField(max_length=250) definition = models.CharField(max_length=250) def __str__(self): return self.word I want to be able to add multiple questions while creating chapter. All will be done using single form only. The view so far I have written is class NewChapter(CreateView): template_name = 'courses/chapter/new_chapter.html' model = Chapter fields = ['name'] def get_context_data(self, **kwargs): context = super(NewChapter, self).get_context_data(**kwargs) course = Course.objects.get(pk=self.kwargs['course_id']) if course is None: messages.error(self.request, 'Course not found') return reverse('course:list') context['course'] = course return context def form_valid(self, form): form.instance.created_by = self.request.user form.instance.course = Course.objects.get(pk=self.kwargs['course_id']) form.save() return super().form_valid(form) def get_success_url(self): return reverse('course:detail', self.kwargs['course_id']) But couldn't understand how to start. Any guide or tutorial will be appreciable. -
Django FieldError, adding users to groups
I want the logged in user to be able to add other users to a 'team' they have created. To do this I have created a form that asks the user to enter the 'teamid' of the team they want to add the user to and the 'userid' of the user they want to add.In the form when the user selects the teamid, i want them to only be able to select from a list of the teams they have created, (where owner in my Team model = logged in user). This is what I have so far which doesn't work, it gives me a FieldError when i load the invite view. My models: class Team(models.Model): name = models.CharField(max_length=100) venue = models.CharField(max_length=100) countryID = models.ForeignKey(Countries, on_delete=models.CASCADE) owner = models.ForeignKey(User) def __str__(self): return self.name class UserTeams(models.Model): userID = models.ForeignKey(User,on_delete=models.CASCADE) teamID = models.ForeignKey(Team,on_delete=models.CASCADE) My view: def invite(request): if request.method == 'POST': form = InvitePlayerForm(request.user, request.POST) if form.is_valid(): userteam = form.save(commit=False) userteam.save() else: form = InvitePlayerForm(request.user) query = UserTeams.objects.all() return render(request, 'teammanager/invite.html', { "invite": query, "form": form }) My form: class InvitePlayerForm(forms.ModelForm): class Meta: model = UserTeams fields = ['userID','teamID'] def __init__(self,user,*args,**kwargs): super(InvitePlayerForm,self ).__init__(user,*args,**kwargs) self.fields['teamID'].queryset = Team.objects.filter(userteam__UserId=user.id) My HTML: <html> <body> <h4>Invite players … -
detail view near list view with django
I have this message list view rendere with a function that return template name, message list, message count. Now I need to show the message detail when I click on a message preview on the left. How can I reach this in django? screenshot -
Error "TypeError context must be a dict rather than Context" on Django 1.11
I received a message TypeError context must be a dict rather than Context. But don't know how to fix it. def comment(request,id): if id: r = Restaurant.objects.get(id=id) else: return HttpResponseRedirect("/restaurants_list/") if request.POST: visitor = request.POST['visitor'] content = request.POST['content'] email = request.POST['email'] date_time = timezone.localtime(timezone()) Comment.objects.create( visitor=visitor, email=email, content=content, date_time=date_time, restaurant=r ) return render_to_response('comments.html', RequestContext(request, locals())) -
Populate existing model objects with AutoSlugField
I need to populate an AutoslugField for already existing model objects. My bad realized that the slug field was so handy and better that using pk for security purposes. I already have model objects (rows) in the database. I want to add the AutoSlugField to them. Anybody know how I can achieve this. Thanks -
My nginx server access log has some unexpected entries like
115.61.87.97 - - [17/Mar/2018:09:20:09 +0000] "GET http://www.meituan.com/ HTTP/1.1" 302 0 "http://www.meituan.com/" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0) 115.61.87.97 - - [17/Mar/2018:09:58:49 +0000] "GET http://www.cnwest.com/ HTTP/1.1" 302 0 "http://www.cnwest.com/" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)" while there should only be access logs of my website can someone explain the cause? 14.139.240.82 - - [17/Mar/2018:10:05:46 +0000] "GET /account/login/ HTTP/1.1" 200 889 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0" something like this. -
django-admin makemessages --no-obsolete doesn't seem to working
First of all, I am expecting --no-obsolete would comment out msgid and msgstr if gettext is deleted, right? How I am testing is: I wrote gettext("some string here") in view I ran makemessages command It wrote a .po file as expected Then I deleted gettext() line from view and saved file, verified runserver working. I ran makemessages --no-obsolete and it has not made any changes to .po file. .po file content extract . #. Translators: This message is a test of wrap line #: servers/views.py:31 msgid "Do let me know if it works." msgstr "" -
Why am I seeing the following error in Django?
So I have a user form in my Django project. After Submitting the form I want to redirect the user to another form (for additional details). But I am seeing the following error NoReverseMatch at /incubators/add-incuabtor/ Reverse for 'details' with keyword arguments '{'pk': 15}' not found. 1 pattern(s) tried: ['incubators/(?P<incubator_id>[0-9]+)'] Request Method: POST Request URL: http://127.0.0.1:8000/incubators/add-incuabtor/ I have the following url pattern: app_name = 'main' urlpatterns = [ url(r'^home/', views.home, name='home'), # Home page url(r'incubators/$', views.incubators, name='incubators'), # Incubator list page url(r'about/', views.about, name='about'), # Websie about page url(r'results', views.result, name = 'result'), # For search function url(r'incubators/(?P<incubator_id>[0-9]+)', views.details, name = 'details'), # shows details of incubators url(r'incubators/add-incuabtor/$', views.AddIncubator.as_view(), name = 'add-incubator'), # Adding Inc url(r'/add-details/', views.AddDetails.as_view(), name = 'add-details'), #for additional details ] Following is my models.py class Incubators(models.Model): # These are our database files for the Incubator Portal incubator_name = models.CharField(max_length=30) owner = models.CharField(max_length=30) city_location = models.CharField(max_length=30) description = models.TextField(max_length=100) logo = models.FileField() verify = models.BooleanField(default = False) def get_absolute_url(self): return reverse('main:details', kwargs={'pk': self.pk}) def __str__(self): # Displays the following stuff when a query is made return self.incubator_name + '-' + self.owner class Details(models.Model): incubator = models.ForeignKey(Incubators, on_delete = models.CASCADE, related_name='banana_pudding') inc_name = models.CharField(max_length = 30) inc_img = … -
How to annotate field from model that not related with current
I have 4 models: class User(AbstractBaseUser, PermissionsMixin): ... class Specialty(models.Model): ... class Order(models.Model): contractor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='contractor', null=True, blank=True, on_delete=models.CASCADE, verbose_name=_('Contractor')) ... specialty = models.ForeignKey(Specialty, blank=True, null=True, on_delete=models.CASCADE, verbose_name=_('Specialty')) ... class Review(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) rating ... I got specialty page, where I want to get users that offer services in this specialty, ordered by rating. Here is QuerySet, where I get users. contractors = User.objects.extra(select={ 'rating': """ SELECT AVG (review_review.rating) FROM review_review LEFT JOIN order_order ON review_review.order_id = order_order.id LEFT JOIN specialty_specialty ON order_order.specialty_id = specialty_specialty.id WHERE order_order.contractor_id = account_user.id AND specialty_specialty.slug = %s """, }, select_params=(slug))\ .filter(userspecialty__specialty__slug=slug).order_by('rating') But i think, that using .extra() method is not a good practice. How can I write this with other Django ORM methods? Thanks for answering! -
How to Create Multi User Account?
Pls how can i create multi-user login page for Student, Tutor, and Admin... Example, I will like the Student to login with their Identity ID while the Tutor and Admin logn with an E-mail on the same login page. -
Best way to design organization-specific models in Django?
This is a database model design question. Let's say I'm designing an app like Slack. Slack has multiple Organizations, and within each Organization there are objects that only should be accessed by that Organization (eg. its chat records, files, etc.). What is the best way to set up these per-Organization objects in Django? A simple solution is to attach a ForeignKey to every one of these objects. Like so: class Organization(models.Model): # ... class File(models.Model): organization = models.ForeignKey( 'Organization', on_delete=models.CASCADE, ) # ... class ChatThread(models.Model): organization = models.ForeignKey( 'Organization', on_delete=models.CASCADE, ) # ... But if we do it like this, we need to put an index on organization, and since there are many such per-Organization objects, it seems a little wasteful. Is there a cleaner way to design this? -
extending a template from project level in django
My Tree looks like this: -Project -App1 -templates -App1(templates here) -App2 -templates -App2 (templates here) -templates (files here) in a template file in, for example, app1, how do I extend from base.html which is in my project templates directory? It is automatically looking in my app directory. What I'm trying at the moment is: {% extends '/base.html' %} no big surprise that thats not working. thx for the help in advance. -
Assign both HTML method='post' and AJAX call to Django's form submit button
In my forms.py I have the following form: from django import forms class RoomForm(forms.Form): city = forms.CharField() In index.html it is entered like this: <form action="" method="post"> {% csrf_token %} {{ form }} <input id="create_table" type="submit" value="View results" /> </form> The puropose of this form is to take user input (city name) which will be then processed by view functions. It takes the city name and puts it in the link of the page that will be scraped by the view function. My view functions are: def index(request): if request.method == 'POST': form = RoomForm(request.POST) if form.is_valid(): global form_data form_data = form.cleaned_data print(form_data['city']) #return HttpResponseRedirect('results') else: form = RoomForm() context = {'form': form} return render(request, 'javascript/index.html', context) def results(request): if request.is_ajax(): city = form_data['city'].title() prices = [] real_prices = [] links = [] url = 'https://www.airbnb.pl/s/' + city +'--Hiszpania/homes?refinement_paths%5B%5D=%2Fhomes&query=' + city + '%2C%20Hiszpania&checkout=2018-04-22&children=0&infants=0&adults=2&guests=2&allow_override%5B%5D=&price_max=252&room_types%5B%5D=Entire%20home%2Fapt&min_beds=0&s_tag=Ph6ohhjw' response = requests.get(url) soup = bs4.BeautifulSoup(response.text) #prices page_selectors = soup.select('._1bdke5s') print(len(page_selectors)) last_page_selector = page_selectors[len(page_selectors) - 10]##############-15 last_page_selector = last_page_selector.getText() for x in range(0, int(last_page_selector)): response = requests.get(url + '&section_offset=' + str(x)) response_text = response.text soup = bs4.BeautifulSoup(response_text) spans = soup.select('._hylizj6 span') for i in range(0, len(spans)): prices.append(spans[i].getText()) for price in prices: if 'zł' in price: real_prices.append(price) #links … -
using pipe delimited string in URL in django
trying to pass a pipe delimited string as a parameter in my url in django, it fails to route to the respective view. this is my pipe delimited string "main/1|adel|1|1989-09-19|1|1|test alert|2018-03-16-09-26-00|test module|1|1|test encounter" and this is my url pattern url(r'^main/(?P<message>\w+)/$',views.TheView.as_view({'get':'view'}),name = 'main') -
Django - Form across multiple views with progress saving
I'm working on a Django project and to make the forms experience far smoother I want to spread a ModelForm across a few pages. It would be ideal if users who are logged in can save their progress in the form without actually posting the content (in this case, a JobApplication where users can come back to filling in info without actually sending off the application). Currently I have looked at other answers on SO such as this one; but this only shows me how to utilise caching to store information between the views where the form is present. Models.py (models, forms and views have been simplified for readability): class JobApplication(models.Model): job = models.ForeignKey(JobPost,on_delete=models.SET_NULL,...) user = models.ForeignKey(AUTH_USER_MODEL,...) details = models.CharField(max_length=300) skills = models.CharField(max_length=300) feedback = models.CharField(max_length=300) #... [insert more fields] ... Forms.py: class Application(forms.ModelForm): details = models.CharField() # To go in page 1 of the form process skills = models.CharField() # To go in page 2 feedback = models.CharField() # To go in page 3 class Meta: model = JobApplication fields = ['details','skills','feedback'] Views.py: from . import forms def view1(request): form = forms.Application() if request.method == 'POST': form = forms.Application(data=request.POST) ... some logic here which I am not sure of … -
DjangoTables2 Add column from another model
I have DjangoTable for this model: class Mark(models.Model) id_mark = models.AutoField(primary_key=True, verbose_name='Id запису') id_student = models.ForeignKey(Student, blank=False, null=False, default=None, on_delete=models.CASCADE,verbose_name='Студент') id_subject = models.ForeignKey(Subject, blank=False, null=False, default=None, on_delete=models.CASCADE,verbose_name='Предмет') mark = models.DecimalField(decimal_places=3, max_digits=5, blank=False, null=False, default=None, verbose_name='Оцінка') class Meta: verbose_name = 'Оцінка' verbose_name_plural = 'Оцінки' def __str__(self): return "{} {} {}".format(self.id_student, self.id_subject, self.mark) Table: class Mark_Table(tables.Table): class Meta: model = Mark exclude = ('id_mark',) attrs = {'class': 'paleblue'} I want to add column with values from this model: class Subject(models.Model) id_subject = models.AutoField(primary_key=True, verbose_name='Id предмету') id_teacher = models.ForeignKey(Teacher, blank=False, null=False, default=None, on_delete=models.CASCADE,verbose_name='Вчитель') name = models.CharField(max_length=32, blank=False, null=False, default=None, verbose_name='Назва предмету') class Meta: verbose_name = 'Предмет' verbose_name_plural = 'Предмети' def __str__(self): return "{}".format(self.name) Now i have fields Student Subject Mark, I want to add filed id_teacher from another model, and relationship must remain. -
Django - delete records with same many to many associations
I have two models: class DjProfile(DateTimeModel): name = models.CharField(max_length=150, db_index=True) ... class Track(models.Model): all_producers = models.ManyToManyField(DjProfile) all_remixers = models.ManyToManyField(DjProfile) title = models.CharField(max_length=200, db_index=True) track_link = models.CharField(max_length=150, blank=True, null=True) ... I have many records of Track with same title, same values of all_producers and all_remixers but different track_link. I'd like to keep only one record of those, regardless of track_link value, that may vary. I might loop over all the records of Track, but I've a pretty large tables (like 2M records) and I'm afraid about performance. What the best way to approach this problem?