Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - different inlines for different users
i have these models class Office(models.Model): name = models.CharField(max_length=255) class User(models.Model): name = models.CharField(max_length=255) status = models.SmallIntegerField() office = models.ForeignKey(Office, on_delete=models.SET_NULL, null=True) class Inspection(models.Model): place = models.CharField(max_length=255, null=True, blank=True) class Jobs(models.Model): inspection = models.ForeignKey(Inspection, on_delete=models.CASCADE) inspector = models.ForeignKey(User, on_delete=models.SET_NULL) cost = models.DecimalField(max_digits=20, decimal_places=2) i have different users: common users(status=1) and admins(status=2) common users can make and see Jobs only with inspectors from the same office admins can put any user into inspectors and see all jobs i can filter job list for users in the same office class JobAdmin(admin.StackedInline): model = Job extra = 0 def get_queryset(self, request): qs = super(JobAdmin, self).get_queryset(request) if request.user.status in [1]: qs = qs.filter(inspector__office=request.user.office) return qs class InspectionAdmin(ModelAdmin): list_display = ['place'] inlines = [JobAdmin] But how can i add additional filters for editing? If it was not inline form i would do it this way: class JobAdminForm(ModelForm): def __init__(self, *args, **kwargs): super(JobAdminForm, self).__init__(*args, **kwargs) if self.user.status == 1: #common user self.fields['inspector'].queryset = Inspector.objects.filter(office=self.user.office) class Meta: model = Jobs fields = '__all__' class JobAdmin(ModelAdmin): form = JobAdminForm def get_form(self, request, obj=None, **kwargs): form = super(JobAdmin, self).get_form(request, **kwargs) form.user = request.user return form -
How to convert time.strptime into an integer for datatime.date() Python 2
How would I convert the result from strptime into an integer value or a value that can be used by date.date()? convertTOdate = time.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S') duedate = datetime.datetime(convertTOdate) I am using Python 2 Thank you -
To expect only one return based on conditions from queryset filter
Based on my Queryset with filter I expect only one value to be returned Currently we use max aggregation to make sure only one value is returned lease_dict = LeaseTenant.objects.filter(tenat_id=self.id, is_active = True).aggregate(Max('id')) Never had issue with it , but it is not best way since if suddenly there is will be some error in the system and more then value will exist the Max will hide the issue. What is the better alternative ? -
Django - How to restrict which user can connect to the socket?
I am using django channels for an application channels, and i want to restrict access to the socket (authorized users only). Have this: @channel_session_user_from_http def connect_blog(message, username): user = message.user try: user_blog = User.objects.get(username=username) has_perm = user_blog.check_perm(user.pk) if not has_perm: return except ObjectDoesNotExist: message.reply_channel.send({ # WebSockets send either a text or binary payload each frame. # We do JSON over the text portion. "text": json.dumps({"error": "bad_slug"}), "close": True, }) return Group(user_blog.group_name).add(message.reply_channel) But when I check the permissions has already been connected to the socket, how can I control this? (How to close the socket or control this case). Thanks and regards. -
Jquery Modal Confirmation on Django form submit for deletion of object
I am using Django with Crispy forms and am also using the Shopify Embedded Apps SDK. I am trying to have a modal window appear to let the user confirm that they want to delete an object. My code is attached so far. I have the modal window appearing with the following code, however, the form is not submitted (and the object is not deleted) after the user selects 'delete' on the modal window: It just closed the modal and nothing happens. I have tried various methods from around the net, but haven't had any luck. form.py class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'edit_form' self.helper.layout = Layout( [... some input fields...] ) # Add delete button self.helper.layout.append(Button('delete', 'delete')) # Normal submit button self.helper.layout.append(Submit('save', 'save')) views.py @login_required def edit_object(request, *args, **kwargs): # Form handling logic with request.user.session: object = get_object_or_404(models.Object, pk=kwargs['object_id'], ...) if request.method == "POST": form = forms.MyForm(request.POST, request=request, instance=object) if not form.is_valid(): [... do some stuff ...] if form.is_valid(): # If the save button is pressed if request.POST.get('save'): [... do some stuff to save and redirect to url of my choice ...] # If the delete button is pressed <<<< The … -
DJANGO - Login while someone else is logged in
My question is if I am logged in to my website in django and have an active session, will another login by a different user from the same browser(device) trigger the logout function automatically clearing all the previous session, or it will stay active too? I'm asking it because I don't necessarily want to call a logout function before every login if it is already in the login function's code. -
Reverse url in reusable app that is consumed as a nested app
A similar question was answered here. My situation is slightly different though. I have created a reusable app called "categories". In my project I have an app called "dashboard". The dashboard app includes the reusable "categories" app. This causes the following to be used to reverse a url reverse('dashboard:categories:browse') However, my reusable app has no knowledge of the "dashboard" namespace. I want to be able to use the solution I linked above to only the following within the reusable categories app. reverse('categories:browse') Currently, setting app_name in categories.urls does not work. I get NoReverseMatch when reversing "categories:browse". Here are excerpts of how the apps are included in the urls.py files. # myproject/urls.py url( r'^dashboard/', include( 'dashboard.urls', namespace='dashboard', ) ), # dashboard/urls.py url( r'^categories/', include( 'categories.urls', namespace="categories", ), ), -
Use JSON data throughout my code
I'm new to Django and would appreciate any kind of help. I request my JSON with this following function inside my app's services.py def get_games(): url = "https://igdbcom-internet-game-database-v1.p.mashape.com/games/" headers = {"X-Mashape-Key": "12131221"} # Pop the Offset with ajax When user reaches the end of the page params = {"filter[release_dates.date][gte]": datetime.date.today(), "fields": '*', "limit": 50, "order": "release_dates.date:desc", "offset": 0} r = requests.get(url, headers=headers, params=params) games = r.json() # Returns JSON Array return games The JSON gets back to me just fine, but how can I use the JSON array I get from the function above throughout my code? My Homepage's view calls the get_games() function and then it sends the JSON data to a template called game_list.html. From there, I parse my JSON and I get to display the information from the web api on my website. class HomePage(TemplateView): def get(self, request): games = services.get_games() # Sends the json string to the template return render(request, 'releases/game_list.html', {"games": games}) Now the problem arises when I make any other kind of view, I can't get to work with the JSON I got from above. "Normally, we grab data from the database in the models.py file, but I am unsure if I should be … -
How to update a ContentFile's content (by overwriting the file)
I'm trying to keep the same filename of a FileField in my UpdateView when I update the file content. It's a css file that CreateView generates by rendering a template with the form data as the context. Here's an extract of that logic: instance = form.save(commit=False) t = TemplateResponse(self.request, 'base.css', {"cssform": form}) t.render() css_string = t.content file_content = ContentFile(css_string) instance.css_file.save(file_name, file_content) I'm not having the same success with the UpdateView: def form_valid(self, form): instance = self.object filename = instance.css_file t = TemplateResponse(self.request, 'base.css', {"cssform": form}) t.render() css_string = t.content filedata = ContentFile(css_string) instance.css_file.save(filename, filedata) super(CSSUpdate, self).save(form) The error is: join() argument must be str or bytes, not 'FieldFile' The error is provoked on this line: instance.css_file.save(filename, filedata) The traceback is short: Traceback: File "/usr/lib/python3.5/posixpath.py" in join 82. if b.startswith(sep): How do I overwrite that old file with my new content? I'm using django 1.10, python 3.5 -
Serialize a Django model with a ForeignKey
In Django Rest Framework, I have a simple Present model which consists in the following fields: class Present(models.Model): name = models.CharField(max_length=15) price = models.FloatField() link = models.CharField(max_length=15) isAlreadyBought = models.BooleanField() user = models.ForeignKey(User, on_delete=models.CASCADE) The serializers for the User and Present models are these ones: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'email') class PresentSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) class Meta: model = Present fields = ('name', 'link', 'price', 'isAlreadyBought', 'user') My goal is, from the following POST request to save a new Present. To do so, I've added a user_id field to my request to link my Present with a given User: import requests save_present = {'name': 'figurine', 'price': '50.8', 'link': 'fake_link', 'isAlreadyBought': 'True', 'user_id': '22'} r = requests.post('http://127.0.0.1:8000/present_list', json=save_present) Here is how I am trying, without success so far, to save my Present: class PresentList(APIView): # add a new present def post(self, request, format=None): user = User.objects.get(id=request.data['user_id']) machin = request.data machin.pop('user_id', None) machin['user'] = UserSerializer(user).data serializer = PresentSerializer(data=machin) if serializer.is_valid(): print('SERIALIZER OK') serializer.save() else: print(serializer.errors()) return Response('') I do not manage to find out the best Django-based way to achieve this. -
serializers.SlugRelatedField, how to pass the User.object.get a value for look up from the view
I would like to get only the items related to the loggin/request.user.id user from a to-do-list model. How am I able to get this value for queryset=User.objects.get() as found in the clas below class ToDoSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField( queryset=User.objects.get(), slug_field='username' ) class Meta: model = ToDoList fields = ('user','name', 'discription', 'dueDate','timezoneChoice','dueMinutes') Im my view.py I have @login_required def todo(request): tmpl_vars = {'form': ToDoSerializer()} return render(request, 'todo/index.html', tmpl_vars) Thank you -
How to upload a file from Angular 2 to Django Server? (enctype="multipart/form-data")
I have seen multiple questions on stackoverflow similar to this but I have not been able to solve the following issue. I can successfully upload a file using this html form: <form method="POST" action="//127.0.0.1:8000/upload" enctype="multipart/form-data"> <input type="file" name="myfile" required> <button type="submit">Upload</button> </form> and here is how the file is handled on the server side: views.py def upload_file(request): f = request.FILES['myfile'] with open('media/name.jpg', 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) return HttpResponse('Done') Everything works perfectly up to this point. The file gets uploaded and saved as name.jpg on disk. Now, I would like to replace the html above to post the file without a url redirect (using angular 2 http). Following this answer, here is my current implementation: file-upload.component.ts import { Component, ElementRef } from '@angular/core'; import {Http, Headers, RequestOptions, Response} from '@angular/http'; @Component({ selector: 'file-upload', template: '<input type="file" name="myfile">' }) export class FileUploadComponent { constructor(private http: Http, private el: ElementRef) {} upload() { var headers = new Headers(); headers.append('Content-Type','multipart/form-data'); let inputEl = this.el.nativeElement.firstElementChild; if (inputEl.files.length > 0) { let file:FileList = inputEl.files[0]; this.http .post('http://127.0.0.1:8000/upload', file, {headers: headers}) .subscribe(); } } and call it like this: <file-upload #myfile (change)="myfile.upload()"></file-upload> I get a 400 bad request error saying (Unable to parse … -
django-toolbox: No module named from django.utils.importlib import import_module
I've the latest version of Django, django-toolbox and Python. I'm using MongoDB as DB and PyMongo. My problem is this: "No module named from django.utils.importlib import import_module" This happens because I want to use Embedded Models and specifically, Lists of Subobjects (One-to-Many Relations) as you can see in the tutorial. Is there a way to solve this problem or to model the Lists of Subobjects in an another way? Thanks. -
Modify Multiple insert by admin in Django with select list
https://docs.djangoproject.com/en/1.10/intro/tutorial07/ from django.contrib import admin from .models import Choice, Question class ChoiceInline(admin.StackedInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] admin.site.register(Question, QuestionAdmin) In the above example how to add select list instead od text box for question_text, in which there is already data in the Question model. -
Django 1.10 doesn't show statiс image
I have a model which contains user_image field. This field has default image value: user_image = models.ImageField(verbose_name='Аватар',blank=True, default=settings.STATIC_URL+'avatar.jpeg') after update to django 1.10 this default image doesn't show in templates because link contain wrong path. For example in my case link should be '127.0.0.0:8000/static/avatar.jpeg' instead I have link like this '127.0.0.0:8000/media/static/avatar.jpeg' -
The best way to use sorl-thumbnail with jpegtran, jpegoptim, OptiPNG, etc
I use sorl-thumbnail in my django project. I tried to check my website in Google PageSpeed Insights, which said that I can decrease images size by jpegtran, OptiPNG, etc. Does somebody know the good way to integrate this in sorl-thumbnail? -
Django: add a DEFAULT class into input/select fields
What I need to is just add a default class I'll call "myclass" to all input/select fields appearing into add/edit forms. I want to transform this <div class="field-label"> <div> <label for="id_label" class="required">Label:</label> <input type="text" name="label" id="id_label" class="vTextField"> </div> </div> Into this <div class="field-label"> <div> <label for="id_label" class="required">Label:</label> <input class="myclass" type="text" name="label" id="id_label" class="vTextField"> </div> </div> I know that this output is done into fieldset.html template (admin/includes/fieldset.html) but I have no clue where field.field parameter is set and how, since is clearly already formatted: [... ] {% if field.is_checkbox %} {{ field.field }}{{ field.label_tag }} {% else %} {{ field.label_tag }} {% if field.is_readonly %} <p>{{ field.contents }}</p> {% else %} {{ field.field}} {% endif %} {% endif %} [...] Where can I edit that? Thanx in advance -
Can't return JSON object from python using django-ajax
Trying to apply this ajax plugin for django https://github.com/yceruto/django-ajax I'v used ajaxPost successfully, but can't apply ajaxGet In views.py. In python all data is printed fine. @ajax def notify(request): notifications = Notification.objects.filter(whom=request.user.profile) for acd in notifications: print(acd) print(acd.choice_afl) print(acd.whom) print(acd.who_did) return {'notifications': notifications} In html: $('.notifications_button').click(function(){ ajaxGet('/notify/', function(notifications){ for(var acd in notifications){ alert(acd.choice_afl) $('#the_very_nw').html(acd.choice_afl); } }) If I alert noty I get "notifications", if I alert acd.choice_afl I get undefined (or just nothing if insert into html), despite in python I get the sting result I need . What is wrong? Doesn't python object transforms into JSON object? -
Error Generic detail view must be called with either an object pk or a slug, even with the pk
i'm trying to update records of a view which has a foreign key field, due to this i'm getting an error, since i tried to update another model without a foreign key field and it worked very well. There are other quetions like this, but in my case i'm passing the pk. urls.py urlpatterns = [ url(r'^info/(?P<studentpk>\d+)/update/$', views.updatestudent.as_view(), name="updatestudent"), ] views.py class updatestudent(UpdateView): model = Student form_class = forms.studentform template_name = "temp/updatestudent.html" def get_success_url(self): return reverse("courses") updatestudent.html <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Update" /> </form> models.py class Student(models.Model): classfk = models.ForeignKey(Class) name = models.CharField(max_length=100) birth_date = models.DateField('Birthdate') def __str__(self): return self.name error AttributeError: Generic detail view updatestudent must be called with either an object pk or a slug. -
Django QueryDict OPTIONAL request method
I am using django 1.10.2 with python 3.5.2 in a Linux machine. my Django app receive a request from client. The request method is identified as type OPTIONAL. I understand that Django automatically create a QueryDict for POST and GET request. So, how do I get the content of request that is not GET and POST Type? How can I create the QueryDict of such request or any other type of requests? For debugging purposes, Is it possible to print the entire http request? body and headers? I would like to see the content of the request. Thanks in advance. -
Django admin make changes to selected user?
So I have created a inline class in my admin.py and some actions to update a selected user. The problem I am facing is that when I select a user and perform said action it only ever updates the admin user....which I am guessing is because I am using request. I am trying to get the action to update the selected user(s) and not the admin user initiating the action, but I have been struggling with it for a couple days now off and on trying to figure this out. When using queryset I get error messages saying 'Queryset' object has no attribute 'profile' but I am not sure what else to use here. So mu question is, is what I am trying to do possible and if so any guidance on how to get this working would be greatly appreciated. Please see my code below. admin.py admin.site.unregister(User) class ProfileAdminInLine(admin.StackedInline): model = Profile class ProfileAdmin(UserAdmin): list_display = ['username', 'email', 'first_name', 'last_name', 'rewards_punch_card', 'rewards_tier'] list_select_related = True inlines = [ProfileAdminInLine] actions = ['pc_add_1'] def rewards_tier(self, user): return user.profile.rewards_tier def rewards_punch_card(self, user): return user.profile.rewards_current def pc_add_1(self, request, queryset): punch_card = request.user.profile.rewards_current tier = request.user.profile.rewards_tier credits = request.user.profile.rewards_credits user_profile = request.user.profile punch_cards_updated = … -
DEBUG = False got error
I am using django 1.9.10 to develop the web site on my laptop, I am trying to set settings.py DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1' ] then, I got the Server Error (500) and if settings.py DEBUG = False ALLOWED_HOSTS = ['localhost'] I got the error Bad Request (400) I do not know why? doest it about the static or media settings problem? -
Page not found 404 with Django
I don't understand where is situated my problem. I get an urls' problem but I don't see where I made a mistake. I have a project : Etat_civil I have an app : BirthCertificate My views.py app is : from django.shortcuts import render from django.http import HttpResponse from django.template import loader from BirthCertificate.forms import BirthCertificateForm # Create your views here. def BirthCertificateAccueil(request) : # Fonction permettant de créer la page d'accueil de la rubrique Acte de Naissance #Cherche le fichier html accueil et le renvois template = loader.get_template('accueil.html') return HttpResponse(template.render(request)) def BirthCertificateCreationAccueil(request) : # Fonction permettant de créer la page de création du formulaire de la partie : Acte de Naissance template = loader.get_template('creation_accueil.html') return HttpResponse(template.render(request)) def BirthCertificateForm(request) : if request.method == 'POST' : form = BirthCertificateForm(request.POST) if form.is_valid(): numero_acte = form.cleaned_data["Numero de l'acte"] nom = form.cleaned_data['Nom'] prenom = form.cleaned_data['Prenom'] else : form = BirthCertificateForm() template = loader.get_template('birthform.html') return render(request, template.render(request),locals()) I have also a urls.py app : from django.conf.urls import url from . import views urlpatterns = [ url(r'^accueil$', views.BirthCertificateAccueil), url(r'^creation$', views.BirthCertificateCreationAccueil), url(r'^formulaire$', views.BirthCertificateForm), ] And my urls.py project looks like : from django.conf.urls import url, include from django.contrib import admin from BirthCertificate import views urlpatterns = [ url(r'^admin/', … -
How to query Non Unique Together values in Django or SQL?
Let's say I have this model: class Contact(BaseModel): order = models.ForeignKey(Order, related_name='contacts', blank=True, null=True) type = models.CharField(max_length=15, choices=TYPES, blank=True)) I want to find all orders where order and type are not unique together. For example, there is order A and there are related contacts: Contact(order=orderA, type='broker') Contact(order=orderA, type='broker') Contact(order=orderA, type='delivery') I want to find this orderA because this order and type='broker' are not unique together in Contact model. And then there is orderB and these related contacts: Contact(order=orderB, type='broker') Contact(order=orderB, type='delivery') I don't want this orderB because it and the field type are unique in Contact model. I tried using annonate() of Django but failed to relate these two fields. Is it possible to do this with Django queries? If not, a slight hint of how I could do it in SQL would be greatly appreciated. Thank you very much. -
no such table: auth_user error while logging to /admin/ after deploy django app on pythonanywhere
I have an issue after deploy on pythonanywhere.com test hosting and setting up an MySQL Database. When Im trying to login to admin with my superuser I get this error: Environment: Request Method: POST Request URL: http://studs.pythonanywhere.com/admin/login/?next=/admin/ Django Version: 1.9.7 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_docs', 'mainapp'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/studs/.virtualenvs/Studsvenv/lib/python3.5/site-packages/django/db/backends/utils.py" in execute 64. return self.cursor.execute(sql, params) File "/home/studs/.virtualenvs/Studsvenv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py" in execute 323. return Database.Cursor.execute(self, query, params) The above exception (no such table: auth_user) was the direct cause of the following exception: File "/home/studs/.virtualenvs/Studsvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/home/studs/.virtualenvs/Studsvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/studs/.virtualenvs/Studsvenv/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/home/studs/.virtualenvs/Studsvenv/lib/python3.5/site-packages/django/contrib/admin/sites.py" in login 414. return login(request, **defaults) File "/home/studs/.virtualenvs/Studsvenv/lib/python3.5/site-packages/django/contrib/auth/views.py" in inner 49. return func(*args, **kwargs) File "/home/studs/.virtualenvs/Studsvenv/lib/python3.5/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/home/studs/.virtualenvs/Studsvenv/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/home/studs/.virtualenvs/Studsvenv/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/home/studs/.virtualenvs/Studsvenv/lib/python3.5/site-packages/django/contrib/auth/views.py" in login 69. if form.is_valid(): File "/home/studs/.virtualenvs/Studsvenv/lib/python3.5/site-packages/django/forms/forms.py" in is_valid 161. return self.is_bound and not self.errors File "/home/studs/.virtualenvs/Studsvenv/lib/python3.5/site-packages/django/forms/forms.py" in errors 153. self.full_clean() File "/home/studs/.virtualenvs/Studsvenv/lib/python3.5/site-packages/django/forms/forms.py" in full_clean 363. self._clean_form() …