Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django datatables.net
I am using Django and jquery datatables.net My model has more than 13000 records When it starts it shows list like datatables.net is not active and the columns is auto adjusting and after it finishes loading it takes 20sec the data it shows with datatables.net active and works perfect and show the pagination and search How should I make it only show the table from datatable.net and increase the speed What am I doing wrong? Thanks prutable.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Hello, Table!</title> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"> </head> <body> <table id="table_id" class="display" border='2' align="center" style="width:100%"> <thead> <tr> <th>Codigo</th> <th>Descripcion</th> <th>Importe</th> <th>Stock</th> </tr> </thead> <tbody> {% for articulo in object_list %} <tr> <td>{{ articulo.cdg }}</td> <td>{{ articulo.desc }}</td> <td>{{ articulo.imp }}</td> <td>{{ articulo.stock }}</td> </tr> {% endfor %} </tbody> </table> </body> <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script> <script> $(document).ready(function () { $('#table_id').DataTable({ } ); }); </script> views.py class LstPreListView(ListView): template_name = "base/prutable.html" queryset = Articulo.objects.all().order_by("desc") models.py class Articulo(models.Model): cdg = models.CharField(primary_key=True, max_length=20, blank=True, null=False) desc = models.CharField(db_index=True, max_length=200, blank=True, null=True) imp = models.DecimalField(max_digits=14, decimal_places=2, blank=True, null=True) stock = models.IntegerField(blank=True, null=True) def __str__(self): return '{} '.format(self.nombre) -
Why doesn't my form remove the selected object?
I'm trying to create a form to unsubscribe newsletter subscribers, but I don't know exactly where I'm going wrong. The steps in my view all work in the command line so its hard for me to debug. When I submit the form on an existing email address the error is 'Subscriber with this email already exists', but I'm trying to delete an object not create one, and I'm a little stuck. Any help is much appreciated! My View: from subscribe.forms import SubscribeForm, UnsubscribeForm from django.shortcuts import render, HttpResponseRedirect from django.contrib import messages from .models import Subscriber from django.shortcuts import get_object_or_404 def unsubscribe(request): if request.method == 'POST': form = UnsubscribeForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] user = get_object_or_404(Subscriber,email=email) user.delete(id=user.id) messages.success(request, 'Unsubscribed') return HttpResponseRedirect('/newsletter/subscribe/') else: messages.error(request, form.errors) return render(request, 'unsubscribe.html', {'form': form}) else: form = UnsubscribeForm() return render(request, 'unsubscribe.html', {'form': form}) My forms: from django.forms import ModelForm, EmailField from .models import Subscriber class SubscribeForm(ModelForm): email = EmailField() class Meta: model = Subscriber fields = ('email',) class UnsubscribeForm(ModelForm): email = EmailField() class Meta: model = Subscriber fields = ('email',) My Model: from django.db import models # Create your models here. class Subscriber(models.Model): email = models.EmailField(max_length=75, unique=True) def __str__(self): return self.email -
redirect to profile after creating a user which auto create a profile
Apologize for being annoying,I'm a beginner programmer and working on my new project. I've made this model which create a profile when a user is created: class ExpertSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_expert = True user.save() expert = Expert.objects.create(expert=user) return user and this is the view. So what i am trying to do here is to sign a user then set his premission as a expert and then log him in which i've already done but what I'm not able to do is to redirect him into his expert details/update profile right after logging in . so if you can help me with that. Thank you in advance. Here are the views: class ExpertSignUpView(CreateView): model = User form_class = ExpertSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'expert' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('/') <<------- the urls might help urlpatterns = [ path('',ExpertListView.as_view(), name='list'), path('Esignup/',ExpertSignUpView.as_view(), name='expert_signup'), path('Ssignup/',StudentSignUpView.as_view(), name='student_signup'), path('create/',ExpertCreateView.as_view(), name='create'), path('<str:pk>/',ExpertDetailView.as_view(), name='detail'), path('<str:pk>/update/',ExpertUpdateView.as_view(), name='update'), path('<str:pk>/delete/',ExpertDeleteView.as_view(), name='delete'), ] -
File upload doesn't work when giving the absolute path when using a a text box to upload python Django
I have a web application with Python, Django framework that allows uploading a file. the uploaded file path is shown in a textbox. When I browse and select a file it is shown as c:\fakepath\Sample.docx in the textbox and I click the upload button, Then the file upload happens hasslefree. But if I provide the absolute path in the textbox as C:\xxx\xxx\xxx\sample.docx and click the upload button, the file doesn't upload. Html code to create the upload in a textbox input id="txt" type = "text" value = "Choose File" size="40" align="center" onclick ="javascript:document.getElementById('file').click();"> python code when I try to extract the file uploaded file = request.FILES['file1'] error while giving the absolute path: raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'file1' -
Django: export csv file with django_table2
I want to have an download button a html page that renders a django table. I followed the documentation of django2 and this post How to export .csv with Django-Tables2? was helpful but could not make the trick. I feel like I have done everything correctly (according to my beginner skills), there is no error but the download button is not there. I was wondering if someone has any help to provide on this one table.py class AnormalTable(tables.Table): class Meta: model = stock_anormal template_name = "django_tables2/bootstrap4.html" export_formats = ['csv', 'xlsx'] view.py @method_decorator(login_required, name='dispatch') class PostDetailalerte_negat(LoginRequiredMixin,APIView, tables.SingleTableMixin, ExportMixin): def get(self, request): queryset = stock_negatif.objects.all() table = NegatTable(queryset) RequestConfig(request).configure(table) export_format = request.GET.get("_export", None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, table) return exporter.response("table.{}".format(export_format)) return render(request, 'detailstocknegat.html', {'table':table}) html snipet <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h1 class="h3 mb-0 text-gray-800">ITEMS IN ALERTE SAFETY STOCK LEVEL</h1> <div> {% for format in view.export_formart %} <a href="{% export_url "csv" %}" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i class="fas fa-download fa-sm text-white-50"></i> Generate Report</a> {% endfor %} </div> </div> <table> {% load django_tables2 %} {% render_table table %} </table> -
How to implement Django's Multiple Store Inventory tracking system
I need some opinion on what’s the best way to design a solution abound customized inventory tracking system which works on regional based stores. I have gone through lot of documents but nothing seems to be working for me. So I need some opinion from expert. Here is my use case: I am creating a inventory tracking system for a client with multiple Physical stores which are defined in different regions. Each store has multiple department so I have following models: class Location(models.Model): LocId = models.AutoField(primary_key=True) Name = models.CharField(max_length=100) ShortName = models.CharField (max_length=25) Address = models.TextField(null=True) IsPhysicalLoc = models.BooleanField(default=False) class LocationParent(models.Model): LocParentId = models.AutoField(primary_key=True) LocId = models.ForeignKey(Location, on_delete=models.CASCADE, db_column="LocId") ParentId = models.ForeignKey(Location, on_delete=models.CASCADE, db_column="LocId") Location model holds all location information. This is common model which stores information about physical location as well as region based location. Example: Region = West Coast, and store is in Hollywood. Then it will have two entries: For Region it will define as: Name= WestCoast Region, ShortName: West Coast, Address: Empty, IsPhysicalLoc=False (assuming LocId=1) For Physical store: Name=1 Hollywood; Short Name=1 Hollywood; Address: ; IsPhysicalLoc=True. (assuming LocId = 3) LocationParent table will hold the parent child relationship between Parent and Child Store, So in above … -
Django Rest Framework Response
I'm studying Django Rest Framework. I understand what is Django content negotiation, and the use of the Response function. In an example I've seen a code like: def func(request): if request.method == "GET": queryset_objects = // serializer = FooSerializer(queryset_objects, many = True) return Response(serializer.data) This function will render a JSON. But the only parameter passed to Response is a dictionary like type (serializer.data). How Render decide that the response must be a JSONN instead another type (without header)? -
images not showing in detail view
posted images are not showing in the detail view of my blog website. on the other hand, they show only when i add them through the admin page. i have older posts whose detail views can show but ever seens this problem started, the detail view do no longer open.it shows this error "The 'blog_Main_Img' attribute has no file associated with it" MY MODELS from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # a class for text to be posted class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField(blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, related_name='blog_author',on_delete=models.CASCADE) blog_Main_Img = models.ImageField(upload_to='images/', verbose_name='Image',blank=True,default='') # this allow the method to be called as a string def __str__(self): return self.title def get_absolute_url(self): return reverse('blog-home') @property def image_url(self): if self.image and hasattr(self.image, 'url'): return self.image.url def __str__(self): return self.name def get_absolute_url(self): return reverse('blog-home') MY VIEWS from django.shortcuts import render,get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from .models import Post def home(request): context ={ 'posts': Post.objects.all() } return render(request, 'blog/home.html', context) class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = '-date_posted' paginate_by = … -
Django file upload as different user
I have a Django application running on an mod_wsgi (embedded mode) Apache instance inside a Docker container. This container shares a volume (media/) with the host. When a user uploads a file, it is stored in the media/<file> directory. The issue is that the file owner and group are both root, and I need write access to these for a particular user (tech) and/or group (tech-group). I'm assuming it is happening because python is running as root in the container(?). Is there a way to instead have it run as tech? Or somehow tell Django to write files as a particular user/group? -
get specific data with click event Django
I have a simple template where a user can compose a team from displayed names. I can't find out how could I get the names selected by the user to use it in view.py when the user click on "Add to the team" and remove the name when user click on "remove from the team" My html code is basic, on the left side of the page I have: <div class="card-body" id="team-list"> <p class="card-text">Select today's teammates:</p> <ul class="list-group list-group-flush"> {% for tech in techs %} <li class="list-group-item"> <span class="name" name="{{tech.id}}">{{tech.name}}</span> <span class="move" style="float: right;" id={{tech.id}}>Add to the team</span> </li> {% endfor %} </ul> </div><!--CLOSE CARD BODY--> and on the right side I have : <div class="card-body" id="selected-list"> <h3 class="title">You have selected the following teammates for today: </h3> <ul class="list-group list-group-flush" style="list-style-type: none;"> </ul> </div In my JS file, I handled the event like that: var selected = document.querySelector('#selected-list ul'); var team = document.querySelector('#team-list ul'); function clickHandlerTeam(e){ if(e.target.classList.contains('move')){ if (e.target.textContent == 'Add to the team'){ console.log('changing add'); e.target.textContent ='Remove from the team'; selected.appendChild(e.target.parentNode); } else { console.log('changing remove'); e.target.textContent = 'Add to the team'; team.appendChild(e.target.parentNode); } } return; } Finally, in views.py I pass the context like that: @login_required def mywork(request): … -
Cumulative sum SQL query for calculate sales contribution with Postgres
Based on this table I need to calculate how much each products contributes to the total sales and be able to filter the for these products that constitute the 80% of contribution | prod_id | sales date | units_sold | total_price | |---------+------------+------------+-------------| | 1 | 2020-04-20 | 10 | 100.00 | | 1 | 2020-04-19 | 2 | 20.00 | | 2 | 2020-04-20 | 5 | 15.00 | | 2 | 2020-04-19 | 5 | 15.00 | | 3 | 2020-04-20 | 25 | 25.00 | | 3 | 2020-04-19 | 25 | 25.00 | considering the total Sales is equal to $200 the resulting table should looks similar to the one below | prod_id | units_sold | total_price | Contribution % | Accumulate Contribution % | |---------+------------+-------------+----------------+---------------------------| | 1 | 12 | 120 | 0.6 | 1.0 | | 3 | 50 | 50 | 0.25 | 0.4 | | 2 | 10 | 30 | 0.15 | 0.15 | -
How can I create multiple objects with one view?
I am creating a dating app and am attempting to create a message form that displays once a user has matched with another user. I already have the matching down and the users displaying correctly, but I need this messaging component. Now, my InstantMessage model has a foreign key to Conversation which should contain 2 members, whom are having a conversation and contains at least one message exchanged between each other . I'm sure there's a clearer way to do this, but I'd rather keep my models as they are. Now, I what I want to do, when a user hits a link to start messaging, to have my code check if there is already a conversation object between the two users, and if so, then use that conversation object pk for my conversation field in Instant Message and then create a form for that. And if there isn't, then I want a conversation object to be created first, and then a message object to be created. I want this all in one view and with one link, so I assume I need to use if/else statements. Now, this is just a simple project I'm creating to show employers, so … -
Django views, models and urls
I'm setting up a few different views in django. I'd like to return info for each object such as 127.0.0.1:8000/courses/1/1 for instance however 127.0.0.1:8000/courses and 127.0.0.1:8000/courses/1 and 127.0.0.1:8000/courses/1/1 all currently return the same value which right now for example would be a book title and author. from .models import Course from django.conf.urls import url from . import views urlpatterns = [ url('', views.course_list, name='course_list'), url('<int:course_pk>/<int:step_pk>/', views.step_detail, name='step_detail_with_pk'), url('<int:pk>/', views.course_detail, name='course_detail_with_pk'), ] -
How to add Datepicker input using Django Model?
I'm using bootstrap to create a TV show template and here's my HTML code: <div class="container"> <h1>Add a New Show</h1> <form action="/"> <div class="form-group" method="POST"> <label for="title">Title</label> <input type="text" name="title" class="form-control" id="input-title"> </div> <div class="form-group"> <label for="network">Network</label> <input type="text" name="network" class="form-control" id="input-network"> <label for="releasedate">Release Date</label> <div class="input-group date" id="datetimepicker4" data-target-input="nearest"> <input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker4" /> <div class="input-group-append" data-target="#datetimepicker4" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> </div> <div class="form-group"> <label for="description">Description</label> <textarea name="description" class="form-control" id="input-description" rows="8"></textarea> </div> <div class="form-group text-center"> <button type="submit" class="btn btn-primary shadow" id="createbtn">Create</button> </div> </form> </div> </div> and here's my models.py for django: from django.db import models Create your models here. class Show(models.Model): title = models.CharField(max_length=255) network = models.CharField(max_length=255) release_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) So how can I create a datepicker in template using django but no jquery or javascript? -
Retrieve related field in Djando Rest Framework
I have the following models that represent Article, Author and Company (where author works): class Article(models.Model): article_title = models.CharField(max_length=250) article_url = models.URLField(max_length=250) article_pub_date = models.DateField() class Company(models.Model): company_name = models.CharField(max_length=250) class Author(models.Model): author_sf_id = models.CharField(max_length=20, unique=True) author_name = models.CharField(max_length=250) article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='author_crtcicle') company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='author_company') My Serializers: class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('__all__') depth = 2 class CompanySerializer(serializers.ModelSerializer): class Meta: model= Company fields = ('__all__') class AuthorSerializer(serializers.ModelSerializer): article = ArticleSerializer() class Meta: model = Author fields = ('__all__')` My Views: class ArticleList(ListAPIView): queryset = Article.objects.all().order_by('-article_pub_date') serializer_class = ArticleSerializer class AuthorList(ListAPIView): queryset = Author.objects.all().order_by('author_name') serializer_class = AuthorSerializer class CompanyList(ListAPIView): queryset = Company.objects.all().order_by('company_name') serializer_class = CompanySerializer In DRF, I want to retrieve all articles of an Author and his Company members' with an url that would take an article_url e.g: /api/v1/{article_url}. I have tried various combination but what I have only succeeded doing so far is just retrieving all articles from an author. An idea I thought of is overriding the get_object method of the ListAPIView in a way that would help retrieve these fields. Does anyone have an idea? -
dependencies reference nonexistent parent node error after deleting app
I got this error after deleting a users app in my project whenever I try to migrate or run my app. I have tried the solutions from Django: dependencies reference nonexistent parent node but none worked. My migration files were all empty, i have tried deleting the pyc files, pycache, and deleting the migration files themselves but it still won't work. here is the error I get: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\clayh\.virtualenvs\VoterInfoApp-z_tPDrnw\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\clayh\.virtualenvs\VoterInfoApp-z_tPDrnw\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\clayh\.virtualenvs\VoterInfoApp-z_tPDrnw\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\clayh\.virtualenvs\VoterInfoApp-z_tPDrnw\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\clayh\.virtualenvs\VoterInfoApp-z_tPDrnw\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\clayh\.virtualenvs\VoterInfoApp-z_tPDrnw\lib\site-packages\django\core\management\commands\makemigrations.py", line 87, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "C:\Users\clayh\.virtualenvs\VoterInfoApp-z_tPDrnw\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\clayh\.virtualenvs\VoterInfoApp-z_tPDrnw\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph raise exc File "C:\Users\clayh\.virtualenvs\VoterInfoApp-z_tPDrnw\lib\site-packages\django\db\migrations\loader.py", line 248, in build_graph self.graph.validate_consistency() File "C:\Users\clayh\.virtualenvs\VoterInfoApp-z_tPDrnw\lib\site-packages\django\db\migrations\graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\clayh\.virtualenvs\VoterInfoApp-z_tPDrnw\lib\site-packages\django\db\migrations\graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\clayh\.virtualenvs\VoterInfoApp-z_tPDrnw\lib\site-packages\django\db\migrations\graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration … -
Why global variable inside for loop doesn't change value? Javascript
I have a problem when executing a function that runs a for loop with 3 global variables that will be passed to a callback function. All the arrays have the same length, the problem comes with the 3 window variables, called in getPickup() inside the callback function don't change value in any of the loop goes. I find it strange because those variables should get a new value updated from location when the callback function is finished, and the loop is run again. function calculateDistanceDriverCustomer() { {% autoescape off %} var locations = {{ locations }} {% endautoescape %} {% autoescape off %} var firstname = {{ firstname }} {% endautoescape %} {% autoescape off %} var lastname = {{ lastname }} {% endautoescape %} {% autoescape off %} var rating = {{ rating }} {% endautoescape %} var location; for (location = 0; location < locations.length; location++) { var origin = locations[location]; window.firstname = firstname[location]; window.lastname = lastname[location]; window.rating = rating[location]; var destination = $('#origin-input').val(); var service = new google.maps.DistanceMatrixService(); service.getDistanceMatrix( { origins: [origin], destinations: [destination], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.METRIC, // kilometers and meters. avoidHighways: false, avoidTolls: false }, callback); } }; function callback(response, status) { if (status != … -
Python/Django button to redirect user depending on the actual site
I've searched for the best idea to clearly implement a button that redirects a user to the post creation page depending on the current URL but I still don't have a good solution. I have 1 same template for 3 pages. Each page has 10 categories (subpages). Maybe example: urls.py: app_name = 'forum' 1 category path('category1/, View.as_view(), name = category1 2 category path('category2/, View.as_view(), name = category2 1 category post creation path('category1/create-post/', PostCreateView.as_view(my_id=11), name = category1-new-post 2 category post creation path('category2/create-post/', PostCreateView.as_view(my_id=12), name = category2-new-post If the user is on the first subpage/category and clicks the button then redirect him to {% url 'forum:category1-new-post' %} If the user is on the second subpage/category and clicks the button then redirect him to {% url 'forum:category2-new-post' %} and etc 28x times (3 pages x 10 categories) I've tried to write something like this: {% if request.resolver_match.url_name == 'category1' %} button with href '{% url 'forum:category1-new-post' %}' {% elif request.resolver_match.url_name == 'category2' %} button with href '{% url 'forum:category2-new-post' %}' and etc 28x times. The code above doesn't seem good. Writing 30 ifs is not the best idea and i don't know how to handle it. For each subpage/category post creation i have … -
NoReverseMatch at /main/insert_num/ Django
I'm trying to make to make a django web app which has a form that asks a user to input a phone number and stores that number in a postgres database. The following code is giving me the error: NoReverseMatch at /main/insert_num/ Reverse for '' not found. '' is not a valid view function or pattern name. And I can't figure out what the issue is, can someone help? index.html <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Test Form 1</title> </head> <body> <form action="{% url 'insert_my_num' %}" method="post" autocomplete="off"> {% csrf_token %} <!-- {{ form.as_p }} --> <input type="submit" value="Send message"> </form> </body> </html> forms.py from django import forms from phone_field import PhoneField from main.models import Post class HomeForm(forms.ModelForm): phone = PhoneField() class Meta: model = Post fields = ('phone',) models.py from django.db import models from phone_field import PhoneField class Post(models.Model): phone = PhoneField() main/urls.py from django.urls import path from . import views urlpatterns = [ path('insert_num/', views.insert_my_num,name='insert_my_num') ] project/urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('main/',include('main.urls')) ] views.py def insert_my_num(request: HttpRequest): phone = Post(request.POST.get('phone')) phone.save() return redirect('') -
why does Django returns BadHeaderError when adding a new line in my 'Contact' page's 'message' field
Everything works except when I add a new line via 'enter' in the "Message" field. It goes through if I don't add new lines in the message textfield. What am i missing here? Tried to solve this problem for 2 days, nothing similar on google. I feel like there could be the problem of my views.py config: def success(request): return render(request, 'home/success.html') def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # send email code goes here sender_name = form.cleaned_data['name'] sender_email = form.cleaned_data['email'] sender_phone = form.cleaned_data['phone'] sender_message = form.cleaned_data['message'] subject = "Enquiry: {0}".format(sender_message[:50]) message = "New message from {0}\n phone number: {1}\n email: {2}\n\n{3}".format(sender_name, sender_phone, sender_email, sender_message) recipients = ['john.smith@gmail.com'] sender = "{0}<{1}>".format(sender_name, sender_email) try: send_mail(subject, message, sender, recipients, fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found') return HttpResponseRedirect('success') else: form = ContactForm() return render(request, 'home/contact.html', {'form': form}) Any ideas? -
Data not passing to django template on DetailView
I have a model that should show data on the home page but isn't. I think the problem has to do with fetching data from an external API that also shows on the home page. `models.py` class Stats(models.Model): confirmed = models.CharField(max_length=20) recovered = models.CharField(max_length=20) death = models.CharField(max_length=20) def __str__(self): return str(self.confirmed) `views.py` import services # API comes from services.py class IndexData(DetailView): template_name = 'pages/home.html' stats = Stats.objects.all() def get(self, request): article_data = services.get_data() return render(request, 'pages/home.html', article_data) home.html {% for s in stats %} {{ s.recovered }} {{ s.deaths }} {{ s.confirmed }} {% endfor %} It should show: But is showing: -
"django_site" does not exist on migration
Earlier today I was having some problems with conflicting migrations for various reasons. I decided to just destroy the entire DB and start from scratch (we're pretty early in the project there is no harm in resetting everything). However, when I tried to get things back up and running with manage.py migrate I get this error: File "/Users/travis/Documents/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): ... return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... ^ This seems to be a very common error and the main solutions I have seen (and tried) are: add SITE_ID = 1 to base.py; in my case, it's already in there. Include "django.contrib.sites" earlier in DJANGO_APPS I've tried putting it first and got the same error. run manage.py migrate sites before other migrations; running this migration gives me the same error. Additionally, I have completely removed the DB, and created a new PGSQL instance, I've removed the project locally and cloned it from our repo. I've tried creating new … -
Record IP Address with Form Submission Django
I am trying to use the django-ipware pacakge to record the IP address of someone submitting a form submission via Django. The form is a ModelForm. Here's the model: # models.py from django.db import models class Upload(models.Model): email = models.EmailField() title = models.CharField(max_length=100) language = models.ForeignKey('about.channel', on_delete=models.CASCADE, default='Other') date = models.DateField(auto_now_add=True) file = models.FileField() ip_address = models.GenericIPAddressField() Here is the form: # forms.py class UploadForm(forms.ModelForm): class Meta: model = Upload fields = ['email', 'title', 'language', 'file'] labels = { 'email': 'E-Mail', 'title': 'Video Title', 'file': 'Attach File' } The business logic for getting the IP address is pretty simple, but I've tried placing it in different locations with no luck. Where should I place the logic so it will be submitted along with the other form data? # views.py from ipware.ip import get_real_ip ip = get_real_ip(request) -
django calendar make first day sunday
Currently my calendar is formatted with Monday being the first day of the week. What I would like is for the first day to be Sunday. I used this to start out: https://medium.com/@unionproject88/django-and-python-calendar-e647a8eccff6 I messed around and began looking at the Documentation but not matter what I added it wouldn't work. utils.py class Calendar(calendar.HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super().__init__() # formats a day as a td # filter events by day def formatday(self, day, events, year, month): events_per_day = events.filter(start_date__day=day).order_by("start_date") d = "" for event in events_per_day: d += f"<a class='calendar-event' href='{reverse('events:detail', args={event.uid})}'>{event.title}</a> <a class='calendar-event-mobile' href='{reverse('events:detail', args={event.uid})}'><i class='fas fa-dot-circle'></i></a>" if day != 0: scope = datetime.date(year, month, day) if scope == datetime.date.today(): return f"<td class='date-today'><span class='date'>{day}</span><div> {d} </div></td>" return f"<td><span class='date'>{day}</span><div> {d} </div></td>" return "<td></td>" # formats a week as a tr def formatweek(self, theweek, events, year, month): week = "" for d, weekday in theweek: week += self.formatday(d, events, year, month) return f"<tr> {week} </tr>" # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = Event.objects.filter(start_date__year=self.year, start_date__month=self.month) cal = ( f'<table border="0" cellpadding="0" cellspacing="0" class="table table-striped table-bordered calendar">\n' ) cal += f"{self.formatmonthname(self.year, self.month, withyear=withyear)}\n" … -
Most efficient database design (models) for tracking daily object rankings in huge database
I am designing a Django project that needs to be able to track 1 million+ products and produce daily rankings for which product had the most total number of sales. I need to store and reference this historical ranking data and be able to retrieve rankings for any day in the past. Therefore, my models.py looks like: class Product(models.Model): product_name = models.CharField(max_length=200, unique=True) updated_at = models.DateTimeField(auto_now=True) sub_description = models.CharField(max_length=500, default='') class Rank(models.Model): class Meta(object): unique_together = ['pub_date', 'product'] pub_date = models.DateField(db_index=True) product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) total_sold = models.IntegerField() My plan is to run a django management command script each day. The script will create a new Rank object for each Product in the database every day. Here is a simplified version of the script logic: now = datetime.datetime.utcnow().replace(tzinfo=utc) for prod in Product.objects.all(): try: rank = Rank.objects.get(product=prod, pub_date=now) print("Already updated for ", str(now)) except Rank.DoesNotExist: rank_value = prod_api.get(prod) rank = Rank(product=prod, pub_date=now) rank.total_sold = rank_value rank.save() Because it is possible for a user to request daily rankings while the management command is only halfway through adding new Rank objects for today, the following annotates were a bit tricky for me. I am returning the most recently updated Rank object for each …