Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST: Auth user is not passed to the serialiser error - Field is required
I'm not sure what I'm doing wrong, but the authenticated user is not registered in the serialiser. Models.py class Post(models.Model): posted_by = models.ForeignKey('auth.User', on_delete=models.CASCADE) def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) Serializers.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' def create(self, validated_data): post = Post.objects.create(**validated_data) # extra code to add images views.py class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer permission_classes = ( permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, ) def perform_create(self, serializer): serializer.save(posted_by=self.request.user) I don't understand why serializer.save(posted_by=self.request.user) doesn't work as intended. It should pass the required information about the field. When I do a POST request, I get the error that { "posted_by": [ "This field is required." ] } I think it's something to do with the create method in the serialiser. For some reason, posted_by is not present in validated_data (or something similar). I would like to know what exactly is happening behind the scenes. -
AttributeError at /projectslist / 'QuerySet' object has no attribute 'objects'
I am newbie in Django. I am tying and struggling to create a search form in Django but I got thus error: AttributeError at /projectslist/ 'QuerySet' object has no attribute 'objects' Request Method: GET Request URL: http://127.0.0.1:8000/projectslist/?projectmanager=1&category=2&state=2&date_created=2018-03-06&date_last_updated=2018-03-06 Forms.py class ProjectForm(forms.ModelForm): class Meta: model = Project exclude = ['state', 'projectmanager', 'date_created', 'date_last_updated'] class FilterForm(forms.Form): projectmanager = forms.ModelMultipleChoiceField(queryset=User.objects.all(), required=False) category = forms.ModelMultipleChoiceField(queryset=ProjectCategory.objects.all(), required=False) state = forms.ModelMultipleChoiceField(queryset=ProjectState.objects.all(), required=False) date_created = forms.DateField(required=False) date_last_updated = forms.DateField(required=False) Views.py class ProjectListView(ListView): model = Project template_name = 'projects.html' context_object_name = 'projectss' ordering = ['date_created'] def get_queryset(self): queryset = super(ProjectListView, self).get_queryset() return queryset def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() filterForm = FilterForm(self.request.GET) if filterForm.is_valid(): projectmanager = filterForm.cleaned_data['projectmanager'] category = filterForm.cleaned_data['category'] state = filterForm.cleaned_data['state'] date_created = filterForm.cleaned_data['date_created'] date_last_updated = filterForm.cleaned_data['date_last_updated'] if category: self.object_list = Project.objects.filter(category=category).filter(state=state) else: raise ValueError('error') context = self.get_context_data() context['filterForm'] = filterForm return self.render_to_response(context) template <form action="/projectslist/" method="GET"> <select name="projectmanager"> {% for option in filterForm.projectmanager %} <option>{{ option }}</option> {% endfor %} </select> <select name="category"> {% for option in filterForm.category %} <option>{{ option }}</option> {% endfor %} </select> <select name="state"> {% for option in filterForm.state %} <option>{{ option }}</option> {% endfor %} </select> <input name="date_created" placeholder="Date "> <input name="date_last_updated" placeholder="Last Date"/> <button type="submit"> Search</button> </form> <br/> … -
How to Export SPSS Files on Web using Python-Django
Using Python/Django, I know how to write a SPSS file on a local computer. with spss.SavWriter(f_name, var_names, var_types) as writer: for record in records: writer.writerow(record) However, I was wondering how I can accomplish that using the StreamingHttpResponse on Django? For example, it is simple to export a csv file on web. Here it is: def export_df_as_csv(df,file_name,write_index, index_name="Index"): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="' + file_name + '.csv"' writer = csv.writer(response) if write_index: writer.writerow([index_name] + list(df.columns)) else: writer.writerow(list(df.columns)) for row in df.itertuples(index=write_index,name=file_name): df_row = list() for i in range(len(row)): df_row.append(row[i]) writer.writerow(df_row) return response Similarly, I want to export a .sav file on a web-based application (I am using Django). Can anyone help with writing/exporting SPSS files on Python/Django? -
Specifying widget from martor (1.2.5) for Django (ver 1.11.10)
I tried to apply a markdown plugin martor to my blog project which gives a nice toolbar in Django Admin. Then I followed its instruction to apply the changes to my models.py and expected to see the same toolbar in my frontend blog post editor. However it doesn't work (it looks like this: . I also tried the suggestions in the post, still doesn't work. Here is my code (model.py): ## models.py from django.db import models from django.utils import timezone from martor.models import MartorField class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) #text = models.TextField() text = MartorField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) And forms.py ## forms.py from django.forms import ModelForm from martor.fields import MartorFormField from martor.widgets import AdminMartorWidget from .models import Post, Comment class PostForm(ModelForm): class Meta: model = Post fields = ('title', 'text',) How can I add the markdown toolbar as in Django Admin (the figure1) into my blog editing page? Thanks in advance! -
Django : Ajax form still reloads the whole page
I am using a django form with ajax using this code: <form id="form-id"> <p> Search : <input name="{{ form.query.html_name }}" value="{{ form.query.value }}" type="search" id="form-input-id" autofocus onfocus="var temp_value=this.value; this.value=''; this.value=temp_value"> </p> </form> and the Javascript code: $('#form-id').on('submit', function(evt) { evt.preventDefault(); var form = evt.target; $.ajax({ url: form.action, data: $(form).serialize(), success: function(data) { $('.results').html(data); } }); But here is the thing, everytime the submit event is triggered, I feel like the whole page is reloaded (it blinks). What could I do to prevent this from happening? -
How to try run django server
I am trying to write test that will test if django app is runnable. I just want to try run django server and if everything is ok return code 0 otherwise another code. python manage.py runserver This command run infinite loop and I need to stop it by CTRL + C. And that is the problem. I would like to run it just for few second. Note: I am runnig django on linux. -
Override get_queryset based on django-guardian permissions
I am trying to override get_queryset based on the object permissions, which the users have from django guardian, so that only the objects are visible, which the users have permissions for. def get_queryset(self, request): if request.user.is_superuser: qs = super(MyAdminInline, self).get_queryset(request) return qs for item in MyModel.objects.all(): for perm in get_perms(request.user, thesis): things_user_can_see = get_objects_for_user(request.user, perm) return things_user_can_see Sadly, this literally does nothing and all of the items, regardless of the permissions that the users have, are visible. -
Django ImageField not uploading the image
I'm developing a simple game webstore. The idea is that developers can upload games that will be displayed on an iframe (so the games are simply just URLs) and then they can be played. The problem is, when publishing a game, the icon image does not get uploaded. So the image cannot be displayed. The Game model: class Game(models.Model): name = models.CharField(max_length=255) url = models.CharField(max_length=255) price = models.DecimalField(max_digits=9, decimal_places=2) developer = models.CharField(max_length=255, blank=True, null=True) icon = models.ImageField(upload_to="images/", default="images/default_game_img.png") description = models.CharField(max_length=255) published = models.DateField(auto_now=False, auto_now_add=True) I use a Django ModelForm: class PublishForm(forms.ModelForm): class Meta: model = Game fields = ['name', 'description', 'url', 'price', 'icon'] widgets = { 'description': Textarea(attrs={ 'cols': 80, 'rows': 4, 'class': 'form-control' }), } The form is generated simply like this: <form class="form-horizonal" name="uploadform" enctype="multipart/form-data" method="post"> {% csrf_token %} {{ form }} <div class="controls"> <button type="submit" class="btn">Upload</button> </div> </div> </form> This is my view that is used here: def publish(request): if request.method == 'POST': form = PublishForm(request.POST, request.FILES) if form.is_valid(): g = form.save(commit=False) g.developer = request.user.username g.save() profile = UserProfile.objects.get(user=request.user) profile.owned_games.add(g) profile.save() return render(request, 'shop/published.html') else: form = PublishForm() return render(request, 'shop/publish.html', {'form': form}) The URL of the image is correct, but the image itself does not … -
Django Sting trimming breaks encoding using truncatechars templlate tag
this is the text used to trim in the list view my_var = une startup (jeune pousse, société ) and use this template tag for trimming {{my_var | striptags | truncatechars:"50" }} I got this output une startup (jeune pousse, soci&eacu... expected out is : une startup (jeune pousse, socié... but got some unexpected output.... -
Amazon AWS- Gunicorn is throwing a lacks both error whenever I start systemctl
I am unable to start the gunicorn3 using systemctl for some reason. Below are my commands written in gunicorn 3: [Unit] Description=gunicorn daemon After=network.target [Service] User=TodoApp Group=www-data WorkingDirectory=/home/TodoApp/project1-na2165-hw1714-ab7232-rdl394-rk3194 ExecStart=/home/TodoApp/project1-na2165-hw1714-ab7232-rdl394-rk3194/TodoAppEnv/bin/gunicorn3--access-logfile - --workers 3 --bind unix:/home/TodoApp/project1-na2165-hw1714-ab7232-rdl394-rk3194/Todo/Todo.sock Todo.wsgi:application [install] WantedBy=multi-user.target I tried changing the name of the user (which I assume can be anything we want) the working directory and the exec start multiple times. However, I still get the following error: systemd[1]: gunicorn.service: Service lacks both -
Python / Django: cannot email TempFile, 'object has no attribute 'splitlines''
I have written a function that turns a queryset into a CSV file, that is then emailed to the user. Since there is no need to store the file on the system I've decided to use Tempfile objects. However though I am succesfull in writing to these objects, I am unable to read them - which is preventing me from emailing them as attachment columns = instances[0].get_columns # create tempfile, in TEXT (t) mode so as not to trip up the # csv module, which cant handle binary data. file = tempfile.NamedTemporaryFile(mode='wt') try: writer = csv.writer(file) writer.writerow([field[0] for field in columns]) for instance in instances: row = [getattr(instance, str(field[0])) for field in columns] # email the file body = 'The exported file has been included as a attachment.' email = EmailMessage( subject='CSV Export', from_email='******', to=['*****'], body=body, ) email.attach('export.csv', file, 'text/csv') email.send() This triggers the following error: '_io.TextIOWrapper' object has no attribute 'splitlines' After some googling it seemed that I had to .read() the file however, the new code (email.attach('export.csv', file.read(), 'text/csv')UnsuportedOperation: not readable` error. Other posts suggest that, besides .read() I needed to 'rewind' the file using file.seek(0, os.SEEK_END), but the not readable error keeps triggering. If I remove the … -
Error that doesn't reference my code - apparently in templates
The error log of my django project is showing the following error: Exception while resolving variable 'non_field_errors' in template 'admin/change_list.html'. Traceback (most recent call last): File "/home/elections/venv/lib/python3.6/site-packages/django/template/base.py", line 882, in _resolve_lookup current = current[bit] TypeError: 'NoneType' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/elections/venv/lib/python3.6/site-packages/django/template/base.py", line 890, in _resolve_lookup current = getattr(current, bit) AttributeError: 'NoneType' object has no attribute 'non_field_errors' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/elections/venv/lib/python3.6/site-packages/django/template/base.py", line 896, in _resolve_lookup current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'non_field_errors' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/elections/venv/lib/python3.6/site-packages/django/template/base.py", line 903, in _resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [non_field_errors] in 'None' This doesn't appear to be referencing any of my code, and as I don't know where the exception was raised, I have no idea how to go about preventing it. It seems to be referencing something to do with Django's templating language, but I'm not sure what. Does anyone know what would trigger this error? -
Python Django Matplotlib : plotting graph twice
I am currently using Django and Matplot. The problem I am facing is that when calling the below: plt.plot(df[XColumns],df[name], label=name[:]) I works as expect when called the first time but when triggering the same function again it gets hung. No error, just freezes the server and I have to close the command prompt window and restart. Note: I close plt after using each time. Any ideas why? -
Django loggin url
How to enable redirect user after login at personal page included user.id, like http://mysite/client/12. I added app client. urls.py from django.conf.urls import url from . import views app_name = 'client' urlpatterns = [ url(r'^(?P<user_id>\d+)/$', views.user_profile, name= 'user_profile'), ] views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required @login_required def user_profile(request,user_id): user_id = request.user.id return render(request, 'client/profile.html') And changed in settings.py LOGIN_REDIRECT_URL = 'client:user_profile request.user.id' Now when I click LogIn I get error Unsafe redirect to URL with protocol 'client' I think that I am not trying to solve this problem correctly. -
Customize the djoser create user endpoint
I am using djoser for auth purposes. I want to customize the create user end point of djoser. I have a User app. Here is my User model from django.db import models class User(models.Model): email = models.CharField(max_length=100, blank=False) name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) account_address = models.CharField(max_length=30, blank=False) password = models.CharField(max_length=100, blank=False) and here is my serializer from rest_framework import serializers from User.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'id', 'email', 'name', 'last_name', 'account_address', 'password') and my User.urls.py looks like following from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from .views import UserViewSet router = DefaultRouter() urlpatterns = [ url(r'^', include(router.urls)), url(r'^account/', include('djoser.urls')), ] and project's url.py is follwing from django.contrib import admin from django.urls import path from django.conf.urls import include, url urlpatterns = [ path('admin/', admin.site.urls), url(r'^users/', include('User.urls')), url(r'^advertisements', include('advertisements.urls')), url(r'^account', include('wallet.urls')), ] but i am unable to create user with customized model instead when i go to user/account/create i see djoser's default create user view. Anybody please tell where I am doing wrong. Thanks :) -
Where is httpd.conf?
I want to deploy a django app on an Ubuntu machine. I installed apache2: sudo apt-get install apache2 Next, I have to edit httpd.conf (I'm reading this documentation) but I don't know where it is. Where is httpd.conf? -
Django middleware setting cache taking 10 seconds
I have discovered that this piece of code is taking up to 10s when under some load, and I don't get why. Using django 1.8 with python 2.7 from django.core.cache import cache from datetime import datetime class ActiveUserMiddleware: def process_request(self, request): current_user = request.user if request.user.is_authenticated(): now = datetime.now() if current_user.in_class: cache.set('seen_%s_%s' % (str(current_user.in_class.id), current_user.username.replace(" ", "_")), now, settings.USER_LASTSEEN_TIMEOUT) Using memcached django.core.cache.backends.memcached.MemcachedCache With settings USER_LASTSEEN_TIMEOUT = 60 * 60 * 24 * 30 And I know that the database calls and memcache calls are just taking millisecs, it hangs here somewhere in django. -
Filter the objects shown in django admin inline
I am trying to filter the objects shown in the django inline admin. Let's say I have a model class Article: #models.py class Article(models.Model): #some fields If the class Article is used as an Inline somewhere, I do not want the Users(Editors) to be able to see all of the Articles, but to filter them out according to a certain criteria (a pseudo example would be if the Articles have a type field and certain editors are allowed to see only certain types, e.g sport articles, news articles etc.) Reading the documentation of django, I found get_formsets_with_inlines and get_inline_instances, which I do not find any difference in and after trying to edit them, I did not succeed. Can I filter out the objects shown in the inlines by overriding a certain function or should I consider something else? -
Dose Django hava a function like `abort` in Flask? I want to break a request in deal with request params
I want to dealwith request parameters in Django more elegant and here is my code: With that I can use in my view function like this: def testparam(request): name = request_get(request, 'name', required=True) age = request_get(request, 'age', ptype=int, required=True) print('name: ', name) print('age: ', age) return HttpResponse('test param run') Then I ran my Django applicaiton and typed url(http://127.0.0.1:8000/test/param) in chrome but I still got the response with "test param run". I want my django to make a response when request_get function called just like abort function in flask framework. Someone can help me? -
Using Celery with a cookiecutter-django project
I'm currently building a small django project and I decided to use cookiecutter-django for a base as everything I need was included. When setting up the project I asked cookiecutter-django to include the settings for Celery and I can find everything in the project, so far so good. However I do have some issues with getting Celery to run as it should. When I start a task from from an app nothing happens. The docker containers are all started properly. Django and Postgres work, Redis is up and I was able to bash into the container and query it. From the console output I see that the celeryworker container is up and running. I also see that my tasks are being recognized by Celery: celeryworker_1 | [tasks] celeryworker_1 | . metagrabber.taskapp.celery.debug_task celeryworker_1 | . scan_and_extract_meta celeryworker_1 | . start_job After puzzling a lot about this I decided to create a new Docker container for Flower to see what's happening under the hood. Interestingly enough I can see that there is a worker and its name is correct (I compared the worker ID in the Celery container). However if I start a task from one of my views like this: celery_task_id … -
Djano /w gunicorn bottlencking with tiny cpu and memory usage
I have a django/gunicorn/nginx app on D.O. which starts throwing this error once I get up to 50 req/s. [error] 1608#1608: *584100 connect() to unix:/my/app/gunicorn.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: 162.158.222.46, server: hbs.hubro.education, request: "GET /notification/count/ HTTP/1.1", upstream: "http://unix:/my/app/gunicorn.sock:/notification/count/", host: "mydomain.com" The cpu usage is really low, in the 10% area, same with memory. I've tried with gunicorn workers equaling the number of cores, twice the cores, and four times the cores, but it seems the bottleneck is somewhere else. I would be grateful for suggestions on figuring out where the bottleneck is, and if there are any recommended monitoring tools that can give me more data on the issue than the D.O dashboard, like response times, open file count, workers utilized and whatnot. -
Dynamic Model Form Fields
I have a model formset. One of the fields in the base model is a charfield. I need this field to carry different choices depending on the form. i.e. Within the formset, some forms will have choices a,b & c and others will have choice e,f and g. Despite reading Django documentation and several Q&A's in stack overflow, I'm still at a loss. The Django documentation says: Note that choices can be any iterable object – not necessarily a list or tuple. This lets you construct choices dynamically. However, it does not give an example how to do this. Would be grateful if someone could give me an example. My model: class Item(models.Model): budgetcatagory=models.ForeignKey(BudgetCatagory, on_delete=models.CASCADE) name=models.CharField(max_length=50) enName=models.CharField(max_length=30, default ="") detail=models.CharField(max_length=30) layout=models.CharField(max_length=30, default="normal") unit=models.CharField(max_length=30) unit_description=models.CharField(max_length=30, default="") unit_price=models.IntegerField(default=0) QTY=models.IntegerField(default=0) param1=models.CharField(max_length=30, blank=True) param2=models.CharField(max_length=30, blank=True) param3=models.CharField(max_length=30, blank=True) param4=models.IntegerField(default=0) parent=models.CharField(max_length=50, default = "0") cost_ave=models.IntegerField(default=0, blank=True) cost_min=models.IntegerField(default=0, blank=True) cost_max=models.IntegerField(default=0, blank=True) total_cost=models.IntegerField(default=0) objects=ItemManager() def __str__(self): return self.name Instances get constructed via the following code in an object manager: def normalCreate(self, cat, parent, name, description, unit, U, enName, Param1, Param2, Layout, min_val, max_val, ave_val): #import pdb #pdb.set_trace() if parent=="פיתוח": q=House.objects.get(user_id=U.id).plot_size else: q=House.objects.get(user_id=U.id).area I=self.create(budgetcatagory_id=cat.id, name=name, unit=unit, detail='Low', unit_description=description , parent=parent, QTY=q, unit_price=ave_val, total_cost=ave_val*q, enName=enName, cost_min=min_val, cost_max=max_val, cost_ave=ave_val ) I.save() … -
template not exist, everything is correct yet not working
I know it has been asked, but, this is different, please have a look below: I've just create a very simple test project, the folder structure is as such: Ignore the red marks, it's because, it was said to not detect meta programming issues. Just for simplicity sake, I've made the view to be called in the homepage itself, the main project urls.py has the urls: """testproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, re_path from test1.views import test1_detail urlpatterns = [ path('admin/', admin.site.urls), re_path('^$', test1_detail) ] The tag_detail1 views file is just this: from django.shortcuts import render from test1.models import model_test1 as Model from django.shortcuts import render def test1_detail(request): tag = Model.objects.get(name__iexact='birlaman') return render(request, 'test1/test.html', {'tag':tag}) The model database is just a … -
AlamoFire POST will get 'GET not allowed' error form DRF server
Used techs Django 2 with Django Rest Framework (Drf) JWT for authentication iOS/Swift4/Alamofire here the issue. django will recieve Alamofire's POST request as GET request. iOS/swift4 code. static func getToken (){ let username = "root" let password = "DAMnShEIsSoHo1!t" let parameters: [String: Any] = [ "username" : username, "password" : password, ] let url = ApiController.baseServerUrl + "api-token-auth" print("URL :: \(url)") Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default) .responseJSON { response in print("RESPONSE :: \(response)") } } log from iOS RESPONSE :: SUCCESS: { detail = "Method \"GET\" not allowed."; } log from django server my.ip.address - - [04/Mar/2018:07:55:32 +0000] "GET /api-token-auth/ HTTP/1.1" 405 40 "-" "Foodle/0.0.1 (com.domain.Appname; build:2; iOS 11.2.0) Alamofire/4.6.0" what shall i do from here? ps. it works fine on PostMan, DRF web console and CURL -
How to show PasswordResetForm errors in Django messages
I have the following view for my page to reset your password: from django.contrib.auth.forms import PasswordChangeForm def password_change(request): if request.method == 'POST': password_form = PasswordChangeForm(data=request.POST, user=request.user) if password_form.is_valid(): password_form.save() update_session_auth_hash(request, password_form.user) messages.add_message(request, messages.SUCCESS, "Password reset.") return redirect(reverse('elections:home')) else: messages.add_message(request, messages.ERROR, "Error with password reset.") return redirect('/password/new/') else: password_form = PasswordChangeForm(user=request.user) return render(request, 'registration/password_change.html', { 'form': password_form }) Some of my users are reporting that they are unable to change their password, but it is working for me. As I can't ask them what their password is for obvious reasons, I need a more informative error feedback to the user. It is my understanding that PasswordChangeForm generates errors that I can access. Is this true, and if so how do I access these errors in the view to add them to the Django message? If not, how do I create my own form that will return these errors?