Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin, ManyToMany field getting Unknown field(s) (linked_sites) specified for Model error
I have two Django Models connected through ManyToMany relation. class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) account = models.ForeignKey(Account, related_name=RelatedNames.USERS, on_delete=models.CASCADE, null=True, blank=True) accessed_sites = models.ManyToManyField(Site, related_name=RelatedNames.USERS) class Site(models.Model): name = models.CharField(max_length=255) location = models.OneToOneField(GeoLocation, on_delete=models.PROTECT, related_name=RelatedNames.ADDRESS, blank=True, null=True) score = models.IntegerField(default=0) avg_spent_time = models.DurationField(default=timedelta(days=0)) _type = models.IntegerField(choices=SiteTypeChoices.CHOICES, max_length=20) primary_email = models.EmailField(null=True, blank=True) def __str__(self): return self.name def get_site_address(self): return str(self.location) I'm trying to display and modify the relation through the admin: class SitesAdmin(ModelAdmin): fields = [Fields.NAME, Fields.PRIMARY_EMAIL, Fields.TYPE, Fields.SCORE, Fields.LOCATION] list_display = fields class UsersAdmin(ModelAdmin): fields = [Fields.EMAIL, 'full_name', Fields.ACCOUNTS, 'linked_sites'] list_display = [Fields.EMAIL, 'full_name', Fields.ACCOUNTS, 'linked_sites'] readonly_fields = ('full_name',) def full_name(self, obj): return obj.get_full_name() def linked_sites(self, obj): return "\n".join([site.name for site in obj.accessed_sites.all()]) the list display works but when opening a User object I'm getting the following error: Unknown field(s) (linked_sites) specified for CustomUser. Check fields/fieldsets/exclude attributes of class UsersAdmin. -
Filter product Django "LATEST", "BEST SALE", "TOP RATED","ON SALE"
I need your help. I have 4 categories "LATEST", "BEST SALE", "TOP RATED" and "ON SALE". In the "LATEST", I want to show the 20 most recently added products. In the "BEST SALE", need to show products that have the best-selling status. In the "TOP RATED", need to show 20 products with a high rating. In the "ON SALE", need to show 20 products that have the sale status. How do I make a filter for these categories? Thanks a lot. Some examples Django, please. class Product(models.Model): StatusProduct=( (_(''), _('')), (_('best sale'), _('BEST SALE')), (_('on sale'), _('ON SALE')), ) name = models.CharField(_('Name'), max_length=150, blank=True, null=True, default=None, help_text=_('The maximum number of characters - 150')) price = models.DecimalField(_('Price'), max_digits=10, decimal_places=1, default=0) discount = models.IntegerField(_('Discount'), default=0) status = models.CharField(_('Status'), max_length=20, choices=StatusProduct, default='') parentcategory = models.ForeignKey(ParentCategory, verbose_name=_('Category'), on_delete=models.CASCADE, blank=True, null=True, default=None) category = models.ForeignKey(MenuBarProduct, verbose_name=_('Category'), on_delete=models.CASCADE, blank=True, null=True, default=None) subcategory = models.ForeignKey(CategoryProduct, verbose_name=_('Category'), on_delete=models.CASCADE, blank=True, null=True, default=None) short_description = CKEditor5Field(_('Short description'), config_name='extends', blank=True, null=True, default=None) description = CKEditor5Field(_('Description'),config_name='extends', blank=True, null=True, default=None) is_active = models.BooleanField(_('Active'), default=True, help_text=_('Activated, allow to publish')) created = models.DateTimeField(_('Created'), auto_now_add=True, auto_now=False) updated = models.DateTimeField(_('Updated'), auto_now_add=False, auto_now=True) created_by = models.ForeignKey(User, verbose_name=_('Created by'), on_delete=models.CASCADE, editable=False, null=True, blank=True) def __str__(self): return "%s" % (self.name) … -
celery add_periodic_task with multiple crontab
I'm using celery with django 3. Originally, I wanted to run my get_index function every minute from 9 to 12:30 in [sat,sun,mon,tue,wed]. After some research, I find out that it's not possible to handle my case with a single crontab (because of 12:30); So I end up using two crontabs, which seem to work: crontab(minute='*', hour='9-12', day_of_week='sat,sun,mon,tue,wed') crontab(minute='00-30', hour='12', day_of_week='sat,sun,mon,tue,wed') But when I try to use them, like: @app.on_after_finalize.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(crontab(minute='*', hour='9-12', day_of_week='sat,sun,mon,tue,wed'), get_index.s(), name='fetch index from tse every minute from 9 to 12 on workdays') sender.add_periodic_task(crontab(minute='00-30', hour='12', day_of_week='sat,sun,mon,tue,wed'), get_index.s(), name='fetch index from tse every minute from 12 to 12:30 on workdays') Only the second one will apply. If I change the name of the second task to something like `get_index2` and duplicate my function, it will work fine. I think the same function name (get_index) is causing the issue. Is there any way to add bind multiple crontab to a single add_periodic_task? or somehow using same function for multiple add_periodic_task? -
Python Django no items shows on cart
My main project shop works as expected. But I just added a cart to my project. when I click add item to cart on my main page I see this: [04/Oct/2020 07:14:56] "POST /cart/EEE-1249363/ HTTP/1.1" 302 0 [04/Oct/2020 07:14:56] "GET /cart/ HTTP/1.1" 200 964 which may say that the item got added to cart. But when I go to my cart I can't display any item. Here is my entire cart. Can you please tell me what I am doing wrong? here is my cart/templates/cart/detail.html {% extends 'base.html' %} {% block content %} <h1>HI there </h1> {% for product in product %} <p>{{ product.quantity }} </p> <p>{{ product.name }} </p> {% endfor %} {% endblock %} cart/apps.py: from django.apps import AppConfig class CartConfig(AppConfig): name = 'cart' cart/cart.py: from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): """ Initialize the cart """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, override_quantity=False): """ Add a product to the cart or update its quantity. """ product_PN = str(product.PN) if product_PN not in self.cart: self.cart[product_PN] … -
correct endpoint for fetching user's profile django rest framework
I have pretty simple models: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=32, unique=True) name = models.CharField(max_length=64, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=128, blank=True) about = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) And I have a /user endpoint. This endpoint is handled by a DRF ModelViewSet. Pretty straightforward. Now I need to also fetch user's profile to render in my React app. I need to be able to get, put/patch and maybe delete profiles. What is the correct implementation for this? For now I have following endpoing /user/int:pk/account. And a view: class ProfileView(RetrieveUpdateDestroyAPIView): serializer_class = serializers.AccountSerializer lookup_url_kwarg = 'pk' queryset = Account.objects.all() http_method_names = ['get', 'put', 'delete'] permission_classes = [IsAccountOwner] def get(self, request, *args, **kwargs): instance = get_object_or_404(Account, user=self.kwargs.get('pk')) serializer = self.get_serializer(instance) return Response(serializer.data) def put(self, request, *args, **kwargs): instance = get_object_or_404(Account, user=self.kwargs.get('pk')) self.check_object_permissions(self.request, instance) serializer = self.get_serializer(instance, data=request.data) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) def delete(self, request, *args, **kwargs): instance = get_object_or_404(Account, user=self.kwargs.get('pk')) self.check_object_permissions(self.request, instance) self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT) So I am overriding the logic to fetch or update profiles by user's id, not the … -
Using Django to retrieve values of an attribute based on user-selected values of another attribute
I have 3 tables which are item, shop and stock item table consists of item_id item_name item_price 1 drug AJG 32.00 2 drug BOLS 10.00 3 drug CPP 5.00 4 drug C77 55.00 5 drug CLIMO 13.00 shop table consists of shop_id shop_name shop_country 3 ABC Clinic Australia 4 FYZ Hospital New Zealand 5 HH Pharmacy Spain 22 SAJ Clinic Portugal 33 PO Pharmacy Portugal stock table consists of shop_id item_id stock_qty 3 1 22 4 2 45 5 3 11 22 4 39 33 5 66 I've built web app using Django to allow the user to input the item_name (i.e., Drug A) and shop_name (ABC Clinic) using the following code. So far, i have a function that is able to show the item names and shop names based on regex. However, the results rendered also show combinations where the shop does not have that particular item. For example, the results.html page will show ABC clinic with Drug CLIMO stock if the user keys in Climo for item and ABC for shop - even though ABC clinic does not have that drug. As such, is there some way Django can display the shops that only have stock of the … -
How to Save or Print the array field in Django using CreateView?
HTML Array of Input Field Model.py Models.py Image Forms.py Forms.py Image Views.py Views.py Image Please help me here. I want to convert this array field values into string with comma separated and then save in table. I hope I will get resolution. Thanks in Advance. -
Django using FTP for large files
I'm using Django admin to upload large files into another server ( A download host ). The files are usually 100mb. I'm using FTP currently based on this. It works fine with files less than 1mb but as it itself says in the documentation, it doesn't work with larger files and I get a 503 when the upload finishes in the Django admin. I really searched a lot about another way to to this but it seems there is no other way in Django. can you help me? -
Taking value of selected radio buttons from one page in Django
I want to take value of selected radio buttons in a single page. To explain this here is my code in models.py file class Quiz(models.Model): Description = models.CharField(max_length=200) def __str__(self): return str(self.Description) class Question(models.Model): Question_Text = models.CharField(max_length=500) Option1 = models.CharField(max_length=100) Option2 = models.CharField(max_length=100) Option3 = models.CharField(max_length=100, blank=True) Option4 = models.CharField(max_length=100, blank=True) Answer = models.CharField(max_length=100) QuizID = models.ForeignKey(Quiz, on_delete=models.CASCADE) def __str__(self): return str(self.Question_Text) I want user to choose one option from "Option1, Option2, Option3, Option4" fields and I want to get value of the selected radio button. Here's my try: disp.html <form action="" method="post"> {% csrf_token %} {% for q in question %} {{ q.Question_Text }} <br> <input type="radio" id="question_{{ q.Option1 }}" name="{{ q.id }}" value="{{ q.Option1 }}"> <label for="question_{{ q.Option1 }}">{{ q.Option1 }}</label> <br> <input type="radio" id="question_{{ q.Option2 }}" name="{{ q.id }}" value="{{ q.Option2 }}"> <label for="question_{{ q.Option2 }}">{{ q.Option2 }}</label> <br> {% if q.Option3 %} <input type="radio" id="question_{{ q.Option3 }}" name="{{ q.id }}" value="{{ q.Option3 }}"> <label for="question_{{ q.Option3 }}">{{ q.Option3 }}</label> <br> {% endif %} {% if q.Option4 %} <input type="radio" id="question_{{ q.Option4 }}" name="{{ q.id }}" value="{{ q.Option4 }}"> <label for="question_{{ q.Option4 }}">{{ q.Option4 }}</label> <br> {% endif %} {% endfor %} <br> <input type="submit" class="btn btn-primary" … -
Stream videos uploaded to digitalocean
I would like to create a website where users could upload some videos and Could set a time to play/stream it at a specific time, so that other logged in users could watch the stream at that time. I am using Django to build the website and using angular to serve the frontend. I have a digitalocean space and would like to know the best options to upload and stream the videos at specific time from the account. I am new to programming so please let me know if there is any way to achieve this, or if I should be making use of any other technologies or methods. -
Django CSRF missing or incorrect Ajax POST without jquery (Vanilla JavaScript)
when i got this error when i was using jquery i simple do: data: {'csrfmiddlewaretoken': "{{csrf_token}}"} Now I'm trying to move to vanilla JavaScript, here is my ajax call <script> document.addEventListener('DOMContentLoaded', function () { document.querySelector('#sendMessage').onclick = function (e) { e.preventDefault(); let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function (e) { if (this.readyState == 4 && this.status == 200) { alert('success') let response = this.responseText console.log(response) } else { console.log(this.status) console.log(this.readyState) } }; xhr.open("POST", "{% url 'chat:room' room.id %}", true); // Send data csrf_token, content, area xhr.setRequestHeader('Content-type', 'application/json'); data = { 'csrfmiddlewaretoken': '{{ csrf_token }}', 'content': document.querySelector('#id_content').value, 'area': parseInt(document.querySelector('#id_area').value), } console.log(data) xhr.send(JSON.stringify(data)); } }); </script> However i get this error: Forbidden (CSRF token missing or incorrect.): /chat/room/3/ [04/Oct/2020 05:25:16] "POST /chat/room/3/ HTTP/1.1" 403 2513 I have been searching for a while but all answers are solving it for jquery not vanilla js, Any help? -
TemplateDoesNotExist at /accounts/login/ login.html
Imm trying to use default django login system. It gives me error that my login.html templates does not exist. I have my login templates saved in a root directory..> templates>registration>login.html Imm using custom user models and token authentication.. Here's what i tried ..> account urls.py from django.contrib.auth import views as auth_views from django.conf.urls import url from django.urls import path urlpatterns = [ path("login/", auth_views.LoginView.as_view(template_name = "login.html"), name='login'), path("logout/", auth_views.LogoutView.as_view(), name='logout'), ] Main App Urls.py from django.contrib import admin from django.urls import path, include from rest_framework.urlpatterns import format_suffix_patterns from django.conf.urls.static import static from django.conf import settings from django.conf.urls import url from articles.views import ArticleDetail, ArticleList from account.views import AccountList from rest_framework.authtoken import views urlpatterns = [ path('admin/', admin.site.urls), path('article/', ArticleList.as_view()), path('article/<int:pk>/', ArticleDetail.as_view()), path('accounts/', AccountList.as_view()), path('accounts/', include('account.urls')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns = format_suffix_patterns(urlpatterns) Templates dir in settings.py# TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Does using a custom user models and Token auth effects default login system ? -
'list' object has no attribute '_meta'
why my code is showing this error as my whole code is correct? 'list' object has no attribute '_meta' my views.py from django.shortcuts import render, redirect, get_list_or_404 from .models import Task from .forms import TaskForm def update_task(request, pk): up_task = get_list_or_404(Task, id=pk) if request.method == 'POST': up_form = TaskForm(request.POST, instance=up_task) if up_form.is_valid(): up_form.save() return redirect('tasks') else: up_form = TaskForm(instance=up_task) context = { 'update_task_form': up_form } return render(request, 'task/update_task.html', context) my urls.py from django.urls import path from . import views urlpatterns = [ path('', views.tasks, name='tasks'), path('task/<str:pk>/update/', views.update_task, name='update_task'), ] my error Internal Server Error: /task/3/update/ Traceback (most recent call last): File "C:\Users\Royal\AppData\Roaming\Python\Python38\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Royal\AppData\Roaming\Python\Python38\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Royal\PycharmProject\todoapp\todoapp\task\views.py", line 31, in update_task up_form = TaskForm(instance=up_task) File "C:\Users\Royal\AppData\Roaming\Python\Python38\site-packages\django\forms\models.py", line 294, in init object_data = model_to_dict(instance, opts.fields, opts.exclude) File "C:\Users\Royal\AppData\Roaming\Python\Python38\site-packages\django\forms\models.py", line 85, in model_to_dict opts = instance._meta AttributeError: 'list' object has no attribute '_meta' [04/Oct/2020 09:06:27] "GET /task/3/update/ HTTP/1.1" 500 71974 Internal Server Error: /task/3/update/ Traceback (most recent call last): File "C:\Users\Royal\AppData\Roaming\Python\Python38\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Royal\AppData\Roaming\Python\Python38\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Royal\PycharmProject\todoapp\todoapp\task\views.py", line 31, in update_task up_form = … -
How to get user instance in Model Serializer in django Rest Framework
I have 2 models CustomUser and Student. In CustomUserSerializer, whenever the user is created i also want to create Student instance inside CustomUserSerializer. How can I get the current user instance? # models.py class CustomUser(AbstractUser): is_student = models.BooleanField('student status', default=False) is_teacher = models.BooleanField('teacher status', default=False) email = models.EmailField(_('Email Address'), unique=True, blank=True) class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) # serializers.py class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = models.CustomUser fields = [ 'id', 'email', 'is_teacher', 'is_student',..] def create(self, validated_data): if validated_data.get('is_student') == True: Student.objects.create(user=...?) # what should I put here? return super(CustomUserSerializer, self).create(validated_data) [UPDATED] I have another question it's related to Student model. If I have models like below should I create serializer for Student? when I want to have serializer for Class. class Class(models.Model): student = models.ManyToManyField(Student) Thanks -
What a solution of with python 3.8.6 version in fatal python error: "initfencoding"
Fatal Python error: initfsencoding: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' -
How do I instantiate Django models using data from an API?
So at the moment, I've written the code to make calls to an API and write it to a file on my machine so I can go through it and figure out which values are located where, etc. I have also written the code to open the file and loop through the values. All I need to do now (as far as I'm aware) is write the piece of code that instantiates models using values provided by the data pulled from the API. The problem is, I have no idea where to put this code and how to call it. The code I've written is all in a separate python file located in the same directory as my Django app.I thought I could run the code from that file if I imported Django's models and the model I'm trying to create, so I added from django.db import models from models import MyModel to the beginning but was given the following error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I appreciate that the traceback is telling me exactly what to do, but I have no … -
TypeError at '' __init__() got an unexpected keyword argument ''
I am working through a project creating a simple Django auction site and I am having difficulty overriding the init method in a Django modelform when creating a new Bid from the 'Detail' view and passing a related object(auction) & user. I am trying to override the BidForm(forms.modelform) init method so i can pass the related 'Auction' object using kwargs.pop. I get the error 'TypeError: init() got an unexpected keyword argument 'auction'' Please suggest what i am doing wrong and point me in the right direction- Thank you in advance Model class Bid(TimeStampMixin): """ Model representing a bid in an auction """ auction = models.ForeignKey( Listing, on_delete=models.SET_NULL, related_name='offer', null=True) bidder = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='bid_user') amount = models.PositiveIntegerField() objects = BidQuerySet.as_manager() def get_absolute_url(self): return reverse('detail', args=[self.pk]) def __str__(self): return f"{self.amount} in Listing No: {self.auction.id}" class Meta: ordering = ['amount'] @staticmethod def high_bid(auction, bidder, bid_amount): """util method to ascertain highest bid in auction then update in related auction obj **auction---listing being bid on, bid__auction **bidder---user bidding **amount--- current highest bid """ ###error checks, is current bid less than start bid? etc if bid_amount < auction.start_bid: return if (auction.highest_offer and bid_amount < auction.highest_offer.amount): return if bidder.id is auction.user.id: raise PermissionDenied ##after … -
Reverse for 'wagtailadmin_explore' with arguments '('',)' not found
I have been trying to rebuild my Wagtail website as a docker container to be run on Fargate. For reasons, I started from scratch and rebuilt all my dependencies. After pip installing everything, the site works fine locally using venv. However, I get strange errors when launching the in the Docker container. Can anyone help me identify a fix for this? I get the following error at /admin: Error during template rendering In template /usr/local/lib/python3.8/site-packages/wagtail/admin/templates/wagtailadmin/home/site_summary_pages.html, error at line 4 Reverse for 'wagtailadmin_explore' with arguments '('',)' not found. 1 pattern(s) tried: ['admin/pages/(?P<parent_page_id>[0-9]+)/$'] 1 {% load i18n wagtailadmin_tags %} 2 3 <li class="icon icon-doc-empty-inverse"> 4 <a href="{% url 'wagtailadmin_explore' root_page.pk %}"> 5 {% blocktrans count counter=total_pages with total_pages|intcomma as total %} 6 <span>{{ total }}</span> Page <span class="visuallyhidden">created in {{ site_name }}</span> 7 {% plural %} 8 <span>{{ total }}</span> Pages <span class="visuallyhidden">created in {{ site_name }}</span> 9 {% endblocktrans %} 10 </a> 11 </li> 12 My base image for Docker is Python 3.8 Alpine. I've diffed a pip freeze for both local and Docker and the versions of the packages are the same. All migrations run on both docker and local. Here is my pip freeze from the Docker implementation: asgiref==3.2.10 … -
How to fit data from a jsonresponse to a live graph in Django?
I'm trying to implement a live graph using ajax and Django. I am using a function bellow that generating continuous data and a view returning this data as a json response. #Data Generation def DataGene(): while True: time.sleep(3) data = {'dp':randrange(10), 'dt':datetime.now().strftime('%Y-%m-%d %H:%M:%S')} #print (randrange(10), datetime.now().strftime('%Y-%m-%d %H:%M:%S')) return data if __name__ == "__main__": DataGene() How to fit this data into the live graph Live plot (https://canvasjs.com/html5-javascript-dynamic-chart/): <html> <head> <script> window.onload = function () { var dps = []; // dataPoints var chart = new CanvasJS.Chart("chartContainer", { title :{ text: "Dynamic Data" }, data: [{ type: "line", dataPoints: dps }] }); var xVal = 0; var yVal = 100; var updateInterval = 1000; var dataLength = 20; // number of dataPoints visible at any point var updateChart = function (count) { count = count || 1; for (var j = 0; j < count; j++) { yVal = yVal + Math.round(5 + Math.random() *(-5-5)); dps.push({ x: xVal, y: yVal }); xVal++; } if (dps.length > dataLength) { dps.shift(); } chart.render(); }; updateChart(dataLength); setInterval(function(){updateChart()}, updateInterval); } </script> </head> <body> <div id="chartContainer" style="height: 370px; width:100%;"></div> <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script> </body> </html> Django View: def fetch_values_ajax(request): data = ReturnData() return JsonResponse(data) -
400 (Bad Request) on an Ajax POST request using Django Rest Framework
I thought I'd ask this here as I'm not too sure where I am going wrong. I am trying to do a POST request via AJAX using Django Rest Framework Class. However, I am getting the following error whenever the event fires: OST http://127.0.0.1:8000/api/uservenue/ 400 (Bad Request) This is what is appearing in the Stack Trace: {"list":["This field is required."],"venue":["This field is required."]} Context I am trying to make it so when a user clicks an "add-to-list" button it sends a cafeName (and eventually other details) to a user defined list. I'm wondering if someone could take a look at my code and give me some guidance as to where I am going wrong? The Code Here is the relevant model: class UserVenue(models.Model): venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT) list = models.ForeignKey(UserList, on_delete=models.PROTECT) Here is the relevant serializer.py class UserVenueSerializer(serializers.ModelSerializer): class Meta: model = UserVenue fields = ['list', 'venue'] Here is the relevant URLs router = DefaultRouter() #need help understanding router register router.register('userlist', views.UserList) router.register('uservenue', views.UserVenue) Here is the relevant views.py class UserVenue(viewsets.ModelViewSet): serializer_class = UserVenueSerializer queryset = UserVenue.objects.all() @ensure_csrf_cookie def get_queryset(self): cafeName = self.request.GET.get('cafeName', None) print(cafeName) return UserVenue.objects.all() And, finally, here is the ajax call with the CSRF code incl. var … -
Django admin panel does not have a standard form
Django admin panel does not have a standard form I'm trying to deploy my site on VPS - debian 10, django 3.1, but the admin panel does not have a standard form -
How can i write an API about listing something between two dates in django?
probably it's quite simple but i've never write an api before so i am stucked. I've 2 datepicker area to choose dates like this; <div> <label>Starting Date</label> <input id="startDatePicker" type="text" class="form-control datepicker" autocomplete="off"> </div> <div class="mx-2"> <label>Ending Date</label> <input id="endDatePicker" type="text" class="form-control datepicker" autocomplete="off"> </div> <a onclick="???" class="btn btn-info" href="javascript:void(0);"> Show <i class="fas fa-caret-right"></i></a> And my models: class Fund(models.Model): name = models.CharField(max_length=500, null=False, blank=False, verbose_name="Fund Name") code = models.CharField(max_length=5, null=False, blank=False, verbose_name="Fund Code") management_price = models.CharField(max_length=15, null=True, blank=True, verbose_name="Management Price") performance_price = models.CharField(max_length=15, null=True, blank=True, verbose_name="Performance Price") explanation = models.TextField(max_length=1000, null=True, blank=True, verbose_name="Explanation") class FundData(models.Model): fund = models.ForeignKey(Fund, on_delete=models.CASCADE, related_name="data_of_fund", verbose_name="Fund") date = models.DateField(auto_now_add=False, editable=True, blank=False, verbose_name="Date") price = models.FloatField(max_length=15, blank=False, verbose_name="Fund Price") Here is my table needs to be fill: <table id="fundReturnsTable" class="table table-striped table-bordered mt-2" style="width:100%; display:none"> <thead> <tr> <th>Fund Code</th> <th>Fund Name</th> <th>Starting Date Price</th> <th>Ending Date Price</th> </tr> </thead> <tbody> <tr> <th>example.FundCode</th> <th>example.FundName</th> <th>example.FundreturnEnterdateprice</th> <th>example.FundreturnNowdateprice</th> </tr> if nothing shows up <tr> <th colspan="6">There are no datas between this dates.</th> </tr> </tbody> What i am trying to do is, user will choose dates and see which fund has what price in that dates. Ask any detail you need to know i'm quite newbie on asking things here, … -
Django Rest Framework GET request returning Unathorized on React Frontend
it's my first question of SO. please, point out where I need to clarify at any point. Im building a django back-end, react front-end app. I have this view that returns a 401 response whenever I try to directly access it on the front-end, even when a user is logged in. I have access to my other views but this one. It works fine in the drf browsable API. I'm using both Session and TokenAuthentication in my default authentication classes. -
How do I stop all of my projects redirecting to a specific URL?
I have been trying to learn Django to build a personal website where I can host some machine learning stuff I've made for others to use. In the process, I found this tutorial by Mozilla. I think what created the issue was the part saying RedirectView.as_view(url='catalog/', permanent=True). I was trying to make a simple function grapher for my site, so I used 'grapher/' instead of 'catalog/'. Now, that worked for what I was trying to do. Then I created a new django project to try some things from a different tutorial, and now when I try to run "py manage.py runserver" and go to http://localhost:8000, I still get redirected to http://localhost:8000/grapher/. This happens in all of my django projects, new and old. Now, the really mysterious part to me was that when I tried deleting those projects AND the virtual environments I was using, then making a new virtual environment and project, I still get redirected http://localhost:8000/grapher/. I have also tried adding "path('', RedirectView.as_view(url='', permanent=True))," to my project.urls.py file which did not work. If there are some commands I can run to give more information, I would love to. I just don't know what other detail I can post since … -
How do I convert .md files from zip files to url links in django using markdown2?
I'm working on how to convert .md files that I extracted from a folder for a project where I create a Wikipedia webpage (with search engine). I have been trying to use markdown on .md files and convert them to viewable and working url links on the webpage, but have had little success. How should I convert them so that they fit in the "a href" tag properly? I'm wondering what it should look like when I convert and if I should use the Path: C:\Users\17346\Desktop\CS50Project01\wiki\entries\Python.md or the Relative path: entries\Python.md ?