Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Database error in Django-admin is not a vulnerability
Not a question, but leaving this here in case it is useful to others. I ran into interesting behaviour of Django Admin, which seemed like it could point to a vulnerability. Upon closer inspection, this was not a vulnerability but expected behaviour. For some pages of Django Admin, if you pass unexpected/incorrect GET-variables, Django-admin will redirect you to a page with an error flag set to 1 (typically e=1) in the URL. If you pass unexpected/incorrect GET-variables and e=1 is already set in the URL, Django-admin will display a 'Database error'. I first thought this might be SQL injection related, but upon closed inspection, I found out that the error is not the result of a failed query or anything like that. The relevant source code: except IncorrectLookupParameters: # Wacky lookup parameters were given, so redirect to the main # changelist page, without parameters, and pass an 'invalid=1' # parameter via the query string. If wacky parameters were given # and the 'invalid=1' parameter was already in the query string, # something is screwed up with the database, so display an error # page. if ERROR_FLAG in request.GET.keys(): return SimpleTemplateResponse('admin/invalid_setup.html', { 'title': _('Database error'), }) return HttpResponseRedirect(request.path + '?' + … -
Django - Pandas Dataframe order
I have a pandas dataframe in Django, when i display them in webpage the order of columns displays in alphabetical order filterdata = pd.DataFrame(list(Books.objects.all().values('name', 'types', 'art'))) my dataframe should save like names|types|art in order but it display on html as art|names|types I want to know is dataframe position changes only in display on webpage or is it saved in aplhabetical in filterdata pandas? because later i want to pass the dataframe to a function argument in correct order -
Change schema for database of django-admin
I'm newbie in Django and python. Just want to ask how to change the schema for database of Django-admin in the Django framework? For now I already migrated the database of Django-admin to the new schema. -
Django Migrate command throwing ORA-00955 error
I have an oracle 12c existing db. I used inspectdb to create the django models. Most of the tables in the db dont have a primary key and I assume that if pk is not set explicitly Django would apply the id column as the primary key to the tables. Also, I have set managed-=True on all my models so, Django should ideally be able to create the id column for its use. When I run makemigrations, I dont get any error. But when I run migrate after that I get the following error:- return self.cursor.execute(query, self._param_generator(params)) django.db.utils.DatabaseError: ORA-00955: name is already used by an existing object Any clue why I am getting this error? -
After creating a new django application, while running the server it's showing the urls for previous project
I am using ATOM ide while I am running new project server it is opening the previous project urls. I have tried restarting the editor and system also but still not working. Can anyone please advise. -
Django-image-cropping is not working outside admin interface
I wish to use django-image-cropping outside the django admin interface. Inside it is working. Also I can get the example of django-image-cropping to work. But it is just not showing the right widgets. Why? Excerpt of my models.py: # ... class Person(TranslatableModel): # ... pic = ImageCropField(_("profile picture"), blank=True, null=True, upload_to=settings.USER_PICTURE_DIR, ) picture_cropped = ImageRatioField( 'pic', '{}x{}'.format(*settings.USER_PICTURE_SIZE) ) # ... Excerpt of my forms.py: # ... class PersonUpdateForm(ModelForm): # ... class Meta: model = Person fields = [ 'pic', 'picture_cropped', ] Excerpt of my views.py: # ... class PersonUpdateView(LoginRequiredMixin, OnlySelfMixin, UpdateView): model = Person template_name = 'persons/person_intern_form.html' form_class = PersonUpdateForm # ... Excerpt of my person_intern_form.html: {% extends 'intern/intern_base.html' %} {% load i18n sekizai_tags %} {% block main_content %} <form action="{{ action }}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"/> </form> {% endblock main_content %} {% addtoblock "css" %} {{ form.media.css }} {% endaddtoblock %} {% addtoblock "js" %} {{ form.media.js }} {% endaddtoblock %} Screenshot -
acess each row before rendering django tables2
I am using djangotables2 to simply render my table but I want to check some condition on each row of a column and print some addition to that value but I can not find anyway to do so Is it posible in djangotables2? view class BowlerList(LoginRequiredMixin, PagedFilteredTableView): model = Bowlers template_name = 'bowlers_list.html' table_class = BowlerTable filter_class = BowlerListFilter formhelper_class = BowlerListFormHelper def get_context_data(self, **kwargs): context = super(BowlerList, self).get_context_data(**kwargs) context['select_list'] = UserSelect.objects.filter(user=self.request.user) return context table class BowlerTable(dt2.Table): name = tables.LinkColumn('bowler-detail', args=[A('pk')]) class Meta: model = Bowlers fields = ('name', 'ahprank', 'pcarank') template_name = 'django_tables2/bootstrap-responsive.html' attrs = {'class': 'table table-striped table-bordered table-hover'} per_page = 10 template {% render_table table %} i need to compare Name column values with the value I will be getting in my "select_list" which I am getting through the views as context data -
Django Form ForeignKey save
Sry for stupid question, but I don't understand. I'm trying to use Django Forms, I have 2 models class Post(models.Model): unit = models.ForeignKey('Unit',on_delete=models.CASCADE, primary_key=False) and class Unit(models.Model): name = models.CharField(max_length=120, unique = True) I've created a form from django import forms from .models import Post, Unit, StatusOfPost class PostForm(forms.ModelForm): class Meta: model = Post fields = [ 'unit', ] than I've written a view.py def ideaNewForm(request): unit = Unit.objects.get(name=request.POST) user = request.user if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): idea = form.save(commit=False) idea.unit = unit idea = Post.objects.create( author = user, ) return redirect('postsList') else: form = PostForm() return render(request, 'post_new.html', {'form':form}) Unit matching query does not exist.- and i have that such issue. I have a dropdown list it is a Unit model. How save it right? Before I did it without Django Form unit = Unit.objects.get(name=request.POST['unit']) and it worked well, but I want use Django Forms -
pyorient + Django : How should I create a model properly so that serializers can access them?
settings.py from pyorient.ogm import declarative Node = declarative.declarative_node() Relationship = declarative.declarative_relationship() models/user.py from pyorient.ogm.property import * from my_proj.settings import Node class User(Node): email = String(unique=True) password = String() serializers/register_serializer.py from rest_framework import serializers, validators from users.models.user import User class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'password') I get the following exception AttributeError: type object 'User' has no attribute '_meta -
Django FileField not saving
There are existing posts here which deal with the same problem as mine however, none offer a proper solution for my problem. I am working on a project with multiple models say A,B,C,D and E. Three of those have FileFields in them. I have made changes to settings.py MEDIA_ROOT and MEDIA_URL to get FileField working. It works perfectly on 2 models and saves to the proper location and everything. For the third model, the same line models.FileField( upload_to='media/documents', null=True, blank=True) doesn't save the file to the location. The httpd error logs are blank. This third model is an inline model. Anyone has any ideas as to why this model would suddenly 'glitch'. Below are the httpd access logs 192.168.45.139 - - [06/Aug/2018:15:50:01 +0000] "POST /admin/midb/job/3027/change/ HTTP/1.1" 302 - 192.168.45.139 - - [06/Aug/2018:15:50:01 +0000] "GET /admin/midb/job/3027/change/ HTTP/1.1" 200 205520 192.168.45.139 - - [06/Aug/2018:15:50:03 +0000] "GET /nested_admin/server-data.js HTTP/1.1" 200 288 192.168.45.139 - - [06/Aug/2018:15:50:03 +0000] "GET /admin/jsi18n/ HTTP/1.1" 200 3185 -
set a variable in django template file, and update it after iteration
Trying to set variable in django template, and make a simple rule to update it after iteration. Here is my template: {% for adv in advs %} <div class="media-item big" style="top: 18%;left:{% cycle '304' '1078' %}px;"> <div class="media-item__tags"> <a href="#" class="tag">{{ adv.year }}</a> <a href="#" class="tag">{{ adv.payer}}</a> </div> <div class="media-item__content"> <div class="media-item__background"> <a href="project-spar.html" class="media-item-background__link"></a> <div class="media-item__canvas"> <div class="media-item__canvas-background" style="background-image: url({{adv.image.url}})"></div> </div> <h2 class="topic white upcase fixed-size">{{ adv.name }}</h2> <a href="#" class="link regular width600-only">Смотреть проект</a> </div> </div> </div> In first div i need to make different 'left:' value. I want to make rule: after every iteration, value changes from base=304 to base+774 px. I tryed to do it somehow with {% cycle %} but it doesnt work for me, also tryed to set variables with {% with %} tag, but didnt find any information about how to update them. -
Django - Least with condition
I have a model with five FKs, each one has a situation and a date. In a QuerySet, I need to annotate the object that has the least date value and the situation equal to one. I can get the least date value using Least: example = example.annotate(older=Least('object__fk1_name__date', 'object__fk2_name__date')) But how to add the 'situation equal to one' condition? -
Integration of Stripe in Django Oscar
i'm following following instructions for the integration of stripe in django oscar: https://github.com/sayonetech/django-oscar-stripe I don't get the last point: Include the urls mentioned in the dashboard into the projects root urls. What for urls are meant here? I only find my stripe.api_key but no url on the stripe dashboard. Thank you in advance, molm -
Class based view not returning httpresponse when reversing in an httpresponseredirect?
I've been trying to figure this out for some time now but don't see how the error message im getting really is the case. I'm getting this error message: The view plan.views.PortfolioReportEdit didn't return an HttpResponse object. It returned None instead. From looking at the code it does seem to return an httpresponse at any place it should from my point of view. Here is the code, first for the parent/superclass: class PortfolioEditBase(UpdateView): post_req = False url_name = 'plan:view_investment_profile' def form_valid(self, form): self.post_req = True print "BASE: form_valid passed" return super(PortfolioEditBase, self).form_valid(form) def get_context_data(self, **kwargs): context = super(PortfolioEditBase, self).get_context_data(**kwargs) try: context['post_req'] = self.post_req context['profile_id'] = self.kwargs['profile_id'] print "BASE: gathered context data" return context except KeyError: context['post_req'] = self.post_req print "BASE: gathered context data" return context def get_success_url(self): print "PortfolioEditBASE: in success_url" return reverse(self.url_name, args=self.kwargs['profile_id']) Here is the code for the subclass: class PortfolioDividendEdit(PortfolioEditBase): model = Dividend form_class = DividendForm template_name = 'plan/portfolio/edit/dividend_edit.html' print "PortfolioDividendEdit: Inside start of function" def form_valid(self, form): if "delete" in self.request.POST: div_obj = Dividend.objects.get(id=self.kwargs['dividend_id']) profile_id = div_obj.profile_id div_obj.delete() return HttpResponseRedirect(reverse('plan:view_investment_profile', kwargs={'profile_id': profile_id})) def get_context_data(self, **kwargs): print "Inside get_context_data dividend" context = super(PortfolioEditBase, self).get_context_data(**kwargs) dividend_obj = Dividend.objects.get(id=self.kwargs['dividend_id']) profile = Profile.objects.get(id=dividend_obj.profile_id) context['post_req'] = self.post_req context['profile'] = profile context['dividend_id'] … -
Select the latest activity time to manipulate the article
My article model has foreign-key of comment and footnote, I'd like to retrieve the latest activity's time to manipulate the article either add new comment or add new footnote. article = get_object_or_404(Article, pk=pk) #retrieve the article's updated time latest_article_date_updated = article.date_updated #retrieve the latest footnote's created time footnotes = article.footnote_set.all() latest_footnote_date_created = footnotes.last().date_created #retrieve the latest comment time latest_comment_date_updated = article.comment_set.order_by("-date_updated").first().date_updated Then select the max as the latest article_active_time = max(latest_article_date_updated, latest_footnote_date_created, latest_comment_date_updated) It report error Exception Value: 'NoneType' object has no attribute 'date_created' I tried to solve the problem by latest_footnote_date_created = footnotes.last().date_created or 0 latest_comment_date_updated = article.comment_set.first().date_updated or 0 article_active_time = max(latest_article_date_updated, latest_footnote_date_created, latest_comment_date_updated) It report TypeError TypeError: '>' not supported between instances of 'int' and 'datetime.datetime' How do I select the latest activity time to manipulate the article? -
How to set "return_value" once for TestCase. Python. Django
Here is example test: import a import b import c import mock from django.test import TestCase @mock.patch.object(a, "method_a") @mock.patch.object(b, "method_b") @mock.patch.object(c, "method_c") class SomeTestCase(TestCase): def setUp(self): # I want to set mock_method_a.return_value = 1 once here (or not here, but once) pass def test_one(self, mock_method_a, mock_method_b, mock_method_c): mock_method_a.return_value = 1 mock_method_b.return_value = 2 pass # some test stuff def test_two(self, mock_method_a, mock_method_b, mock_method_c): mock_method_a.return_value = 1 mock_method_b.return_value = 2 pass # some test stuff def test_three(self, mock_method_a, mock_method_b, mock_method_c): mock_method_a.return_value = 1 mock_method_b.return_value = 2 pass # some test stuff Queston: How I can avoid of duplicate code for setting "return_value" in each test in TestCase? I expect something in "setUp" method or something similar. Is it possible? PS: mock version mock==1.3.0, django version Django==1.8.4 -
Running external python script from shell vs Django view
I'm trying to run a Python script that I run using Django shell: from os import chdir from subprocess import run chdir('/home/pi') run('python3 script.py', shell=True) It works like a charm, but when I try to run it from a view like this: # django imports omitted from os import chdir from subprocess import run def index(request): if request.POST.get('clicked'): chdir('/home/pi') run('python3 script.py', shell=True) ... ... the same code won't run when executed this way. I changed permissions to port so that I can do whatever heck I want for the time being. Error log isn't very helpful. It only detects missing favicon.ico which isn't really important at this point. Are there any "gotchas" when it comes to running scripts from Django shell vs Django views ? -
Hide Toekn table from admin panel in Django REST Framework
I'm using Django REST Framework and Django-OAuth-toolkit to enable OAuth2 authentication in my application. Since after using OAuth2, I no more need token-based authentication and hence no token table/model. Sometimes it makes me confused after seeing two different modules for handling token. Therefore, I want to remove/hide Token table from the admin panel of Django. Here is my settings.py file REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication' ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10 } I have removed Token based authentication but still Token table is there in the admin panel -
Custom form with custom User model - Django
I am trying to build a custom User Model like this: class UserTest(models.Model): #username=models.EmailField() username=models.OneToOneField(User, on_delete=models.CASCADE) email=models.EmailField(User) # password=models.CharField(max_length=40) first_name=models.CharField(max_length=20) last_name=models.CharField(max_length=20) birthday=models.DateField(auto_now=False, null=True, blank=True) # USERNAME_FIELD='username' def __str__(self): return self.username.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile=UserTest.objects.create(username=kwargs['instance']) post_save.connect(create_profile,sender=User) To register a new user i created this form: class UserRegisterForm(forms.ModelForm): #neuen "normalen" Nutzer registrieren username=forms.EmailField(label='Email address') email=forms.EmailField(label='Confirm Email') password=forms.CharField(widget=forms.PasswordInput) password2=forms.CharField(widget=forms.PasswordInput) first_name=forms.CharField(label='First Name') last_name=forms.CharField(label='Last Name') birthday=forms.DateField(label='Birthday') class Meta: model=User fields=[ 'username', # 'username2', 'email', 'password', 'password2', 'first_name', 'last_name', 'birthday', ] def clean(self,*args,**kwargs): username=self.cleaned_data.get("username") email=self.cleaned_data.get("email") password=self.cleaned_data.get("password") password2=self.cleaned_data.get("password2") username=self.cleaned_data.get("username") birthday=self.cleaned_data.get("birthday") if username!=email: raise forms.ValidationError("Emails must match") email_qs=User.objects.filter(username=username) if email_qs.exists(): raise forms.ValidationError("This Email has already been registered") if password!=password2: raise forms.ValidationError("Passwords must match") return super(UserRegisterForm,self).clean(*args,**kwargs) This is working fine but the DateField is displayed as an Text Field. I used a custom DateInput like this before: class DateInput(forms.DateInput): input_type = 'date' Which is called like this: class UserRegisterForm(forms.ModelForm): username=forms.EmailField(label='Email address') email=forms.EmailField(label='Confirm Email') password=forms.CharField(widget=forms.PasswordInput) password2=forms.CharField(widget=forms.PasswordInput) first_name=forms.CharField(label='First Name') last_name=forms.CharField(label='Last Name') class Meta: model=User fields=[ 'username', 'email', 'password', 'password2', 'first_name', 'last_name', 'birthday', ] widgets = { 'birthday': DateInput() } Now i get an error in models.py: Unknown field(s) (birthday) specified for User This is weird to me because the filed is known as long as i stick to the … -
Django db_for_read router method not returning hints
I would like to be able to switch databases depending on the current user logged in. The field that needs to be checked is username. So in order to do this I have to somehow retrieve it in my router class that I define in the following way (so far it doesn't differ much from that in the official django docs): class DatabaseRouter: def get_customer_db(self, model, **hints): pass def db_for_read(self, model, **hints): if model._meta.app_label == 'user': return 'clients' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'user': return 'clients' return None In case with the db_for_write method I'm getting a User model instance that I could use to retrieve their username, email etc but I'm not getting any hints when the db_for_read is executed. Why does it happen and is there any way to pass a model instance to the router? -
how to request array of objects using request.POST[] in django
for c in request.POST['colors']: col=Colors() col.color=c['name'] col.main_id_id=article.id col.save() if request.POST['is_dimension']: for wbd in (request.POST['dimension'] dim=Dimensions() dim.width=wbd['width'] dim.breadth=wbd['breadth'] dim.depth=wbd['depth'] dim.main_id_id=article.id dim.save() In above code, if i use request.POST.getlist('colors') instead of this request.POST['colors'] i will get empty array , -
How to update apache configuration to avoid thread timeouts in Python / Django?
I am very new to threading / apache configuration so looking for some help. I have a view in Django that takes a request, does some parsing, and then starts a new python thread before returning a 202 response: my_thread = threading.Thread( target=my_function, args=function_args ) my_thread.start() return response.Response(data={'status': 'thread started'}, status=202) The problem is that I have a thread that's taking ~ 4 minutes to run locally, but it seems to be timing out in my production Apache environment. Is there a parameter I can set in my Apache configuration or wsgi.py to extend the time a thread is allowed to execute before timing out ? These are the relevant parameters I have set currently: <IfModule mpm_event_module> StartServers 5 ServerLimit 565 MinSpareThreads 25 MaxSpareThreads 75 ThreadLimit 64 ThreadsPerChild 25 MaxRequestWorkers 1000 MaxConnectionsPerChild 100 </IfModule> -
POST on ModelViewSet with nested object Django Rest Framework
I'm building an API with the django rest framework. I have these models: class Organisme(models.Model): nom = models.CharField(max_length=255) adresse = models.ForeignKey(Adresse, on_delete=models.CASCADE) class Adresse(models.Model): rue = models.CharField(max_length=255, blank=True) This is the view for my mode Organisme : class OrganismeViewSet(viewsets.ModelViewSet): queryset = Organisme.objects.all() serializer_class = OrganismeSerializer pagination_class = StandardResultsSetPagination filter_backends = (filters.SearchFilter, DjangoFilterBackend) filter_class = OrganismeFilter search_fields = ('nom') And my serializer: class OrganismeSerializer(serializers.ModelSerializer): class Meta: model = Organisme fields = '__all__' depth = 1 So I'm trying to create a new Organisme by sending this: { "adresse": { "rue": "test" }, "nom":"TestTest", } or { "adresse": pk_id, "nom":"TestTest", } But I always end up with this error: IntegrityError at /organismes/ (1048, "Column 'adresse_id' cannot be null") If you guys know how to proceed... Thank you in advance. -
Sort queryset by added field
I'm trying to add an extra field to the instances of my queryset and then sort the set by the new field. But I get a field error( Cannot resolve keyword 'foo' into field. Choices are: ... ) My view(abstract): def view(request): instances = Model.objects.all() for counter, instance in enumerate(instances): instance.foo = 'bar' + str(counter) instances.order_by('foo') #this line causes trouble return render(request, 'template.html', {'instances': instance}) My template: {% for instance in instances %} {{instance.foo}} {% endfor %} If I leave out the order_by line the templates renders as expected, so the field seems to be there. So why do I get a field error? It would be awesome, if somebody could help me to understand what I'm doing wrong. Thanks in advance. I found a possible solution to change the template to {% for instance in instances|dictsort:'foo' %} and that works fine, but from what I understand there should be as little logic as possible in the view, so I figure sorting should be done in the view. Or is this actually the right way? -
Execute code in dispatch method with LoginRequiredMixin
class HomeView(LoginRequiredMixin, TemplateView): template_name = 'home.html' def dispatch(self, request, *args, **kwargs): # Do some other checks after user is logged in # This does not work because the LoginRequiredMixin # will be executed after calling the super method return dispatch(self, request, *args, **kwargs) How can I execute code in the dispatch method after the user is logged in using a Class Based View with the LoginRequiredMixin?