Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-oauth-toolkit to issue a JWT token
Tech Stack Django1.10.8 + Python3.6 + docker + React + Axios.js I have a situation where I need to make a server to server call and for this I am using Django-OAuth-toolkit. How can I convert this token to issue JWT token instead? { "access_token": "txxxxxxxxxxxxxxxxxxxxxFB45a", "expires_in": 36000, "token_type": "Bearer", "scope": "read write groups", "refresh_token": "16oKxxxxxxxxxxxxxxxxxxxxx" } to { "access_token": "xxxxxxxx.xxxxxx.xxxxx", "expires_in": 36000, "token_type": "Bearer", "scope": "read write groups", "refresh_token": "xxxxxxxx.xxxxxx.xxxxx" } I have gone through https://github.com/Humanitec/django-oauth-toolkit-jwt/ but I think the version I am using of django-oauth-toolkit are incompatible. -
how to filter a model based on the value of another field in another model in django
i have two models: Model Order class Order(models.Model): truck = models.ForeignKey(Truck, on_delete=models.CASCADE, related_name='relation_truck',default=None) date= models.DateField() product=models.CharField(max_length=30) depot = models.CharField(max_length=10) volume = models.CharField(max_length=30, blank=True) volume_delivered = models.CharField(max_length=30, blank=True) order_status = models.CharField(max_length=50, blank=True) pub_date = models.DateTimeField(auto_now_add=True, blank=True) and another model which is mODEL lOADED: class Loaded(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='relation_order',default=None) status = models.CharField(max_length=50, blank=True) i want to filer the objects with order_status=Received and Loaded from model order on my model Loaded in the views because i have the foreign key order. in my views i have something like: loadings = Order.objects.filter(Q(order_status='Loaded') | Q(order_status='Released') )[0:200] loaded = Loaded.objects.filter(order=loadings[0]) but it doesnt filter the objects with the order status released and loaded in the model loaded. -
django: redirecting back to a multimodel view after passing required variables
I'm receiving the error: Reverse for 'botanyoverview' with arguments '({'flotation_id': '21', 'sample_id': '28780488'},)' not found. 1 pattern(s) tried: ['botany/botanyoverview/flotation/(?P[0-9]+)/sample/(?P[0-9]+)$'] Both ids exist, usually this is an issue in the urls.py but I can't seem to spot it. What I have are several tables/models which are displayed in one html view, you click on one and you go to the edit page, I'm trying to fix the redirect so it returns you to the beginning overview page, this requires the flotation and sample ids. The url works originally but throws this error when trying to redirect back to the original page after editing. I can't see the error, any ideas? views.py def editplantpart(request, pk, fk='', sp='', fl=''): post = get_object_or_404(PlantPart, pk=pk) if request.method == "POST": form = PlantPartForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) sample_id=sp flotation_id=fl post.save() return redirect('botanyoverview', { 'flotation_id': flotation_id, 'sample_id':sample_id,}) else: form = PlantPartForm(instance=post) return render(request, 'plantpart/create_plantpart.html', {'form': form}) urls.py re_path('flotation/(?P<fl>\d+)/sample/(?P<sp>\d+)/fraction/(?P<fk>\d+)/plantpart/edit/(?P<pk>\d+)/edit/', views.editplantpart, name='editplantpart'), html <tr class='clickable-row' data-href="{% url 'editplantpart' fk=plantpart.fraction_id pk=plantpart.plantpart_id fl=flotation.flotation_id sp=flotation.sample_id %}"> -
Django 2.1.1,Ubuntu 16.04,apache2 css and js content-type problem
I get this error Resource interpreted as Stylesheet but transferred with MIME type text/html: "https://django.project-eleven.pro/assets/7c7bec41/dest/main.css". Can't figure out how to fix this, is this apache2 conf problem, or django problem?How can I fix this? Thank you everyone -
How to list attributes of a user in a query set
I'm trying to list users that are a member of a given group using template tags, i'm using the code: @register.inclusion_tag('perms/list-users-in-group.html') def users_in_group(group_name): group = Group.objects.get(name=group_name) query = group.user_set.all() return {'user': query} and my html snippet is <div> <ul class="list-unstyled"> {% for user in users %} <div class="card"> <li>{{ user.values }}</li> <li>{{ user|linebreaks }}</li> <li>{{ user.username|linebreaks }}</li> <li>{{ user.first_name|linebreaks }}</li> <li>{{ user.last_name|linebreaks }}</li> <li>{{ user.email|linebreaks }}</li> </div> {% endfor %} </ul> The query does return a result and the list shows up on the web page however the actual data doesn't, how do you access the fields of user ? -
Cannot resolve keyword 'pub_' into field in views.py
In following tutorial, https://docs.djangoproject.com/en/2.1/intro/tutorial03/ I did exactly the same as the tutorial instructed, create the template file in the polls/templates/polls/index.html: polls/templates/polls/index.html¶ {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} And the views.py: polls/views.py¶ from django.http import HttpResponse from django.template import loader from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) When I start the server, and visit the URL: http://127.0.0.1:8000/polls/, I got the following error: FieldError at /polls/ Cannot resolve keyword 'pub_' into field. Choices are: choice, id, pub_date, question_text Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Django Version: 2.1.7 Exception Type: FieldError Exception Value: Cannot resolve keyword 'pub_' into field. Choices are: choice, id, pub_date, question_text Exception Location: /home/martin/anaconda3/envs/web/lib/python3.7/site-packages/django/db/models/sql/query.py in names_to_path, line 1389 Python Executable: /home/martin/anaconda3/envs/web/bin/python Python Version: 3.7.2 Python Path: ['/home/martin/nlp/web/web', '/home/martin/anaconda3/envs/web/lib/python37.zip', '/home/martin/anaconda3/envs/web/lib/python3.7', '/home/martin/anaconda3/envs/web/lib/python3.7/lib-dynload', '/home/martin/anaconda3/envs/web/lib/python3.7/site-packages'] Server time: Sun, 3 Mar 2019 09:20:08 +0000 Error during template rendering In template /home/martin/nlp/web/web/polls/templates/polls/index.html, error at line 1 Cannot resolve keyword 'pub_' into field. Choices are: choice, id, pub_date, question_text 1 {% if latest_question_list %} 2 <ul> 3 … -
Testing triggers for fulltext search in Django
I'm adding a search engine to a Django project, and thus set up SearchVectorFields on several models, with custom triggers. I would like to unit-test that my columns of type TSVECTOR are updated when the instance of a Model changes. However, I've been unable to find any information on how to test the content of a SearchVectorField... I can't compare my_document.search to SearchVector(Value("document content") or similar, because the first one seems to be string-like, while the latter is an object. TL;DR More precisely, with the model: class Document(Model): ... content = TextField() search = SearchVectorField() and trigger: -- create trigger function CREATE OR REPLACE FUNCTION search_trigger() RETURNS trigger AS $$ begin NEW.search := to_tsvector(COALESCE(NEW.content, '')) return NEW; end $$ LANGUAGE plpgsql; -- add trigger on insert DROP TRIGGER IF EXISTS search_trigger ON myapp_document; CREATE TRIGGER search_trigger BEFORE INSERT ON myapp_document FOR EACH ROW EXECUTE PROCEDURE search_trigger(); -- add trigger on update DROP TRIGGER IF EXISTS search_trigger_update ON myapp_document; CREATE TRIGGER search_trigger_update BEFORE UPDATE OF content ON myapp_document FOR EACH ROW WHEN (OLD.content IS DISTINCT FROM NEW.content) EXECUTE PROCEDURE search_trigger(); How can I test that when I create a new Document instance, its search field is populated with the right values … -
How to remove spaces from the url in Django
How can I remove spaces or any non-alpha-numeric characters from the URLs in Django? My urls.py looks like this. urlpatterns = [ url(r'^(P?<query>^\d+:[a-z]+)/show$', views.results, name='results') ] I want to remove if there is space in the queries like ("/12:some query/show") and fire the query as ex("/12:somequery/show") -
Django - ModelForm - UpdateView -pk
I would like to implement UpdateView in order to update selected objects of my Model. Currently I have: views.py def f_detail(request, fslug): fdetail = F.objects.get(slug=fslug) cffilter = CashFlowFilter(request.GET, queryset=CashFlow.objects.filter(feeder__slug=fslug)) return render(request, 'f/f_detail.html', {'fdetail': fdetail, 'cffilter': cffilter, }) class CashFlowUpdate(UpdateView): model = CashFlow fields = ['amount', 'description'] url.py path('<slug:fslug>/updatecashflow/', views.CashFlowUpdate.as_view(),name = "update_cashflow"), path('<slug:fslug>/', views.f_detail, name="f_detail") update_cashflow.html <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Update"> </form> I get the following error : " Generic detail view CashFlowUpdate must be called with either an object pk or a slug in the URLconf." , which means i need to pass-through the primary key of the object I want to Update... What is the best way to do it? Currently all my objects are displayed via a table (see below)? i could add a column with a url link "Edit", but how to put the pk in it? <table class="table table-bordered"> <thead> <tr> <th>Amount</th> <th>Description</th> <th>Edit</th> </tr> </thead> <tbody> {% for cashflow in cffilter.qs %} <tr> <td> {{cashflow.amount}} </td> <td> {{cashflow.description}} </td> <td> ?????? </td> </tr> {% empty %} <tr> <td colspan="5"> No cashflow matches your search criteria</td> </tr> {% endfor %} </tbody> </table> many thanks -
django: Images are not loading
I need to show images in templates. The images are fetched from models. My models.py reside in an app named services: class Car_model(models.Model): name = models.CharField (max_length = 25, blank=False) ... category = models.ForeignKey (Category, on_delete=models.CASCADE) photo = models.ImageField (upload_to ='static/images/models') I have added these lines in my settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'media') # i added it later STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] I have also added this line in my project_name's urls.py file: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I am trying to get the images in my templates through this code: {% load static %} {% for c in ca %} <p><strong>{{ c.car_no }}</strong>--<em>{{ c.car_model }}</em>--{{ c.garage }}</p> <img src="{{ c.car_model.photo.url }}" height="200" /> <form action="{%url 'booking' c.id c.garage.id %}" method="POST"> {% csrf_token %} <input type="submit" name="the_selected_car" value="Select this car"> </form> {% endfor %} But whatever I try photos aren't showing. I tried by placing this: + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) in my services app's urls.py but that didn't help. -
Python TypeError: Object of type 'User' is not JSON serializable after upgrading to Django 2.1
I'm trying to upgrade a Django project from Django(1.10) to Django(2.1), while doing that I'm just stuck at one error, where I was using the request.user.pk to pass a user create an object. Here's what I have, so far: From models.py: class TaggedArticle(models.Model): user = models.ForeignKey(User, related_name='tagging', on_delete=models.CASCADE) email = models.EmailField(max_length=255) category_fit = models.CharField(choices=choices, max_length=255) article = models.ForeignKey(Article, related_name='articles', on_delete=models.CASCADE) link = models.URLField(max_length=255,) relevant_feedback = models.TextField(blank=True) category = models.CharField(max_length=255,) created_at = models.DateTimeField(default=timezone.now, editable=False) From forms.py: class TagForm(forms.ModelForm): class Meta: model = TaggedArticle fields = ('user', 'category_fit', 'article', 'link', 'relevant_feedback', 'category',) widgets = { 'category_fit': forms.RadioSelect() } And From views.py: class TagView(LoginRequiredMixin, generic.CreateView): form_class = forms.TagForm def post(self, request, *args, **kwargs): try: post_data = request.POST.copy() post_data.update({'user': request.user.pk}) print(post_data.values) form = forms.TagForm(post_data) if form.is_valid(): tag = form.save(commit=False) tag.user = request.user tag.email = request.user.email tag.save() request.session['user'] = tag.user request.session['email'] = tag.email else: print(form.errors) return HttpResponse(form.errors, status=400) print('going to redirect after successful tagging.') return HttpResponseRedirect(reverse('users:dashboard')) except Exception as exp: logging.error(exp) print('error is: {}'.format(exp)) return HttpResponse(exp, status=400) So, on POST request it returns the error below as: TypeError: Object of type 'User' is not JSON serializable When I print the form.errors then it prints: <ul class="errorlist"><li>user<ul class="errorlist"><li>Select a valid choice. That choice is not one … -
is there a way to keep the time in updateview same as the time in createview in django
i have realised that when i run the updateview the listdate changes to the time I updated the listing.Here is my models.py class Listing(models.Model): list_date = models.DateTimeField('date created', blank=True, auto_now=True) favourite = models.ManyToManyField(User, related_name="favourite", blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("user-dashboard") def save(self, *args, **kwargs): if self.is_published and self.list_date is None: self.list_date = datetime.datetime.now() elif not self.is_published and self.list_date is not None: self.list_date = None super(Listing, self).save(*args, **kwargs) -
Using memoization with imports, to avoid querying in database for variables that don't change very often
In Django for an app I have the following structure: app_name - const.py - models.py - forms.py - views.py In const.py I keep the constants and I import them in the other 3 files. I have some variables that I usually obtain from the database (using QuerySet) but this variable don't change very often(months). I want to add this variable as constants to const, and only update this variables value, when there are changed from admin. I want to do this, not to do 1-3 querysets more every time in models/forms/views when are called. If I add them in const, on every importof const.py the database querysets are executed, so in this case I just moved them form views/models/forms to const. So I need a sort of memoization, that can be cross-files/modules. I know how to do basic memoization, but this works only inside the module. -
Django Form - include a "reset" button
I've managed to include a form in my django project using FilterSet. It works very well - no issues. When I have typed something in the form to make a search ('for instance BMW'), the table in my template is filtered on ('BMW'), though my search 'BMW' stays in the field. Hence, I would like to include a button 'clear' on which the user can click and 'BMW' disappears from the field & the search result goes back to the initial table. How can I realise this? Currently I have included a button in my template (but nothing happens when I click on it) <button type="reset" class="btn btn-primary" onclick="resetEffort()""> <span class="glyphicon glyphicon-search"></span> Clear </button> And this is my view.py: def cars_overview(request): car = CarFilter(request.GET, queryset=Car.objects.all()) return render(request, 'cars/cars.html', {'filter': car}) many thanks ! -
Listing all friend requests using django-friendship
I was going to create my own friendship view and everything (But I couldn't figure out how to get everything working in a database) So I opted to use something called django-friendship which seems quite good, and It also came with tags to use in the HTML templates but now I am trying to list all the friend requests I can't seem to do a for statement in the tag which is: {% friend_requests request.user %} What I would like to be able to do is {for friend_requests in request.user} #show this then that# the link to the github page for the project is this: https://github.com/revsys/django-friendship If it comes to it I would prefer to create my own friendship implementation, but I don't know where to start. -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'
I want to make a comments section in my post detail page. For that i was watching a tutorial for that on youtube. Here the tutorial uses function based view and i want to make it class based view. Can anyone please help me convert this to class based view in function based view def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=None) content_type = ContentType.objects.get_for_model(Post) obj_id = Post.id comments = Comment.objects.filter(content_type=content_type, object_id=obj_id) context = { "title": instance.title, "instance": instance, "comments": comments, } return render(request, "post_detail.html", context) so far i tried this way to make it function based class PostDetailView(LoginRequiredMixin,DetailView): model = Post template_name = 'posts/post_detail.html' content_type = ContentType.objects.get_for_model(Post) obj_id = Post.id comments = Comment.objects.filter(content_type=content_type, object_id=obj_id) But this gives me error something like this return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' -
Django: ManyToMany field with multiple fk fields
Here is a simplified version of my models (Django 1.9, if that matters): class Player(models.Model): name = models.StringField() class Match(models.Model): player_1 = models.ForeignKey(Player, related_name="player_1") player_2 = models.ForeignKey(Player, related_name="player_2") Is there any way to add a player.matches field to the model, which would query all matches where the player is player_1 or player_2? Specifically, I want to do this to take advantage of select_related() to reduce n+1 queries when getting matches for each player I know I can re-structure the database to support that, but would prefer not to. -
Can a Django app be run directly from python?
I have created an app with Django, on my Raspberry Pi, as part of my smart home project. Now that i am coming to the end of the project, i would like to make it so that i can run one script and have all of the features of the smart home working. (This would be especially useful as then i can just make it run on boot without having to connect a screen or ssh). What i would like to know is if there is a way i can make a python script that will run the whole Django app so that i don't have to go into terminal and set it up. Is this possible? and if not what is the best way to go about my issue? -
Pandas Record Count into a Date Series
I have a series of records by date. Some dates have no records and some dates have multiple records. I need to but the count of the records into a complete date series. This lists all the dates from start to finish. (covers about 10 years of days) This code works, but takes forever! for i, row in df.iterrows (): x = df_days.loc [ df_days.day == row.date.strftime('%Y-%m-%d') ] df_days.hit.iloc[x.index] = df_days.hit.iloc[x.index] + 1 Is there a faster way? Should this be a groupby? These are the data frames. df["date"] 0 2011-02-15 1 2011-03-04 2 2011-06-05 3 2011-09-17 4 2012-04-19 df_days day 0 2011-02-15 1 2011-02-16 2 2011-02-17 3 2011-02-18 4 2011-02-19 Thank you. -
If.-Value in a for loop: adding selected
Want to add the attribute "selected" to this select-field in my Django-Project: <form id="formselect" method="post"> {% csrf_token %} <select name="position_select" id="position_select"> <option value="0">all positions</option> {% for position in position_options %} <option value="{{ position.id }}" {% if form.position.value == position.id.0 %} selected{% endif %}> Position: {{ position.position_order }} </option> {% endfor %} </select> The result with this if method is that now every option is marked as selected in the output of that HTML. Is there a better way to handle that if-statement in a for loop? I'm submitting this form on every click with: $("#position_select").on("change", function() { document.getElementById("formselect").submit(); }); -
Wagtail Image Upload Directory in Production
I have deployed my Wagtail site and all the static content loads except images uploaded by the user. I have set DEBUG = False, set my directories to: STATIC_ROOT = home/user/static MEDIA_ROOT = home/user/media The problem is that Wagtail is uploading images to: home/user/project/media/ Is there a way to set the image upload directory that is different than plain Django? -
How can I compare a slug url with the current address?
I have this if for a static page: {% if request.get_full_path == "billing/address/" %} test {% endif %} how can I replace billing/address/ with the path getting from here: path('billing/address/<slug:address_slug>/', views.addressChange, name='edit-address') Thanks guys -
Django static file 404 not found
I have searched the similar questions but did not find my answer. My simple webapp structure is: mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py static/ test.txt myfirstapp/ I have set STATIC_URL = '/static/' and STATIC_ROOT = os.path.join(BASE_DIR, "static") and when I start the django server, I print the static path out which is /home/pi/mysite/static, looks correct In my template, the code is: {% load static %} <li><a href="{% static 'test.txt' %}">Test File</a></li> If I click the link, I always got 404. However, if I put the static folder in /home/pi/mysite/mysite/, then the static dir is /home/pi/mysite/mysite/static, this code can work and I can view the txt file. I am confused by the settings, and I thought I set the static directory in settings in the root directory but not in the "mysite/mysite". Why the real behavior is opposite? What is the problem here? Thanks! -
redirect vs reverse django
i have experienced using reverse within get_absolute_url method in the model #but i wish i have an idea about the difference between reverse and redirect , i have tried to search on google about it but there is almost nothing i don't know what should i write also to convince stack overflow that i don't have any other description can anyone help to solve this problem can anyone help to solve this problem can anyone help to solve this problem can anyone help to solve this problem can anyone help to solve this problem can anyone help to solve this problem -
Unable to POST data with foreign key relationship - Django rest
Here are my models : User - I am using the default User provided by django admin class UserProfile(models.Model): user = models.ForeignKey(User,on_delete=CASCADE,related_name='user') phonenumber=models.IntegerField() picture=models.CharField(max_length=20,null=True) #dp=models.ImageField(upload_to='profile_pics',blank=True) points=models.IntegerField(default=0) def __str__(self): return self.user.name def __repr__(self): return str(self.user.name) Here is my View where I am trying to post the data class UserCreate(generics.CreateAPIView): queryset=User.objects.all() serializer_class=None def get_serializer_class(self, *args, **kwargs): if(self.request.method=='GET'): return UserSerializer return CreateUserSerializer def post(self,request,format=None): user=CreateUserSerializer(data=request.data) if(user.is_valid()): user.save() Here is my serializer class CreateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField() username = serializers.CharField(max_length=100) password = serializers.CharField(max_length=255) userprofile = UserProfileSerializer(required=True) class Meta: fields=('username','password','email','userprofile') model=models.User def create(self, validated_data): """ Create and return a new `User` instance, given the validated data. """ userprofile = validated_data.pop('userprofile') instance = super(CreateUserSerializer, self).create(validated_data) instance.save() return instance profile=UserProfileSerializer(data=request.data) if profile.is_valid(): profile.save() return Response(user.data, status=201) return Response(user.errors, status=400) class UserProfileSerializer(serializers.ModelSerializer): class Meta: fields=('phonenumber','picture') model=models.UserProfile def create(self, validated_data): profile = super(UserProfileSerializer,self).create(validated_data) profile.save() return profile User gets saved properly. Problem arises with UserProfile only. It says : Got AttributeError when attempting to get a value for field userprofile on serializer CreateUserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'userprofile'. I understand that it expects 'userprofile' inside 'user', but …