Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To Save A User's Favorite Posts in Django
So, i'm trying to allow a user to favorite a post (in my case Deals), which will later be displayed on their profile page. The problem I'm having --If I look in the Django admin, under a specific user for the 'favorites' field, ALL of the Deals are appearing. I got my initial inspiration from this post here So i added a 'favorites' field to my User model with a Many to Many relationship on my Deal model...like so: favorites = models.ManyToManyField(Deal, related_name='favorited_by') My html template where a user can favorite a 'Deal' looks like this: <form id="favorite{{deal_detail.id}}" method="POST" action="{% url 'deals:favorite' deal_detail.id %}"> {% csrf_token %} <input type="hidden" name="supporttype" /> <input type="submit" value="Add Deal to Favorites" /> My url for favorites is this: url(r'^(?P<pk>[0-9]+)/favorite', favorite, name='favorite') this is the view for 'deal_detail' and 'favorite' def deal_by_detail(request, slug): deal_detail = Deal.objects.get(slug=slug) return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail}) def favorite(request, pk): if request.method == 'POST': deal = Deal.objects.get(pk=pk) deal.save() messages.add_message(request, messages.INFO, 'Deal Favorited.') return redirect('home') -
how to authenticate users in Django rest framework?
I have added some URLs in my Django API for posting deleting and putting data and I don't know how to authenticate users first and give some of them to use these methods and ban some of them -
urls.py django 2.0.2 need parameters
i'm learning django and i'm making a blog tutorial but it's from older version that i have, i have version 2.0.2 and i'm not understand documentation my problem is that i dont know how configure my urls.py this is my three proyect: i need to put archive.html in 127.0.0.1:8000/ and this is my urls code codigofacilito/blog.urls.py : """codigofacilito 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 from . import views urlpatterns = [ path('admin/', admin.site.urls), ] and codigofacilito/codigofacilito.urls.py: from django.contrib import admin from django.urls import path from . import views enter code hereurlpatterns = [ path('admin/', admin.site.urls), ] -
Django REST Framework, limiting fields on foreignkey relationship when serializer depth = 1
I am using the Django REST Framework and I have a serializer as follows: class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile depth = 1 fields = ['user','team','correct','wrong','percentage'] The problem if this passes all user data (including a hashed password). How do I limit the fields being passed? I have a UserSerializer as follows (which holds the only fields I really want): class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['first_name','last_name','username'] -
Django Sign Up with extra fields
I have expanded my SignUp form with UserCreationForm and make email activations. And all works perfect, but I don't understand how I address the new variable. I can't display it in a template and I do not find it in the user admin panel. forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from customuser.models import User class SignUpForm(UserCreationForm): phone = forms.CharField(max_length= 20) #<--my new variable class Meta: model = User fields = ('phone', 'email', 'password1', 'password2',) views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string('reg/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: form = SignUpForm() return render(request, 'reg/signup.html', {'form': form}) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) # return redirect('index') return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') … -
Disable CSRF on api view method(django rest framework)
I have such api method: @api_view(['POST']) @login_required def get_posts(request): # ... How can I disable CSRF only on this method? -
module 'uritemplate' has no attribute 'variables'
I am getting this module 'uritemplate' has no attribute 'variables' using corepai Schema Generator in Drf probably not working -
How can I compare two Django QuerySets and return QuerySet with replacement of the same values from second in first?
My env is Django 2.0.2 and Python 3.6.1. How can I compare two Django QuerySets and return QuerySet with replacement of the same values from second in first? For example, I have QuerySets: >>> qs_local = PriceLocal.objects.filter(user_id=request.user.id) >>> print(qs_local) [{ 'user_id': 1, 'product_id': 1, 'price': 100 }] >>> qs_world = PriceWorld.objects.all() >>> print(qs_world) [{ 'product_id': 1, 'price': 300 }, { 'product_id': 2, 'price': 500 }, ... ] I want to compare this Django QuerySets and return QuerySet, like this: [{ 'product_id': 1, 'price': 100 }, { 'product_id': 2, 'price': 500 }, ...] At this point, we are replacing the same records (with 'product_id': 1) from second to first QuerySet. -
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.