Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at /Reverse for 'newsdesc' with keyword arguments '{'slug': ''}' not found
I am running a django project to display a website. Here is my views.py : def news_desc(request,slug): # request.session.flush() news=NewsPort.objects.get(news_title_slug=str(slug)) return render(request,'accounts/newsdesc.html',{'news':news, 'slug':slug}) urls.py : urlpatterns = [ path('signup/', views.signup, name='signup'), path('login/', views.user_login, name='user_login'), path('logout/', views.user_logout, name='user_logout'), # path('', views.index, name='index'), path('<int:pk>/',views.index_with_pk, name='index_with_pk'), path('profile/<int:pk>/',views.profile_detail,name='profile_detail'), path('profile/<int:pk>/edit/',views.profile_edit,name='profile_edit'), path('profile/<int:pk>/wallet/',views.wallet_view,name='wallet_view'), path('profile/<int:pk>/wallet/transac',views.history_transac,name='history_transac'), path('news/all/', views.news_all, name='news_all'), path('profile/<int:pk>/maps/',views.map_view,name='map_view'), path('news/<slug:slug>/',views.news_desc,name='newsdesc'), ] when i run, i am getting a error like this NoReverseMatch at / Reverse for 'newsdesc' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['accounts/news/(?P<slug>[-a-zA-Z0-9_]+)/$'] I dont know what exactly my error is. Any help would be appreciated. -
Django equivalence with datetime
I need that every day the voted_today field is reset to 0. from django.db import models from datetime import datetime, time from django.conf import settings from places.models import Place class Subscription(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) place = models.ForeignKey(Place, on_delete=models.DO_NOTHING) last_vote_date = models.DateTimeField(default=datetime.now) voted_today = models.IntegerField(default=0, editable=True) def __str__(self): return self.user I think something like this: def reset_votes_day(user, current_stade): subscription = get_object_or_404(Subscription, user=user, place=current_stade.place) if (subscription.last_vote_date != today()): subscription.voted_today = 0 subscription.save() But I don't know How can I do this correct: subscription.last_vote_date != today() -
Django ValueError at / The view todolist.views.index didn't return an > HttpResponse object. It returned None instead
I got this error message when I try to create my todo. Error message is: ValueError at / The view todolist.views.index didn't return an HttpResponse object. It returned None instead. def index(request): if request.method == 'POST': form = ListForm(request.POST or None) if form.is_valid(): form.save() all_tasks = List.objects.all messages.success(request, ('Task Has Been successfuly Added to Your List!')) return render(request, 'index.html', {'all_tasks': all_tasks}) else: all_tasks = List.objects.all return render(request, 'index.html', {'all_tasks': all_tasks}) -
Error 'AnonymousUser' object has no attribute '_meta' when updateprofile
so i try to make a page to update profile , so when i try to update -> the database is success updated , but the frontend keep showing this error 'AnonymousUser' object has no attribute '_meta', i dont know why it occured , but here's the code profile.html {% load staticfiles %} {% block body_block %} <div class="container"> <div class="jumbotron"> {% if registered %} <h1>Thank you for updating!</h1> {% else %} <h1>Update Here</h1> <h3>Just fill out the form.</h3> <form class="cmxform form-horizontal style-form" id="commentForm" enctype="multipart/form-data" method="POST" action=""> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} <input type="submit" name="" value="Update"> </form> {% endif %} </div> </div> {% endblock %} views.py(include register + update) def update_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = UserProfileInfoForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile_form.save() messages.success(request, ('Your profile was successfully updated!')) return redirect('/profile/') else: messages.error(request, ('Please correct the error below.')) else: user_form = UserForm(instance=request.user) profile_form = UserProfileInfoForm(instance=request.user.profile) return render(request, 'profile.html', { 'user_form': user_form, 'profile_form': profile_form }) def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' … -
How to apply specific css to Django login form
Here is the code of that form: <div> <h2>Login here</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> </div> This form comes from django.contrib.auth -
Django: listing many-to-many intermediate model instances gives 404 error
I have a similar set up as that illustrated in the documentation Extra fields on many-to-many relationships with some changes. class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) And in serializers.js, I have class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ("name") class MembershipSerializer(serializers.ModelSerializer): person = PersonSerializer() class Meta: model = Membership fields = ("person", "date_joined", "invite_reason") And in view.js, I have class GroupMembershipViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = MembershipSerializer(many=True) lookup_field = "group_name" def get_queryset(self): queryset = Group.objects.get(name=self.kwargs["group_name"].membership_set.all() return queryset I have checked that the queryset in get_queryset is not empty. However, when I actually try e.g. localhost:3000/group-membership/group123, I am getting HTTP 404 Not Found. Any thoughts? -
How do I dynamically change link tags in header based on region in Django CMS
I'm looking for a way to change link tags with hreflang depends on region or language used on a site. For example: I have one blog site written in english and on this site I would like to have: <link rel="alternate" hreflang="en" href="https://example.com" /> <link rel="alternate" hreflang="de" href="https://example.com/de" /> And for German version: <link rel="alternate" hreflang="de" href="https://example.com/de" /> <link rel="alternate" hreflang="en" href="https://example.com" /> I could do that with statements like this: {% if request.build_absolute_uri == "https://example.com" %} {% if request.build_absolute_uri == "https://example.com/de" %} but what if I will have more then these two paths and my if statement will grow. Is there a better solution? -
With drf-yasg, how to use statics schemas and manage custom permissions?
I am a little confused how to develop the documentation using the drf-yasg library. So I would like to ask exactly: How can I use a static swagger.json file created by swagger editor online with drf-yasg? (There are endpoints in my project that don't have serializers and models, so i created the schema manually!) My project use a permissions control with custom management. Is there any way to manage the endpoints urls in the schema if the user is not allowed permission to view specific endpoint? -
Django - Am I in the right direction for creating the models of my travel collaboration application?
I am learning Django by building an application, called TravelBuddies. It will allow travelers to plan their trip and keep associated travel items (such as bookings, tickets, copy of passport, insurance information, etc), as well as create alerts for daily activities. The application will also able to update local information such as weather or daily news to the traveler. Travelers can also share the travel information with someone or have someone to collaborate with them to plan for the trip. So, it will have the following features: Main traveler will be able to manage (add, delete and share) trip details and add co-traveler (collaborative planning). Traveler will be able to login, view and update profile. Trip will contain travel schedule and each schedule may have associated travel items. Any changes made to the schedule will be logged. For collaborative planning, each traveler will be notified of the changes. Here is one of the wireframes of my project: I have built the data model of the app. Here are my codes in models.py: from django.db import models # Create your models here. from django.template.defaultfilters import slugify class Coplanner(models.Model): coplanner_name = models.CharField(max_length=20) def __str__(self): return self.coplanner_name class Trip(models.Model): trip_name = models.CharField(max_length=100) planner_name … -
Django, 2 forms on one page, one form uses data from the other
Here are my models: from django.db import models ATTACK_TYPES = ('EXA','Example') class AttackImage(models.Model): title = models.CharField(max_length=255) image = models.ImageField(upload_to='attack_images') source_url = models.URLField(blank=True,null=True) class AttackItem(models.Model): attack_image = models.ForeignKey(AttackImage, on_delete=models.CASCADE) attack_used = models.CharField(max_length=55, choices=ATTACK_TYPES) hidden_data_found = models.BooleanField(blank=True) I want a user to be able to create an attackitem and an attackimage at the same time, with the attackitem having a foreignkey relation to the attackimage, as you can see. How can I do this? Thanks in advance. -
Creating signup process using a bootstrap theme
I am trying to create a signup process, allowing a user to signup. I have an existing signup theme that I am using. This is what I have in settings.py INSTALLED_APPS = [ 'sendemail.apps.SendemailConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] and urls.py from django.contrib.auth.views import LoginView urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('about/', views.about, name='about'), path('courses/', views.courses, name='courses'), path('course-details/', views.coursedetails, name='course-details'), path('login/', views.login, name='login'), path('', LoginView.as_view()) and signup.html {% load static %} <!DOCTYPE html> <html lang="en"> ..... -
django: how to get the current url that the user is visiting on my site
I have a django project with two different apps: market and forum. All market related urls starts with /market/ and all forum related urls starts with /forum/. I want to have a search box which can search globally, but will prioritize search results based on the current url that the visitor is on. For example, if a user is currently visiting forum-related sites and searched something, I would show search results from forum posts first. Below is my search form <form class='search-form' action="{% url 'search_forum_market' %}" method="GET"> <input id='search-bar' name="searchterm" type="text"> <button class="searchbutton" type="submit">Go</button> </form> It will be great if I can pass a variable in the action, something like "{% url 'search_forum_market' option='' %}". -
DJ-Stripe Subcriptions
Can anyone clearly explain how the process (workflow) for a new subscription is while using the DJ-Stripe app? I'm very noobish to this, and want to make sure I'm thinking correctly. Using the latest stripe with payment intents. My idea of the workflow is this dj-stripe creates a stripe customer ID during registration for the app after the customer selects a 'plan' that creates a 'payment intent' for the user payment intent gets passed to the checkout phase, along with plan ids and price which completes the purchase via stripe elements Is that correct? Can anyone simply this anymore for me? Thanks! -
Django. Import module error. ModuleNotFoundError: No module named 'foo'
This is very simple. I have a new project with these files: in my urls file, how can I import the home.views? I thought this would work: from django.contrib import admin from django.urls import path from website.home import views <--- urlpatterns = [ path('admin/', admin.site.urls), ] But when I runserver o makemigrations or anything I get: ModuleNotFoundError: No module named 'website.home' I am clueless. Plz help. I have included 'home' in INSTALLED APPS -
Can I host Python Django Application on german V-Server (Provider: Strato)
Hello dear Community, I have developed a Python Django project and want to host it on my german V-Server on the provider strato. I don't know if the server provider "strato" makes it possible to run a Django application on it. Therefore the QUESTION, if you can host a Django application on every V-Server? or if it has to be a special provider e.g. DigitalOcean. I am very grateful for any advice! Thank youu :) Best regards, programmerg -
I am getting a date of "598146673" when I use JSONEncoder with a Date type
Title says it all. I don't mind getting the date as "598146673" but I just need to convert it when I receive that on my Django. Ideally, I would like to what format it is or how I can have xcode leave it in "2019-12-15 23:51:13 +0000" -
Django 2.2 Cannot figure out how to authorize user to edit or delete blog post if user created that blog post
So this is the third time I'm asking this question. I don't know how to allow only a user, that created a particular blog post, to edit or delete that post. So this blog is like any other blog. All users can look at all other users blog posts. To create a blog post, a user must be logged in with an account already. Same thing for edit and delete a blog post. However, I don't know how to check to see if a user can edit or delete a blog post based off whether that user was the one that created the blog post or not. I'm typing this question since no one answered my previous questions I posted. below are three files for models, views, and the html for update/edit a blog post. I can figure out the delete once I figure out the edit. I know Django creates add, change, delete permissions automatically. Unfortunately, the change and delete permissions always return false, even if that user is already logged in. I've been stuck on this for days. Like 15+ hours already over three days. blog/models.py from django.db import models from django.conf import settings from django.utils import timezone … -
Best way to add custom SQL to a queryset in Django 2.2.4+?
I'm looking to add the following line of SQL to my django queryset's SQL query. "SET LOCAL enable_nestloop = 'off';" (this line configures my postgres database to behave a certain way, which I need for this specific query I'm running). This line of SQL has nothing to do with the query, so .extra doesn't seem appropriate. https://docs.djangoproject.com/en/2.2/ref/models/querysets/#extra The context I'm in (a django-rest-framework ViewSet w/ a custom filter) requires me to maintain a queryset object. Therefore I can't use .raw either, because it returns a RawSQL object https://docs.djangoproject.com/en/2.2/topics/db/sql/#performing-raw-sql-queries Finally, I cannot write a completely raw cursor.execute command because the query is dynamic and extremely complicated, so a queryset is a must. How do I add this 1 line of SQL to the queryset query? Thank you! -
Django, How to transform from a queryset to json and use a value from a key?
This is my model.py class Ont_Pruebas_Json(models.Model): usuario_id = models.CharField(max_length=12) data = jsonfield.JSONField() def __str__(self): return '{}'.format(self.usuario_id) On data field I am storing this: {u'1': {u'user': u'user1',u'mac': u"'00:00:00:00:00:01'"}, u'2': {u'user': u'user1',u'mac': u"'00:00:00:00:00:01'"}} On my views.py I am passing the query set this way: context['context_json'] = Ont_Pruebas_Json.objects.all() How can pass from the queryset to json format so I can choose for example from 1 the key mac and get the value: 00:00:00:00:00:01. -
How to associate only a subdomain to my Django App on Digital Ocean?
We already have a website called X.com. Now I am building a Django App on a Digital ocean Droplet. I am able to access it using the IP-address. But we want to have it called reporting.X.com for sharing it with our users. On my domain providers, I already added an A record like the below Host- reporting Type - A Content - <ip-address> of digital ocean droplet However I keep getting a 400 error when I try to access reporting.X.com. What should I do? -
Django update template after download completes
I have a function which is called via a user action in my template: <a href="{% url 'channels:download_channel' channel.id %}" onclick="showLoader()"> download_channel is a function that merges audio files (into one file) and initiates a file for download. This can take some time and isn't instantaneous. So I show a spinner. showLoader() is a javascript function that simply shows a spinner to let the user know the process/download is ongoing. My problem is when the download is finished on the server side, I have no way of communicating with the template to hide the spinner I've tried via ajax, but I guess you can't initiate downloads that way (unsafe). This was the ideal solution I was hoping would work. function downloadChannel() { showLoader() $.ajax({ type:'GET', url:'{% url "channels:download_channel" topic.id %}', success:function(json){ console.log('got some success of heah') hideLoader(); location.reload(); }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); hideLoader(); // provide a bit more info about the error to the console } }); } I've looked at django channels, but sockets seem like a big setup for such a simple problem. I'm a bit stumped on how to properly approach this problem. Any feedback is greatly appreciated -
Django media files, and horizontal scalabilty
I have recently started working on web development with Django, and I am planning to make a horizontally scalable web app. I would like the web app to allow users of the website to upload/download files/images and media in general. Seems like a lot of tutorials out there, including Django doc's approaches do not support horizontal scalability, as they rely on local storage for saving media. https://docs.djangoproject.com/en/2.2/topics/files/ Something I was wondering I could do is to save those images in the SQL database, but some people I know were quick to point out that this may slow down the database tremendously. And now I am here with the question: What do you think is a good way of solving this issue, where I would like a scalable web app, that supports media upload/download capabilities. Note: I am by no means trying to transfer terabytes of data. This is more of a school project for myself, but I would like to get it right from the get-go. -
Is it possible to run django app on raspberry pi zero w [closed]
As per title, considering no calculations are performed on app side, is it safe to assume a simple django app will work okay? Are there specific system requirements for django, or does it run on anything capable running python? -
Issues with Pipenv on git-bash.exe
OS Info: OS: Windows 10 Version: 1909 Build: 18363.476 Python Info: Python: v3.8.0 Python path: C:\Python\38 Pip: v Pip Path: C:\Python\38\Scripts Terminal: shell: bash.exe (git-bash) version: 2.24.0.2-64-bit Issue: Trying to initiate dependency management running on bash.exe (git-bash) and end up with some issues... $ pipenv shell Warning: Python 2.7 was not found on your system… You can specify specific versions of Python with: $ pipenv --python path\to\python Trying to install another package such as pipenv install django would give me same error. I am not sure what's exactly error was and I cannot find any solution after searching around answers for 2 days. What have I done? I have downloaded python3.8 (Windows x86-64 executable installer for win 64 AMD64/EM64T/x64) from this site https://www.python.org/downloads/release/python-380/. Installed python3.8 following my customized path C:\Python\38 and made sure "Add Python3.8 to PATH" is checked before begin installing. After completed install python in my system, I have installed pipenv following pip install pipenv Installation was success after confirmed with pipfreeze pip freeze astroid==2.3.3 autopep8==1.4.4 certifi==2019.11.28 colorama==0.4.1 isort==4.3.21 lazy-object-proxy==1.4.3 mccabe==0.6.1 pipenv==2018.11.26 pycodestyle==2.5.0 pylint==2.4.3 six==1.13.0 virtualenv==16.7.8 virtualenv-clone==0.5.3 wrapt==1.11.2 and there's pipenv.py inside C:\Python\38\Scripts. What exactly is my issue, and is there a way to resolve it? Thanks in … -
Downsides of using Gunicorn with Django for development
Gunicorn + Django is a typical combo for production environments. Are there any downsides, apart for the added complexity, of using Gunicorn also for development, instead of runserver?