Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying Django page views in my detail page
I want to display the number of times a page have been viewed in my details page. I also want to increment the pageview by 1 anytime the page is anytime the page is loaded. I have a code that does but it also updates my DateTime attribute. How can I achieve this without having to alter everything? models.py class Music(models.Model): artist = models.CharField(max_length=300) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(default='', blank=True, unique=True) thumbnail = models.ImageField(blank=False) audio_file = models.FileField(default='') uploaded_date = models.DateTimeField(default=timezone.now) description = RichTextUploadingField() views = models.IntegerField(default=0) class Meta: ordering = ['-uploaded_date'] def save(self): self.uploaded_date = timezone.now() self.slug = slugify(self.title) super(Music, self).save() def __str__(self): return self.title + ' by ' + self.artist def get_absolute_url(self): return reverse('music:detail', kwargs={'slug': self.slug}) views.py def detail(request, slug): latest_posts = Music.objects.order_by('-uploaded_date')[:5] song = get_object_or_404(Music, slug=slug) song.views = song.views + 1 song.save() -
Django FTP client Name Error: name TEST_HOST not defined
so i tried to use this (https://github.com/author135135/django-ftp-client) django app in my project. Everything is fine, but when i tried to connect to my remote ftp server, i get this error on my terminal. manager.add_connection(TEST_HOST, TEST_USER, TEST_PASSWD) NameError: name 'TEST_HOST' is not defined nothing seems to be mentioned on the github readme file, so seems like i am doing it wrong. where am i wrong? -
virtualenv can't create env in project
I'd like to create virtual environment in my distribution project on Catalina OS Mac. I receive this feedback from terminal: user@MBP-zen distribution % virtualenv env Traceback (most recent call last): File "/usr/local/bin/virtualenv", line 6, in <module> from pkg_resources import load_entry_point File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3241, in <module> @_call_aside File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3225, in _call_aside f(*args, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3254, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 585, in _build_master return cls._build_from_requirements(__requires__) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 598, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 786, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'zipp>=0.4' distribution was not found and is required by importlib-resource user@MBP-zen ~ % which virtualenv /usr/local/bin/virtualenv this is my python installed: user@MBP-zen ~ % python Python 3.7.7 (default, Mar 10 2020, 15:43:33) [Clang 11.0.0 (clang-1100.0.33.17)] on darwin Type "help", "copyright", "credits" or "license" for more information. I tested many answers given here as well as over internet but no success as for now. Any ideas why is this happening? -
CORS issue with react and django-rest-framework
I'm using react on the frontend side and Django on the backend. I using django-cors-headers for managing CORS in my Django app. I have added the package in INSTALLED_APPS like this:- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework.authtoken', 'rest_framework', 'corsheaders', 'services', 'feeds', 'knox', 'users', ] then I have also added same in MIDDLEWARE MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['*'] and I'm passing CORS headers from my client-side React app like:- const Axios = axios.create({ baseURL: `${BASE_URL}/api`, timeout: 1000, headers: { 'X-Custom-Header': 'foobar', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }) -
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: DLL load failed while importing _psycopg: module could not be found
I have installed psycop2 on my virtualenv. Then after running python manage.py makemigrations command in my pycharm terminal got this error: (venv) C:\Users\ADMIN\PycharmProjects\django_pro_postgres\django_project>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 25, in <module> import psycopg2 as Database File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\psycopg2\__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: The specified module could not be found. During handling of the above exception, another exception occurred: 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\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\ADMIN\PycharmProjects\django_pro_postgres\venv\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> … -
Having a problem redirecting with the correct pk value in django
So, I am having trouble redirecting using other_user pk. I can't figure out to pass that pk in. I am either passing request.user pk, or I am getting a 'local variable 'other_user' referenced before assignment' error. I can pass other_user into my template, but , I don't how to combine the href link WITH the button to submit the form. I wonder if that's even possible? I did try doing it via the redirect method with other_user.id, but I can't. So, basically I am getting the other_user when I query for it, but I don't know how to pass it to my redirect so it take my user where it needs to go. How would I go about solving this problem? views.py/message def message (request, profile_id): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): form.save() return redirect('dating_app:messages') else: conversation, created = Conversation.objects.filter(members = request.user).filter(members= profile_id).get_or_create() other_user = conversation.members.filter(id=profile_id).get() form = MessageForm({'sender': request.user, 'conversation': conversation}) context = {'form' : form, 'other_user': other_user } return render(request, 'dating_app/message.html', context) message.html <form method="post" action="{% url 'dating_app:message' user.id %}" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button name="submit">login</button> {% endbuttons %} <a href="{% url 'dating_app:messages' other_user.id %}">Start messaging </a> <input … -
Guessing Game where players have to correctly guess the name of a specific NBA player given their image (Python)
I would like to create a game for my friends where we are given a random NBA player's head shot and we would have to guess his name correctly. I want to be able to display a wide range of players, including mainstream players and even obscure players. Each correct guess would score more points and whoever has the most points wins the game. I plan on using this website to get all the head shots that I need: (https://sportradar.us/2018/10/nba-headshots-now-available/). I am a beginner in Python and would like some ideas on where to even start. What frameworks should I use? I have dabbled in Django and could imagine creating a web app for this game. I've tried looking up similar tutorials but mostly I've only found basic number guessing games. I don't need a complete solution, maybe just some ideas on where to start so I can figure out the rest. Any advice or resource is appreciated! -
Add new line (and bullet points) in Django forms response label text?
I have a form: class FormFood(forms.Form): CHOICES = [ (1,'Yes'), (2, 'No')] response = forms.ChoiceField(widget=forms.RadioSelect, label="Would you like some pasta, bread or rice?", choices=CHOICES) It appears like this in my browser: The problem I would like 'pasta', 'bread' and 'rice' to appear on different lines with bullet points like this: Would you like: Pasta Bread Rice What I've tried Adding \n in the label text and skipping a line using 'enter'. Neither have worked. Could somebody point me in the right direction as to how best to do this? -
What is the proper syntax to import view in urls.py in django3?
What is the proper syntax to import view.py into urls.py I am trying to add pagination and search and have run into a SyntaxError "SyntaxError: invalid syntax" . I tried my best to debug it the last few days. I can see it is the way I am importing view. I tried a bunch of combinations and made it worse any guidance extremely appreciated. File "C:\Users\taylo\Desktop\pybox\blogdemo\blog\urls.py", line 3 blogdemo/blog/urls.py from django.urls import path from . import views from .views index, single, SearchResultsListView urlpatterns = [ path('', views.index, name='index'), path('<int:id>/', views.single, name='single'), path('search/', SearchResultSingleView.as_view(), name='search_results'), #added ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) blogdemo/blogdemo/URLS.PY from .views index, single, SearchResultsListView from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include # imported include module urlpatterns = [ path('', include('blog.urls')), #added path('admin/', admin.site.urls), path('search/', SearchResultListView.as_view(), name='search_results'), #added ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) blogdemo/VIEWS.PY from django.core.paginator import Paginator from django.shortcuts import render from .models import Article def index(request): articles = Article.objects.all() paginator = Paginator(articles,3) page = request.GET.get('page') posts = paginator.get_page(page) return render(request, 'index.html', {'posts': posts}) def single(request, id): single = Article.objects.get(id=id) nextpost = Article.objects.filter(id_gt=single.id).order_by('id').first() prevpost = Article.objects.filter(id_lt=single.id).order_by('id').last() return render(request, 'single.html', {"single": single, "prevpost": prevpost, "nextpost": nextpost}) class SearchResultsListView(SingleView): model = Article … -
Django - What is the best approach to handle multiple user types...and route the HTML pages based on this?
I'm making a small test project with below user types: School Admin, Teacher, Student, Parent. And each user type will have different Permissions like School Admin has full access... Parents can only view their Childern's Activity. Teacher can see all students but can add / edit marks for their respective students only. Teachers can setup Exam etc.. Students can take exam and submit the exam, but cannot edit / add any other information. Just can edit his profile detail. Approach 1: Do i need to create a Custom User calss and apply to each user type (ie one Custome Class.. and 4 user type calss).. and similarly have 4 different view and html pages? Approach 2: Just have one custome class and have an field with UserType which will have the have as "SchoolAdmin", "Teacher", "Student","Parent".. and one view and html (as the data page would remain same and only data record will restrict), and somehow identify the User Type in View, and filter the record? Definately some view or html pages will be specific to one user type only which is i am able to handle, the issue is to use same view / html page to handle all … -
Django: validation of restricted Foreign keys forms in Mixins Class views
Context: how I handled foreign keys restrictions on GET I have some trouble validating this form: class RecordConsultationForm(forms.ModelForm): class Meta: model = Consultation fields = ["fk_type", "fk_client", "duration", "date"] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(RecordConsultationForm, self).__init__(*args, **kwargs) self.fields['fk_client'].queryset = Client.objects.filter(fk_owner=self.user) # <=====HERE The queryset restricts the available clients to users. Pretty effective, I just had to add the following to get_context_data(): @method_decorator(login_required, name='dispatch') class BrowseConsultations(BrowseAndCreate): template_name = "console/browse_consultations.html" model = Consultation form_class = RecordConsultationForm success_url = 'browse_consultations' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.form_class(user = self.request.user) #<=====HERE return context Form validation on BrowseConsultations Despite what I added in get_context_data(), form data on POST does not seem valid, as if user were None (so it seems): Invalid fk_client: Select a valid choice. 2 is not one of the available choices. Maybe get_context_data() was not the proper place to set the user? Is there a way I could tweak the form in post()? Is it the proper way to do it? Additional details BrowseAndCreate BrowseConsultations inherits from is a Mixing class I created to handle common ordering tasks and messages. Here is a portion of it: @method_decorator(login_required, name='dispatch') class BrowseAndCreate(CreateView, TemplateView): """display a bunch of items from … -
Multiply two fields together in django database
I am new to Django and i have been trying to do this for sometime now. models.py class Majitele(models.Model): cena_p = models.DecimalField(decimal_places=2, max_digits=10, null=True) cena_l = models.DecimalField(decimal_places=2, max_digits=10, null=True) lv = models.IntegerField(null=True) katastr = models.CharField(max_length=40, null=True) jmeno = models.CharField(max_length=40, null=True) ulice = models.CharField(max_length=30, null=True) mesto = models.CharField(max_length=30, null=True) psc = models.IntegerField(null=True) v_pole = models.DecimalField(decimal_places=4, max_digits=10, null=True) v_les = models.DecimalField(decimal_places=4, max_digits=10, null=True) v_celkem = models.DecimalField(decimal_places=4, max_digits=10, null=True) cena_pole = models.DecimalField(decimal_places=4, max_digits=10, null=True) cena_les = models.DecimalField(decimal_places=4, max_digits=10, null=True) cena_rok = models.DecimalField(decimal_places=4, max_digits=10, null=True) nevyplaceno = models.IntegerField(null=True) podil = models.CharField(max_length=5, null=True) hlasu = models.IntegerField(null=True) poznamka = models.CharField(max_length=200, null=True) prezence = models.BooleanField(null=True) vyplatni = models.BooleanField(null=True) postou = models.BooleanField(null=True) osobne = models.BooleanField(null=True) def __str__(self): return '%s'%(self.jmeno) Here is what would i like to do: Take v_pole value then cena_p value and multiply them together and the result should then be saved in the cena_pole field. I tried this: Majitele.objects.all().annotate(vypocet_c=F('cena_p') * F('v_pole')).update(cena_pole=vypocet_c) Is there even a way how to do it? Thanks for any advice. -
Get Item from Django Annotated Queryset With Dynamic Database Functions
I'm encountering something unexpected, and I'm sure it must be a simple solution. I'm trying to use the CUME_DIST() function to annotate a django SQL query. This part is working fine and giving me a proper output. The challenge I'm having is, when I try to fetch a specific item from the annotated queryset using .get(user=request.user) it will give me back the correct item, but the annotated column seems to be re-evaluated. I want to get the item with the same annotated value as in the original query. Note that I can access this correctly with index notation (ex: annotated_queryset[10] gives the correct output for item at index 10), but I'm not sure at which index the desired item will be. Example of my code: annotated_queryset = Profile.objects.annotate(score_cume=RawSQL(""" CUME_DIST() OVER ( ORDER BY score ) """, ())) Above gives me the correct queryset. user_profile = annotated_queryset.get(user=request.user) print("score cum : ", user_profile.score_cume) Printing out the above always gives 1.0 because (I believe) it's evaluating the score_cume filed against the one object it's retrieving. How can I retrieve this object by request.user from the original annotated queryset and keep the annotated value? FWIW: I'm using postgres with django -
at=error code=H10 desc="App crashed" heroku retuning this error
at=error code=H10 desc="App crashed" heroku retuning this error Django Changed Procfile with all previous stack solution but still its same. web: gunicorn projectname.wsgi --log-file - web: gunicorn django_project.wsgi:application --log-file - --log-level debug python manage.py collectstatic --noinput manage.py migrate both format i used -
Exclude and filter graphene django query set
Hi i'm trying to add a filter and exclude to my query set but don't know how. I can filter and exclude separately but cant do it simultaneously. This is my resolver def resolve_articles(self, info, limit=None, offset=None, slug=None, search=None, exclude=None, braking=None, non_braking=None): if search: filter = ( Q(id__icontains=search) | Q(title__icontains=search) | Q(categories__name__icontains=search) ) return BlogPage.objects.filter(filter).order_by('-first_published_at')[offset:limit] How can i do this def resolve_articles(self, info, limit=None, offset=None, slug=None, search=None, exclude=None, braking=None, non_braking=None): if search and exclude: filter = ( Q(id__icontains=search) and Q(categories__name__icontains=exclude) ) return BlogPage.objects.filter(filter).exclude(filter).order_by('-first_published_at')[offset:limit] Thank you -
How to Send Emails to Subscribed Users in Django or How to send News Letters in Django
I am trying how can I send mass mails to the Subscribed Users. I have the E-mails of the User and want them to send News Letters or anything else. But, I am unable to do these. So Help me by the Explanation and providing CODE. Thanks in Advance !!! -
Retrieve data from external API and display in django admin
Rather than querying a local database I would like to use an external API to retrieve the data to display in the django admin. For simplicities sake I have a model, and plan to retrieve a list of names from the API: class Person(models.Model): first_name = models.CharField() last_name = models.CharField() class Meta: managed = False As it is not managed it therefore does not create the person table. What is the order of functions I must override in ModelAdmin to Perform the API call instead of the database lookup Output the data to a default table in the admin (with first name and last name) Disable functions such as to add (as this will just be a lookup table) Use the django admin search to query the external api - ie. perform a new request and display the new data. -
Problems with uploading large files in django
I have project with courses. Course contains videos that usually bigger that 100mb. But when i am trying to upload this file, it instantly redirects without any loading, and when i am opening the admin i can see the name of this video, but when i am trying to open, i am redirecting to the page with player that doesn't showing video. How i can upload large files? models.py class SectionVideos(models.Model): title = models.CharField(max_length=50,null=True) video = models.FileField(upload_to='courses/course_videos',max_length=100) section = models.ForeignKey(CourseSections,on_delete=models.CASCADE,null=True) preview_image = models.ImageField(upload_to='courses/course_videos_preview_images',null=True) short_description = models.CharField(max_length=50,null=True) -
Searching by category in Django and not by product
I have created a search bar which searches based on product name. I would now like to change this to search by category but I am finding it difficult. Here is my URLs file: ''' from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.marketplaceHome, name='marketplace-home'), url(r'^search/$', views.search, name='search'), url(r'^contact/$', views.Contact, name='contact'), url(r'^(?P<category_slug>[-\w]+)/(?P<product_slug>[-\w]+)/$', views.productPage, name='product_detail'), url(r'^(?P<category_slug>[-\w]+)/$', views.marketplaceHome, name='products_by_category'), url('^cart$', views.cart_detail, name='cart_detail'), url(r'^cart/add/(?P<product_id>[-\w]+)/$', views.add_cart, name='add_cart'), url(r'^cart/remove/(?P<product_id>[-\w]+)/$', views.cart_remove, name='cart_remove'), url(r'^cart/remove_product/(?P<product_id>[-\w]+)/$', views.cart_remove_product, name='cart_remove_product'), ] ''' views.py ''' from __future__ import unicode_literals from django.shortcuts import render, get_object_or_404, redirect from .models import Category, Product, Cart, CartItem from django.core.exceptions import ObjectDoesNotExist from . import forms # Create your views here. def marketplaceHome(request, category_slug=None): category_page = None products = None if category_slug !=None: category_page = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=category_page, available=True) else: products = Product.objects.all().filter(available=True) return render(request, 'marketplacehome.html', {'category': category_page, 'products': products}) def productPage(request, category_slug, product_slug): try: product = Product.objects.get(category__slug=category_slug, slug=product_slug) except Exception as e: raise e return render(request, 'product.html', {'product': product}) def search(request): products = Product.objects.filter(name__contains=request.GET['name']) return render(request, 'marketplacehome.html', { 'products': products}) ''' template.html ''' <ul class="navbar-nav ml-auto"> <form class="form-inline" action="{% url 'search' %}", method="GET"> <div class="input-group"> <input type="text" name="name" class="form-control" placeholder="Location" aria-label="Search" name="query"> <div class="input-group-append"> <button type="button" class="btn btn-warning" name="button"><i class="fas fa-search"></i></button> … -
How can I dynamically find out a subclass' package name in Python?
For context, I'm writing a library that uses Django's ORM. I don't want users of my library to have to define the app_label every time they subclass my custom Model superclass, instead I want to enforce a standard structure for projects created with it that makes sure the package name of every class that subclasses my Model superclass will equal the app_label. Here's the code I currently have: class Model(django.db.models.Model): class Meta: abstract = True def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) # package_name = ??? cls._meta.app_label = package_name The ??? part is what I can't seem to figure out. Any ideas? -
How to deploy create-react-app and Django to the same linux server
I want to deploy create-react-app as frontend and Django with Graphene as backend to a Linux server. Gunicorn config in /etc/systemd/system/gunicorn.service is as follows: [Unit] Description=gunicorn daemon After=network.target [Service] User=name Group=www-data WorkingDirectory=/home/name/mijn-bureau/backend/app ExecStart=/home/name/mijn-bureau/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/name/backend.sock app.wsgi:application [Install] WantedBy=multi-user.target Nginx config in /etc/nginx/sites-available/ is as follows: server { listen 80; root /var/www/frontend/build; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location / { } location /api { include proxy_params; proxy_pass http://unix:/home/name/backend.sock; } } Thus, react frontend is served and I see the login screen. But when I want to login it doesn't work. The Graphql client config is as follows: const client = new ApolloClient({ uri: 'http://example.com/api/graphql/', fetchOptions: { credentials: 'include' }, request: (operation) => { const token = localStorage.getItem(AUTH_TOKEN_KEY) || ""; operation.setContext({ headers: { Authorization: `JWT ${token}` } }) }, clientState: { defaults: { isLoggedIn: !!localStorage.getItem(AUTH_TOKEN_KEY) } } }); What do I do wrong? -
Cross-Origin Request Blocked Django-project
I've built a REST API and I'm following along with this tutorial: https://www.youtube.com/watch?v=hISSGMafzvU&t=14s I've completed all up until 13minutes. addition of a JS script into the html template. When I run and check the console I get: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/task-list/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)." I have no idea what part of my projects the CORS header goes into? script type="text/javascript"> buildList() function buildList(){ var wrapper = document.getElementById('list-wrapper') var url = 'http://127.0.0.1:8000/api/task-list/' fetch(url) .then((resp) => resp.json()) .then(function(data){ console.log('Data:', data) }) } </script> -
Django I want to limit user voting to once per 24 hours but I limited it per article and not per user
I would like to kindly ask you for your help. I wanted to create simply voting system for questions. And I succeded, then I wanted to limit users to voting only once per 24 hours and I failed miserable. I know what I want to achieve but I don't know how to code it. Right now with my mistake I limited voting on QUESTION once per 24 hours. Instead of that I wanted to limit one USER to vote ONCE per 24 hour on EACH question. So I made pretty stupid mistake. Here is my code with my mistake: models.py: class Question(models.Model): question = models.CharField(max_length=300) answered = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) datecompleted = models.DateTimeField(null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) votesscore = models.IntegerField(default='0') votescoresubmitted = models.DateTimeField(null=True, blank=True) amountofvotes = models.IntegerField(default='0') def __str__(self): return self.question views.py: @login_required() def questionvoteup(request, question_pk): question = get_object_or_404(Question, pk=question_pk, user=request.user) if request.is_ajax() and request.method == "POST": if question.votescoresubmitted is None or timezone.now() > question.votescoresubmitted + timedelta(minutes=1440): question.votesscore += 1 question.amountofvotes += 1 question.votescoresubmitted = timezone.now() question.save() data = { "msg": 'Thank you for your vote!' } return JsonResponse(data) else: raise forms.ValidationError("You can vote only one time every 24 hours.") else: return HttpResponse(400, 'Invalid form') Right now I … -
Django extra parameter of modelformset_factory
I noticed a behaviour I am not sure I understand with the parameter extra of modelformset_factory: When I set extra to an integer, django pulls out object instances that I recently deleted. How could this be the case ? Thank you. -
Why can't I update my heroku website via git push?
I am working on a website (django) that I uploaded online with heroku. Everything worked fine until I had to make a change in my views.py. Now when I do: - git add . - git commit -m "smtg" - git push heroku master It tells me that nothing change but I made some changes, it seems like it cannot see those. When I try git init it tells me " Reinitialized existing Git repository in C:/Users/Loic/Documents/my_site2/.git/ " Could you please help me it is a school project. Thank you