Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does the 'next' parameter work? Django authentication system
I understand that if a user is not logged in the next parameter is used to redirect the user to whatever @login_required decorated view they were trying to access after logging in. Though the way this happens seems a bit automagical. I have the following login related settings: LOGIN_REDIRECT_URL = 'dashboard' # tells django which url to redirect after login if no 'next' parameter is present in the request LOGIN_URL = 'login' # url to redirect the user to log in (for example, views using the login_required decorator) and am using the authentication views fount in django.contrib.auth (only included three for simplicity): from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('', views.dashboard, name = 'dashboard'), path('login/', auth_views.LoginView.as_view(), name = 'login'), path('password_change/', auth_views.PasswordChangeView.as_view(), name = 'password_change'), ] Here is the custom login.html tempate located at account/registration/index.html: <div class="login-form"> <form action="{% url 'login' %}" method="post"> {{ form.as_p }} {% csrf_token %} <input type="hidden" name="next" value="{{ next }}"> <input type="submit" name="" value="Log-in"> </form> </div> Now say I am not logged in and try to access /account/password_change, I will be redirected to login and the path will be http://127.0.0.1:8000/account/login/?next=/account/password_change/, after logging in I can change … -
Error in fetching model data based on date
I wanted to fetch data from Django database based upon the choice selected by the user, which could be past 1, 2 or 6 month. I am unable to get how we can pass this data in our get function. Given below is the code snippet of my views.py wherein I am try to implement the above mentioned task. if 'form2' in request.POST: date_id = request.POST["groupOfDefaultRadios1"] x = employee.objects.get(name = request.user) if date_id == 1: d = transaction.objects.get(emp_id = x, datetime.date.today-timestamp <= 1) elif date_id == 2: d = transaction.objects.get(emp_id = x, datetime.date.today-timestamp <= 2) else: d = transaction.objects.get(emp_id = x, datetime.date.today-timestamp <= 6) return render(request, 'profiles/userLogin.html', {'model':d}) The database entries need to filtered on the basis of months specified. -
I have only one primary key in my Django Model, but it shows error as multiple primary key
My model is class authenticate(models.Model): name=models.CharField(max_length=50) uid=models.CharField(max_length=39,editable=False) image=models.CharField(max_length=250) email=models.CharField(max_length=100,primary_key=True) mobile=models.CharField(max_length=12) dob=models.CharField(max_length=12) regno=models.CharField(max_length=10,editable=False) created=models.CharField(max_length=10,editable=False) last_login=models.CharField(max_length=10) department=models.CharField(max_length=5) admin=models.BooleanField(default=False) Error occurred when tried to migrate my model in Heroku repo: psycopg2.errors.InvalidTableDefinition: multiple primary keys for table "Auth_authenticate" are not allowed The above exception was the direct cause of the following exception: -- -- -- return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: multiple primary keys for table "Auth_authenticate" are not allowed The above model is working perfectly when I am using sqlite DB. -
django query accessing foreign key data
Apology if this is a duplicate but I could not find any satisfying answer for this case. Maybe I am doing something fundamentally wrong, like need to define models in a different way. Suggestions will be really helpful. Suppose I have my models like this: from django.contrib.auth.models import Group class Team(Group): description = models.CharField(max_length=30) class Players(models.Model): name = models.CharField(max_length=60) team = models.ForeignKey(Team, on_delete=models.CASCADE) Now if I for example, want a queryset of all players by the Team model what can I do? I have the foreign key in the Players model and not in Team model. So something like Team.objects.filter(logic) is needed to get all players. But exactly what logic will work here? Any help will be much appreciated. -
How to compare DateTime in django template in Oneweek
I'm trying to use different stylesheet in django template if the time since publish is less than 7 days. but Its not works. model.py import datetime created = models.DateTimeField(default=timezone.now) @property def less_than_week(self): if self.created.datetime.date + datetime.timedelta(days=7) <= datetime.date.today(): return False else: return True template.html {% if post.created.date.less_than_week %} <h1>sample test</h1> {% endif %} -
How can i to turn a site into a mobile application
There is a site built using python / django, I need to turn it into a mobile application, so that only the program shows how the site, how can I do it -
Contact form sending emails from and to the same email -Django
So I am building a three-section webpage and one of these sections contains a contact form for users to send messages to my email (EMAIL_HOST_USER in settings.py). But send_mail(subject, message, email_from, [email_to,], fail_silently=False) is only using EMAIL_HOST_USER for both the sender and the recipient parts and it sends the email from and to that email. And I can't figure out what I am missing here. Here's the code and thank you in advance. views.py from django.shortcuts import render from django.http import HttpResponse from hajar.settings import EMAIL_HOST_USER from django.core.mail import send_mail from .forms import ContactForm def base_view(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = "Hello" name = form.cleaned_data['name'] email_from = form.cleaned_data['email'] email_to = EMAIL_HOST_USER message= form.cleaned_data['message'] send_mail(subject, message, email_from, [email_to,], fail_silently=False) return HttpResponse(f'Thank you for your message, {name}!') form = ContactForm() return render(request, 'base.html', {'form': form}) settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword' forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'mdl-textfield__input required', 'id':'name'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'mdl-textfield__input required', 'id':'email'})) message = forms.CharField(widget=forms.Textarea(attrs={'class':'mdl-textfield__input required', 'id':'textarea'})) -
django ImpropertlyConfigured. The included urlsconf does not appear to have any patterns in it
I am using django 2.2.2 . I am trying to include path('api/', include('music.urls')),into my root url but I get an exception thrown from resolvers.py file. Here is my music/urls.py urls.py from django.urls import path from . import views app_name = 'music' urlpatterns = [ path('songs/', ListSongsView.as_view(), name = 'songs-all'), ] here is my root url file urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('music.urls')), ] views.py from django.shortcuts import render from rest_framework import generics from .models import Songs from serializers import SongSerializer # Create your views here. class ListSongsView(generics.ListApiView): queryset = Songs.objects.all() serializer_class = SongsSerializer and my stacktrace File "/home/brianonchari/Documents/django/drf/myapi/lib/python3.5/site- packages/django/urls/resolvers.py", line 588, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'rest.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Django show extra content in class based view with ForeignKey models
Im trying to add extra content to Djangos Class based view to the template I have some models like this class District(models.Model): district = models.CharField(max_length=255, null=False, unique=False, blank=True) def __str__(self): return self.district class Street(models.Model): street_name = models.CharField(max_length=255, null=False, unique=False, blank=True) district = models.ForeignKey(District, verbose_name=_('district'), on_delete=models.CASCADE, null=True, blank=True) zone = models.IntegerField(blank=True, null=True) def __str__(self): return self.street_name class Article(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name="author", on_delete=models.SET_NULL) timestamp = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=1, choices=STATUS, default=CREATED) comment = models.CharField(max_length=255, null=True, unique=False, blank=True) name = models.CharField(max_length=255, null=True, unique=False) street = models.ForeignKey(Street, verbose_name=_('street'), on_delete=models.CASCADE, null=True, blank=True) class ArticlesListView(LoginRequiredMixin, PermissionRequiredMixin,ListView): model = Article paginate_by = 50 context_object_name = "articles" permission_required = 'is_staff' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['Filter_name'] = Article.objects.order_by().values('name').distinct() context['Filter_user'] = Article.objects.order_by().values('user').distinct() return context def get_queryset(self, **kwargs): return Article.objects.all() And late in the template {% for f in Filter_name %} <ul> <li>{{f.name}}</li> </ul> {% endfor %} What I want is to display a list of the district names and a list of the author names in the template. how can I display models correctly with ForeignKey? -
Adding two numbers and show the output on the same page
I am new to Django, I am not sure if I could do action and show result on the same page. For this page I want to add two numbers that are entered on textarea a1 and a2 together, and output it on textarea a3. Now, the error is showing Page not found (404), I guess it is something to do with my routing. And if I am doing dynamic content like this, should I use VueJS or react instead? Here is my view: def add(request): """The Cipher and Decipher page""" res = 0 val1 = int(request.GET.get('a1', 0)) val2 = int(request.GET.get('a2', 0)) res = val1 + val2 return render(request, 'morse_logs/add.html', {'result': res}) my html (add.html): {% block content %} <h1>Addition</h1> <form action="add"> <textarea rows="10" cols="50" name='a1' ></textarea> <textarea rows="10" cols="50" name='a2' ></textarea> <button type="submit" name="add">Calculate</button> <textarea rows="10" cols="50" name="a3" >{{result}} </textarea> </form> {% endblock content %} my url.py: app_name = 'morse_logs' urlpatterns = [ # Home Page path('', views.index, name='index'), # Page that shows all topics path('topics/', views.topics, name='topics'), # Page that do addition path('add/', views.add, name='add'), ] -
Multiple datetime picker for Django calendar
I am a newbie to Django. I would like to create a Django Web-App similar to the Doodle Calendar. The web-app is supposed to show a calendar. The user should be able to create an event and select various timeframes from the calendar to propose available times for the event. Does anyone have a proposal how I can select various dates by clicking on the calendar and store them into a list? Thank you in advance for your help! -
Show pdf in Django template
I have stored a pdf in my media folder and would like to embed it in my template. It says '127.0.0.1 is blocked' and '127.0.0.1 refused to connect'. My HTML code: <embed src="{{ project.publications_pdf.url }}" type="application/pdf" height="700px" width="500px"> The url is stored in the Project model as publications_pdf. -
Django - generic UpdateView works in one form but not in other
I am working on a web application for my school project and I chose Django and all the tutorials found online were pretty comprehensive and I manage to get to some point to where I am stuck. I have the following class based view trying to update an object: views.py class MyPostUpdateView(UpdateView): model = Post fields = ('VideoURL', 'MainDescription') template_name = 'myapp/editpost.html' Then, I imported in my urls.py: path('profile/account/my-posts/<int:pk>/edit/', MyPostUpdateView.as_view(), name='myapp-editpost') Then, in my HTML template I have a several <form> elements but all belongs to the same <div> element: <div class="row"> <div class="col-12 col-lg-7"> <form method='post' class="card shadow-soft border p-4 mb-4"> {% csrf_token %} <h5 class="mb-4">Form1</h5> <div class="form-group"> <label for="MainDescription">Titlu</label> {{form.MainDescription|add_class:"form-control shadow-soft"}} </div> <div class="row"> <div class="col"> <button class="btn btn-primary btn-dark mt-2 animate-up-2" type="submit">Update form 1</button> </div> </div> </form> </div> <div class="col-12 col-lg-5"> <form method='post' class="card shadow-soft border p-4 mb-4"> {% csrf_token %} <h5 class="mb-4">Form2</h5> <div class="form-group"> <label for="VideoURL">Video URL:</label> {{form.VideoURL|add_class:"form-control shadow-soft"}} </div> <div class="row"> <div class="col"> <button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right" type="submit">Update form 2</button> </div> </div> </form> </div> </div> The behavior is the following: I cannot update any of the two fields if I leave the HTML code as above. However, if I bring together the … -
Django Rest Framework how to group by date and return model
I am using DRF and django-filters to return a list of Tournaments. This has to work with a calendar on the front end so I want to group by the date field and return the initial object. My view: class TournamentDayCountViewSet(viewsets.ModelViewSet): queryset = Tournament.objects.all() serializer_class = TournamentCalendarSerializer # permission_classes = [permissions.IsAuthenticated] distance_filter_field = "latlng" filter_backends = (DjangoFilterBackend, DistanceToPointFilter, OrderingFilter) filterset_class = TournamentDayCountFilter class TournamentDayCountFilter(TournamentFilter): def filter_queryset(self, queryset): return ( queryset.annotate( start_date=Trunc("time_stamp", "day", output_field=DateTimeField()) ) .values("start_date") .annotate(tournament_count=Count("id")).order_by() ) and serializer """Serialize calendar info only pertinent to displaying count for speed, pagination is very high""" tournament_count = serializers.IntegerField() start_date = serializers.DateTimeField() class Meta: fields = ("tournament_count", "start_date") This currently returns results like { "tournament_count": 1, "start_date": "2019-01-12T00:00:00Z" }, { "tournament_count": 2, "start_date": "2020-01-18T00:00:00Z" }, I suspect I have to do something like results = defaultdict(list) qs = queryset.annotate( start_date=Trunc("time_stamp", "day", output_field=DateTimeField()) ).annotate(tournament_count=Count("id")).order_by('start_date') for tourney in qs: results[tourney.start_date].append(tourney) return list(results) But currently that doesn't work. The results I would like are [ {'2020/01/10': [{'count': 1, tournaments: [...]}, {'2020/01/11': [{'count': 2, tournaments: [...]}, ] How do I efficiently return results like this so that I don't have to manipulate a regular queryset on the front end? -
Duplicate key error after an exception DoesNotExist has been raised in Django
I need to insert new Candle objects which has a datetime field option unique=True. To avoid validation error when creating the object I first test if I can get it with objects.get() and when an exception DoesNotExist is raised I create it. My problem is that after an exception is raised, the creation failed because a key is duplicated. try: Candle.objects.get(market = instance, dt = dt) except Candle.DoesNotExist: Candle.objects.create( market = instance, dt = dt ) As you can see I try to get the candle for a specific market, which is the instance I'm working on. And it seems to work because it throws the exception. However, when it creates the object another exception is raised for violation error: duplicate key value violates unique constraint "marketsdata_candle_timestamp_key" DETAIL: Key (dt)=(2019-11-28 00:00:00+00) already exists. My analysis is that a candle with the same dt field exist in another market, but it shouldn't throw a violation error because I specify market = instance to create the candle in the instance of the market I'm working on. And it works just fine with the get. Also what I found weird is that Candle doesn't have a field timestamp since it has been renamed … -
Making nested JSON optional
My webhook is successfully receiving details of payments from my bank. Below are my JSON serializers which validate the JSON received from the bank. Payments come thru successfully and get logged. But bank transfers are failing validation because they don't contain the nested Merchant info. I tried setting Required=False in the serializers but I still get error: {'data': {'merchant': [ErrorDetail(string='This field may not be null.', code='null')]}} How do I configure the serializers to validate with or without the merchant info? Serializers.py: class MerchantSerializer(serializers.Serializer): id = serializers.CharField(required=True, max_length=50) name = serializers.CharField(required=True, max_length=100) logo = serializers.URLField(max_length=250, required=False) class DataSerializer(serializers.Serializer): account_id = serializers.CharField(required=True, max_length=50) amount = serializers.IntegerField(required=True) created = serializers.DateTimeField() currency = serializers.CharField(required=True, max_length=3) description = serializers.CharField(required=True, max_length=250) id = serializers.CharField(required=True, max_length=50) category = serializers.CharField(required=True, max_length=100) is_load = serializers.BooleanField() merchant = MerchantSerializer(required=False) # Have set this to false but still not working class TransactionSerializer(serializers.Serializer): type = serializers.CharField(required=True, max_length=50) data = DataSerializer() The JSON for bank transfer (which fails validation) - sensitive info hashed: { 'type': 'transaction.created', 'data': { 'id': '##########', 'created': '2020-01-18T14:36:52.337Z', 'description': 'MONZO', 'amount': 1000, 'fees': {}, 'currency': 'GBP', 'merchant': None, 'notes': 'MONZO', 'metadata': { 'faster_payment': 'true', 'fps_fpid': '#####', 'fps_payment_id': '####', 'insertion': '###', 'notes': 'MONZO', 'trn': '#######' }, 'labels': None, 'account_balance': 0, … -
Reverse for 'login' not found. 'login' is not a valid view function or pattern name
It gives the error: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. It says NoReverseMatch. Tried replacing the url login with accounts:login and didn't work. <form id="logoutForm" action="/logout/" method="post" class="navbar-right"> {% csrf_token %} <ul class="nav navbar-nav navbar-right"> <li><span class="navbar-brand">Hello {{ user.username }}!</span></li> <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li> </ul> </form> {% else %} <ul class="nav navbar-nav navbar-right"> <li><a href="{% url 'login' %}">Log in</a></li> </ul> {% endif %}``` My accounts app urls file: ```urlpatterns = [ path('login/', LoginView.as_view ( template_name='accounts/login.html', authentication_form=forms.BootstrapAuthenticationForm, extra_context= { 'title': 'Log in', 'year' : datetime.now().year, } ), name='login'), path('logout/', LogoutView.as_view(next_page='/'), name='logout'), path('signup/', views.signup, name='signup'), ]``` My main urls file: ```urlpatterns = [ path('', views.home, name='home'), path('', include('accounts.urls')), path('contact/', views.contact, name='contact'), path('about/', views.about, name='about'), path('admin/', admin.site.urls), ]``` I don't know what to do about this, tried many stuff. -
Trying to reference foreign key field...Why is it also displaying the name of the referenced table?
I'm trying to display data from my template. The issue I'm having is with the foreign key in the BattingStats table that references playerid of the PlayerInfo table. When I get it to display, the data for that field is showing but it is wrapped in parenthesis and preceded by ReferencedTable object. So for me it looks like this PlayerInfo object (smithjo05). Why would it be doing that and how would i get it to just show the playerid? Help is appreicated. Thanks. VIEWS def battingview(request): playerinfo = PlayerInfo.objects.all() playerstats = BattingStats.objects.filter(year=2018) return render(request, 'playerstats/battingRegStnrd2018.html', {'playerinfo':playerinfo,'playerstats': playerstats}) MODELS class BattingStats(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) playerid = models.ForeignKey('PlayerInfo', models.DO_NOTHING, db_column='playerID', blank=True, null=True) player = models.CharField(db_column='Player', max_length=255, blank=True, null=True) hr = models.IntegerField(db_column='HR', blank=True, null=True) rbi = models.IntegerField(db_column='RBI', blank=True, null=True) ba = models.FloatField(db_column='BA', blank=True, null=True) class PlayerInfo(models.Model): playerid = models.CharField(db_column='playerID', primary_key=True, max_length=255) namefirst = models.CharField(db_column='nameFirst', max_length=255, blank=True, null=True) namelast = models.CharField(db_column='nameLast', max_length=255, blank=True, null=True) height = models.IntegerField(blank=True, null=True) debut = models.CharField(max_length=255, blank=True, null=True) finalgame = models.CharField(db_column='finalGame', max_length=255, blank=True, null=True) HTML {% for index in playerstats %} <td>{{ index.playerid }}</td> <td>{{ index.year}}</td> <td>{{ index.age}}</td> <td>{{ index.team}}</td> <td>{{ index.league}}</td> {% endfor %} {% for index in playerstats %} {{ index.playerid }} {% endfor %} Browser … -
How to login users with the build-in admin login panel for my own app?
Django comes with a built-in admin page, which has it's own login panel. Most Django sites implement their own login panel. That makes sense, since it gives them a lot of flexibility. But for some apps it would be sufficient to use the existing admin login panel instead of implementing your own. Of course I could just redirect the user to the admin login page. However, after login the user is automatically is redirected to the main admin page and I would like him to be redirected to my app' s page instead. -
How to add 2 different logins for different users in Django Rest Framework?
I wanna make an app with 2 types of users Regular Users that will log in into the app and use it Admin Users that will log into the app to manage resources I know I could easily just make a field is_staff to differentiate if the user is admin or not, but the thing is....The regular user should not have password at all, it will be logged via the facebook/google api, but the admin users do need a password and can't log in via their google accounts So I made a model User like this """ User model.""" # Django from django.db import models from django.contrib.auth.models import AbstractUser # Utilities from api.utils.models import BaseModel class User(BaseModel, AbstractUser): """ User model. """ email = models.EmailField( 'email address', unique=True, error_messages={ 'unique': 'A user with that email already exists.' } ) facebook_id = models.CharField(blank=True, max_length=255) google_id = models.CharField(blank=True, max_length=255) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: db_table = 'users' def __str__(self): """ Return email""" return self.email def get_short_name(self): """ Return email""" return self.email Now I made something similar for the Admin User """ Admin User model.""" # Django from django.db import models from django.contrib.auth.models import AbstractUser # Utilities from api.utils.models import … -
Error in path with django-storages with dropbox
This is my settings code DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = "my token" DROPBOX_ROOT_PATH = "Apps/Djangoproject" The error i am getting while uploading a image: ValidationError: did not match pattern '(/(.|[\r\n])|id:.)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)' how to solve this issue? Anyone know how to solve this issue? -
How to change Text of Button?
Hello I am working on Blog in Django. I have a comment section in my blog page. Each Comment has a button "Show Replies" when I click it shows a hidden div which contains replies on that particular comment.I want to change the text of button from "Show Replies " to "Hide Replies" when I click it and when I click "Hide Replies " I want to change it to "Show Replies". $('.showreplybutton').click(function() { $('#divreplies' + a).toggle(500); }); .divreplies { display: none; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class='showreplybutton'>Show Replies</button> <div class="divreplies"> Code for Showing Replies </div> -
Format display of timedelta() Python Django
I have an object which has "time" property. "time" property value is seconds. I'm using tempalate filter to change it into desired format: @register.filter(name="timedelta") def timedelta(timedeltaobj): delta = datetime.timedelta(seconds=timedeltaobj) return delta This filter returns correct value, for example: 1:01:07.249000 But the problem is that i want only 3 digits after comma "1:01:07.249". Is there any simple way to do this? -
How to save pdf in download directory rather then current working directory in python?
I have written simple pdf splitting code in django using PyPDF2 but it is downloading splitted pdf in same directory(cwd).How do i specify path so that it will downloaad it in Download directory? -
How deploy django website to cpanal godaddy
i am trying to deploy my first Django application to godaddy cpanal i created my application in a virtual environment so in cpanal what these field means 1.Application Root 2.Application URL 3.Application start up file( i know this is manage .py how should i add in it the URL is it like local disk/new folder/project/manage .py 4.application entry point 5. passenger log file