Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django filter choices, order choices on template in order written in filter
I have a Django Filter that that has 4 choices. I would like to order these choices on the template in the order that I have written them in the filter. filter.py: RarityChoices = { ('common', 'Common'), ('uncommon', 'Uncommon'), ('rare', 'Rare'), ('mythic', 'Mythic') } rarity = ChoiceFilter(field_name='rarity', empty_label='Any', choices=sorted(RarityChoices), widget=RadioSelect()) template.html: <div> <label class="mb-1" for="id_type">Rarity:</label> {{ card_filter.form.rarity}} </div> Screenshot: If I change my filter to: rarity = ChoiceFilter(field_name='rarity', empty_label='Any', choices=RarityChoices, widget=RadioSelect()) The filter looks like this on the template: Neither are in the order that I want or in the order listed in the filter.py file. -
Can't find installed package when running GitHub actions
I'm trying to switch from Circle to GH actions and having an issue; I'm getting a ModuleNotFoundError when importing Django. I think the error is happening because I'm using a custom image; I'm using GH actions on other Django projects in almost exactly the same way without issues. ci.yml name: CI on: push: branches: - master tags: - '**' pull_request: {} jobs: test: runs-on: ubuntu-latest container: tutorcruncher/tutorcruncher-test-image:py3.9 services: postgres: image: postgres:12 ports: - 5432:5432 redis: image: redis ports: - 6379:6379 options: --entrypoint redis-server steps: - uses: actions/checkout@v2 - name: set up python uses: actions/setup-python@v1 with: python-version: '3.9' - name: install dependencies run: | make install-test pip freeze python manage.py collectstatic --noinput --verbosity 0 - run: make test For reference, make install test simply calls pip install -r requirements.txt and pip install -r requirements.test.txt. When I run pip freeze, I can see all of my installed packages, including Django. However, when python manage.py collectstatic runs, I get a ModuleNotFoundError: Traceback (most recent call last): File "/__w/MyProject/MyProject/manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' Thanks in advance, Tom -
i got a connection refused error in my windows 10 while i trying to login by django
ConnectionRefusedError at /accounts/login/ [WinError 10061] No connection could be made because the target machine actively refused it Request Method: POST Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 3.1.5 Exception Type: ConnectionRefusedError Exception Value: [WinError 10061] No connection could be made because the target machine actively refused it Exception Location: c:\users\naseem ssd\appdata\local\programs\python\python39\lib\socket.py, line 831, in create_connection Python Executable: E:\PROJECTS\CODELATTICE\Envitic\CodelatticeMaster\venvEnvitic\Scripts\python.exe Python Version: 3.9.0 -
how to delete local files from client computer with django
hello i am trying to make a file deleter, that when you specify the file adress and submit, that file would be deleted. worked great on localhost but when i uploaded to server and run it was not working.. the logic is simple it is only deleting files from server not from client computer. pls give me a solution for this? html <form action="" method="post"> {% csrf_token %} <input type="text" name="adress" id="url"> <button type="submit">delete</button> <button onclick="edit()" type="button">edit</button> </form> <script> function edit(){ let inp = document.getElementById('url') let val = document.getElementById("url").value; let raw = val.replaceAll('\\',"\\\\") inp.value = raw; console.log(inp.value) console.log('\\') } views def delete(request): if request.method == "POST": adress = request.POST['adress'] shutil.rmtree(adress) return redirect('/success') else: return render(request,'file_deleter_app/home.html') def page(request): return HttpResponse("success") pls give me solution to delete client local files with django and python -
Slicing paginator.page_range inside a template
I have page_obj in a template which was returned from a ListView view. Now, I wanted to create links to several pages before and after the current page. Therefore, I wanted to slice page_obj.paginator.page_range this way: page_obj.paginator.page_range[page_obj.number-3:page_obj.number+4]. This works in django shell but for some reason when I did it a template, there is a Template Syntax Error, Could not parse the remainder: '[page_obj.number-3:page_obj.number+4]' from 'page_obj.paginator.page_range[page_obj.number-3:page_obj.number+4]'. Is there a workaround for this case? P.S. I know I can do it using the whole page_obj.paginator.page_range and then using if statements to check if a page is in the required range, but I thought it's a bit inefficient. -
how can I edit data while clicking on edit button in sheet and auto populating data in the form above
I want to auto populate my data in the form above from sheet displayed below, for editing/updating when the user clicks at edit button beside that particular row.[enter image description here][1] [1]: https://i.stack.imgur.com/VSk9F.png this is my html file`<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://use.fontawesome.com/releases/v5.15.2/js/all.js" data-auto-replace-svg="nest"></script> <title>Manufacture Spare Items</title> <style> label { font-weight: bold; } </style> </head> <body> <div class="jumbotron-fluid bg-dark text-light text-center p-3"> <h1> Manufacture Spare Items</h1> <h3>(Board RSP)</h3> </div> <div class="container mt-3"> <form method="POST" action=""> {% csrf_token %} <div class="form-group"> <div class="row"> <div class="col-sm-4"> <label for="currentFY">Financial Year <sup style="font-size: 15px; color:red;">*</sup> </label> <select id="currentFY" name="currentFY" size="1" class="custom-select text-center" required> <option value="" selected>Select</option> </select> </div> <div class="col-sm-4"> <label for="stock_ord_type">Type of Stock Ordered <sup style="font-size: 15px; color:red;">*</sup></label> <select id="stock_ord_type" name="stock_ord_type" class="custom-select" onchange="populateRate(this)" required> <option value="" selected>Select</option> <option value="Clutch Drive Assly">Clutch Drive Assly</option> <option value="HHP PP">HHP PP</option> <option value="HHP MTA WDP4D">HHP MTA WDP4D</option> <option value="HHP MTA WDG4">HHP MTA WDG4</option> <option value="Power Assly (Blade Rod)">Power Assly (Blade Rod)</option> <option value="Power Assly (Fork Rod)">Power Assly (Fork Rod)</option> <option value="Turbo over Hauling">Turbo over Hauling</option> <option value="TSC Assly">TSC Assly</option> <option … -
django.db.utils.IntegrityError: UNIQUE constraint failed: auctions_bids.item_id
I building the auctions website and have this problem: UNIQUE constraint failed: auctions_bids.item_id models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.deletion import CASCADE from django.db.models.fields import EmailField, NOT_PROVIDED class User(AbstractUser): pass class Listings(models.Model): title = models.CharField(max_length=64) description = models.TextField(max_length=250) price = models.FloatField() image_url = models.CharField(max_length=150) category = models.ForeignKey(Categories, on_delete=models.CASCADE) listed_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.title}" #{self.description} {self.price} {self.image_url} {self.category}" class Bids(models.Model): item = models.OneToOneField(Listings, on_delete=models.CASCADE) bid = models.FloatField(blank=True) user_bid = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) def __str__(self): return f"{self.item} {self.bid} {self.user_bid}" views.py def placebid(request, id_product): if request.method == "POST": item_list = Listings.objects.get(pk=id_product) bid = request.POST['bid'] user = request.user Bids.objects.update_or_create(item=item_list, bid=bid, user_bid=user) return redirect(reverse("listings", args=(id,))) When I try to update the new bid, this appears the above error, the only way to delete the old object and create a new object, I want to update the new bid if the object exists and create if the object doesn't exist by using update_or_create I think I had wrong in setting parameter item values of the Bids model, but I don't know how to fix them! Any advice for me, Thanks so much !!! -
Having problems getting bootstrap snippet to display as previewed
I tried using the following footer snippet below (in my base.html file, using Django), but am having problems getting it to display as previewed. I'm using bootstrap 5 for most of my code, but this snippet is supposed to be for bootstrap 4. Any guidance on where I'm going wrong would be greatly appreciated. TIA Snippet Code for Footer: <div class="footer"> <!-- footer --> <div class="container"> <div class="row "> <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12 "> <div class="ft-logo"><img src="https://easetemplate.com/free-website-templates/cointrade/images/logo.png" alt=""></div> </div> </div> <hr class="footer-line"> <div class="row "> <!-- footer-about --> <div class="col-xl-3 col-lg-3 col-md-4 col-sm-6 col-6 "> <div class="footer-widget"> <div class="footer-title">Company</div> <ul class="list-unstyled"> <li><a href="#">About Us</a></li> <li><a href="#">Customer Support</a></li> <li><a href="#">Press</a></li> <li><a href="#">Legal & Privacy</a></li> </ul> </div> </div> <!-- /.footer-about --> <!-- footer-links --> <div class="col-xl-3 col-lg-3 col-md-4 col-sm-6 col-6 "> <div class="footer-widget"> <div class="footer-title">Quick Links</div> <ul class="list-unstyled"> <li><a href="#">News</a></li> <li><a href="#">Contact Us</a></li> <li><a href="#">FAQs</a></li> </ul> </div> </div> <!-- /.footer-links --> <!-- footer-links --> <div class="col-xl-3 col-lg-3 col-md-4 col-sm-6 col-6 "> <div class="footer-widget"> <div class="footer-title">Social</div> <ul class="list-unstyled"> <li><a href="#">Twitter</a></li> <li><a href="#">Google +</a></li> <li><a href="#">Linked In</a></li> <li><a href="#">Facebook</a></li> </ul> </div> </div> <!-- /.footer-links --> <!-- footer-links --> <div class="col-xl-3 col-lg-3 col-md-12 col-sm-6 col-6 "> <div class="footer-widget"> <h3 class="footer-title">Subscribe To Our Newsletter</h3> … -
How to iterate list of dict in django template?
I have this dict in python django template how can i show this in select box code as value and text as name {"operatingUnits":[{"code":"Banswara","name":"Banswara"},{"code":"Ratlam","name":"Ratlam"},{"code":"Mandsaur","name":"Mandsaur"},{"code":"ENUGU","name":"ENUGU"},{"code":"Bhubaneswar","name":"Dammam"},{"code":"GGN","name":"Gurgaon"},{"code":"SELANGOR","name":"SELANGOR"},{"code":"Bhiwandi","name":"Bhiwandi"},{"code":"GZB","name":"Ghaziabad"},{"code":"Gandhidham","name":"Gandhidham"},{"code":"Kota","name":"Kota"},{"code":"Udaipur","name":"Udaipur"},{"code":"Neemuch","name":"Neemuch"},{"code":"Jodhpur","name":"Jodhpur"},{"code":"KEDAH","name":"KEDAH"},{"code":"ANTARA","name":"ANTARA"},{"code":"ABUJA","name":"Pune"},{"code":"NASHIK","name":"nashik"},{"code":"Ind","name":"Indore"},{"code":"CHENNAI","name":"CHENNAI"},{"code":"RIYADHFRANCHISEE","name":"Chandigarh"},{"code":"123","name":"dsd"},{"code":"HARIDWAR","name":"HARIDWAR"},{"code":"PUNE","name":"Jeddah"},{"code":"VAPI","name":"vapi"},{"code":"Delhi","name":"HO Delhi"},{"code":"HYDERABAD","name":"HYDERABAD"},{"code":"ISTANBUL","name":"ISTANBUL"},{"code":"Kolkata","name":"Kolkata"},{"code":"Ahmadabad","name":"Ibadan"}]} I am facing problem in django template -
Django contact us section
I am new to web development, I have one page django portfolio app in which there is section for contact us, I have used class based views with post method. However when I click submit button I think POST request is not getting called, due to which my send_mail function inside post function is not working. views.py class HomeView(TemplateView): template_name = 'home.html' http_method_names = ['post', 'get'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['about'] = About.objects.first() context['services'] = Service.objects.all() context['works'] = RecentWork.objects.all() return context @csrf_exempt def post(self, request): if request.method == "POST": message = request.POST['message'] try: send_mail('Test Subject', message, settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER]) except Exception: print(Exception) return HttpResponse('Error: Invalid header found') return HttpResponse('success') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.HomeView.as_view(), name='home'), ] home.html <div class="invitation-area section-padding"> <div class="container"> <div class="row"> <div class="single-invite text-center"> <h2>Do you have any project need to be done?</h2> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias at cupiditate distinctio dolorem dolores impedit, inventore magnam magni nam numquam quidem ratione rem repellendus, saepe?</p> <a href="#contact" class="my-btn-3">Get started</a> </div> </div> </div> </div> <div id="contact" class="contact-area section-padding"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="section-header text-center"> <h2>Contact Me</h2> </div> </div> </div> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-8 col-md-offset-2 col-lg-8 col-lg-offset-2 … -
Django: Parsing multipart/form-data
Problem: From the client side, a request with the following specifications is sent to the server. http://localhost:8000/api/v1/user/save Method: POST The data send the request as formdata. data includes an object of user information and an image of the user as follows: { user_info: { name: "John", code: "12345", }, avatar(an image file) } Question: How can I parse user_info and avatar values in UserInfoAPI views.py? # views.py class UserInfoAPI(APIView): def post(self, request, format=None): try: # return Response({"Success": "User created successfully!"}, status=status.HTTP_200_OK) ... Efforts: I wanted to get help from this link, and although I think my answer is in this answer, I could not get a result. -
How do i successfully add Topic to Django admin? Using settings.py to add learning_logs to INSTALLED_APPS
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] I was directed to enter code 'learning_logs' along with installed apps and I was unable to migrate learning_logs as admin topic. I tried to edit code over again and format it as there are 2 files: learning log and learning log(s) and when I reopened editor the edit wasnt saved and admin wasnt showing Topics to add on localhost website. Thanks in advance for help. -
Django Size (Dropdown) and Color (Radio Buttons) with changing prices/images dependant of radio button data JQuery
I want to hide/show the colors (radio buttons) when i choose a different size (dropdown). Like this: Red - 16Gb, Blu and Red 32Gb. But instead of showing Red, Blue and Red, it should only show red when it is 16Gb and only show Blue and Red when it is 32Gb (All are separate products I added from the admin panel) My HTML is: <form id='add-form' method='POST' action="{% url 'cart' %}"> <h3 id='price'>{{ object.variation_set.first.price }}</h3> <br/> <!-- SIZE --> <span class="text-uppercase">Size :</span> {% csrf_token %} <select name="size" class='form-control' id="size"> {% for variation in sizes %} <option data-variation-id-1='{{variation.size}}' > {{ variation.size.name }} </option> {% endfor %} </select> <br/> <!-- COLOR --> <span class="text-uppercase">Color :</span> <div id="buttons"> {% for variation in colors %} <!-- this controls how the price, images, and all attributes of the variations change through JQuery--> <input type="radio" class="radio_color" name='item' id="variantid" data-img-list='{{variation.get_image_url}}' data-variation-id-2='{{variation.size}}' data-sale-price="{{ variation.sale_price }}" data-price="{{ variation.price }}" value="{{ variation.id }}" data-color-hex="{{variation.color.code}}"/> {{ variation.color }} {% endfor %} </div> My JS is: function setPrice(input){ var price = $(input).attr("data-price") $("#price").html("<h3> $" + price + "</h3>"); } setPrice("input[type='radio']"); //on change $('input[type=radio]').change(function(){ setPrice($(this)); }); How do I make my Colors (Radio buttons), dependant (show/hide) on what size is chosen in the … -
Django Rest Framework URL for custom action not working
I've got the following custom action in my view: class OrderAPIViewSet(viewsets.ViewSet): def create(self, request): print("Here: working") @action(detail=True, methods=['post']) def add(self, request, *arg, **kwargs): print("HERE in custom action") order = self.get_object() print(order) my app's urls.py is: from rest_framework import routers from .views import OrderAPIViewSet router = routers.DefaultRouter() router.register(r'orders', OrderAPIViewSet, basename='order') urlpatterns = router.urls So in my test when I try to access orders/post it works, but when I try to access orders/{pk}/add it fails. I mean, the reverse itself is failing: ORDERS_LIST_URL = reverse('order-list') ORDERS_ADD_URL = reverse('order-add') class PublicOrderApiTests(TestCase): def test_sample_test(self): data = {} res = self.client.post(ORDERS_ADD_URL, data, format='json') as I said before, I've got a separate test where I use ORDERS_LIST_URL like this: res = self.client.post(ORDERS_LIST_URL, data, format='json') but when running the test I'm getting the following error: ImportError: Failed to import test module: orders.tests Traceback (most recent call last): File "/usr/local/lib/python3.7/unittest/loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "/usr/local/lib/python3.7/unittest/loader.py", line 377, in _get_module_from_name import(name) File "/app/orders/tests.py", line 22, in ORDERS_ADD_URL = reverse('order-add') File "/usr/local/lib/python3.7/site-packages/django/urls/base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 685, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'order-add' with no arguments not found. 2 pattern(s) tried: ['orders/(?P[^/.]+)/add\.(?P[a-z0-9]+)/?$', 'orders/(?P[^/.]+)/add/$'] ---------------------------------------------------------------------- Ran 1 … -
how to set rest framwork in django settings.py file
INSTALLED_APPS = [ 'rest_framwork', #is this correct# 'movie.apps.MovieConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
Error during template rendering : NoReverseMatch at /OnetoOneRelationApp/ Reverse for 'RestaurantDetails' with arguments '('',)' not found
ERROR : NoReverseMatch at /OnetoOneRelationApp/ Reverse for 'RestaurantDetails' with arguments '('',)' not found. 1 pattern(s) tried: ['OnetoOneRelationApp/(?P<pk>[0-9]+)/$'] I am getting the above error while try to access the restaurant details from hyperlink of restaurant name.It is working fine when I am using " {{ restaurant.name }}" in my template but when I tried use the below code it is throwing error {{ restaurant.name }}" code: Models.py: ------------------------------------------------------------- from django.db import models from django.urls import reverse class Place(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=70) def __str__(self): return self.name class Restaurant(models.Model): name = models.CharField(max_length=70) place = models.OneToOneField(Place, on_delete=models.CASCADE, primary_key=True) servers_pizza = models.BooleanField(default=False) def get_absolute_url(self): return reverse('OnetoOneRelationApp:RestaurantDetails', kwargs={'pk': self.pk}) def __str__(self): return self.name class Waiter(models.Model): name = models.CharField(max_length=30) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) def __str__(self): return self.name urls.py: -------------------------- from django.urls import path from .views import RestaurantsList, WaiterRestaurantDetails app_name = 'OnetoOneRelationApp' urlpatterns = [ path('OnetoOneRelationApp/', RestaurantsList.as_view(), name='RestaurantsList'), path('OnetoOneRelationApp/<int:pk>/', WaiterRestaurantDetails.as_view(), name='RestaurantDetails'), ] Views.py ---------------------------------------------------------------------------------------- from django.views import generic from .models import Restaurant class RestaurantsList(generic.ListView): model = Restaurant template_name = 'OnetoOneRelationApp/Restaurants.html' context_object_name = 'Restaurants_List' class WaiterRestaurantDetails(generic.DetailView): model = Restaurant template_name = 'OnetoOneRelationApp/Restaurant-Details.html' context_object_name = 'Restaurant' templates.py:(Restaurants.html) ----------------------------------------------------------------------------------------- {% if Restaurants_List %} {% for restaurant in Restaurants_List %} <ul> <li> <a href="{{ restaurant.get_absolute_url }}" target="_blank">{{ restaurant.name }}</a> … -
How do I internationalize a Django site while ignoring Accept-Language?
I'm about to internationalize a site. I considered the options. Should I use subdomains or path? Subdomains seems to rather target the case where different language versions are going to differ (diverge). Should the language be always present in the URL, or should I use cookies/local storage? In other words, should the URL determine the language version? Since I want all the versions to be indexed, putting language into URL seems more reasonable. Also, there's the "sending a link" case. Right now I'm leaning towards using path and URL determining language version. Moreover I'm thinking of leaving the main language URLs intact, e.g.: https://example.com/path - English version https://example.com/de/path - German version ... To avoid adding redirects from language-agnostic URLs. Particularly I'm not sure if redirects from the main page are good for SEO. That said, I discovered that LocaleMiddleware processes the Accept-Language header (unless there's nothing in the URL). Which is nice, but how do I avoid that? Or is it a sign I'm doing it wrong? -
Django model save() not working when I submit
So I make a page that can let user submit their data and save to database, however, it doesn't save. Here is my code: Models: from django.contrib.postgres.fields import ArrayField; from django.conf import settings; from django.db import models; class UsersAddGame(models.Model): STATUS = [ ('booked', 'Booked'), ('wishlist', 'Wishlist'), ('Not interested', 'Not intersted'), ] PLATFORMS = [ ('NS', 'Nintendo Switch'), ('PS4', 'PlayStation4'), ('PS5', 'PlayStation5'), ('XBO', 'Xbox One'), ('XS', 'Xbox Series S/X'), ] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE); gameName = models.CharField(max_length = 200, null = False); tba = models.BooleanField(default = False); releaseDate = models.DateField(auto_now = False, auto_now_add = False); platform = ArrayField(models.CharField(max_length = 100,null = False, choices = PLATFORMS)); status = models.CharField(max_length = 200, null = False, choices = STATUS, default = 'booked'); forms.py: from showList.models import UsersMarksTags, UsersAddGame; from django.contrib.auth.forms import UserCreationForm; from django.contrib.auth.models import User; from django import forms; class DateInput(forms.DateInput): input_type = 'date' # user add game to list. class addGameForm(forms.ModelForm): PLATFORMS = [ ('NS', 'Nintendo Switch'), ('PS4', 'PlayStation4'), ('PS5', 'PlayStation5'), ('XBO', 'Xbox One'), ('XS', 'Xbox Series S/X'), ]; class Meta: model = UsersAddGame; fields = ['gameName', 'tba', 'releaseDate', 'platform', 'status']; widgets = { 'releaseDate': DateInput() } platform = forms.MultipleChoiceField( required=True, widget=forms.CheckboxSelectMultiple, choices=PLATFORMS, ) views.py: from django.views.generic import TemplateView, FormView, View; from … -
Django add many to many with Big Integer as primay key
I have users model with Positive Big integer field as the primary key, and I want to create a many to many relationship with Roles table, the issue is that the pivot table (containing the relationship) is being created with an integer field (user_id), which doesn't allow me to actually store any relationship for users with high ID number. id = models.PositiveBigIntegerField(unique=True, primary_key=True) This is my user model: class User(AbstractBaseUser): id = models.PositiveBigIntegerField(unique=True, primary_key=True) email = models.EmailField(_("email address"), unique=True) display_name = models.CharField(_("Display Name"), max_length=64, blank=True) is_active = models.BooleanField(_("active"), default=True) is_deleted = models.BooleanField(default=False) roles = models.ManyToManyField(Role, related_name="%(app_label)s_%(class)s_related") and this is my Role model: class Role(models.Model): name = models.CharField(max_length=64) is_deleted = models.BooleanField(default=False) Check screenshot of DB schema below P.S: I tried creating the relationship manually with: roles = models.ManyToManyField(Role, related_name="%(app_label)s_%(class)s_related", through='UserRoles') and creating the table: class UserRoles(models.Model): role = models.ForeignKey(Role, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, to_field='id') But that also didn't work. -
Adding a customizable date range to exporting csv
For previous context, I programmed (huge thanks to ladhari) a export csv button for my Wagtail site. See here. Currently, it prints out all of the objects desired. However, a new goal I want to accomplish is to be able to somehow specify a customizable date range in the admin to export to the csv. The object in question has a Created On field that we can call in the code. How would we approach this? The most straightforward solution I tried was creating a second button that exports the last 30 days but obviously this doesn't match the objective of allowing the user to somehow input a data range in the Wagtail dashboard. For example, if we want a record of all of the objects created between 2/13 and 2/20 it'd export that to the csv instead. -
Serializer field 'source' argument does not work when validating
Why does 'source' not work when trying to validate data? from rest_framework import serializers class Test(serializers.Serializer): my_field = serializers.CharField(source='myField') test_data = {'myField': 'test1', 'myOtherField': 'test2'} Test(test_data).data The output: {'my_field': 'test1'}. Test(test_data).is_valid(raise_exception=True) The output: AssertionError: Cannot call .is_valid() as no data= keyword argument was passed when instantiating the serializer instance. Test(data=test_data).is_valid(raise_exception=True) The output: ValidationError: {'my_field': [ErrorDetail(string='This field is required.', code='required')]} -
ManyToMany Field what to put for auto generated id in template?
I have read this https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/ and I'm still struggling with working with ManyToMany integrated with the form, view, and HTML file. I basically want to do this but in DJango and can't figure out how to do it properly: class Person: def __init__(self, name): self.name = name self.skills = [] class Skill: def __init__(self, name): self.name = name programmingSkillOne = Skill("C++") programmingSkillTwo = Skill("Java") programmingSkillThree = Skill("QML") listOfSkills = [] listOfSkills.append(programmingSkillOne) listOfSkills.append(programmingSkillTwo) listOfSkills.append(programmingSkillThree) personOne = Person("Stephanie") personOne.skills = listOfSkills personTwo = Person("Lizzy") personTwo.skills.append(Skill("C++")) people = [personOne, personTwo] print ("\n") for person in people: print(person.name + "'s skills are: \n") for s in person.skills: print(s.name) print("\n") Any help will be greatly appreciated!:) -
Django: reverse error when passing multiple arguements in url
I am getting a reverse error when trying to use a url that has many arguements. error: Reverse for 'find_search' with arguments '('all',)' not found. 1 pattern(s) tried: the url path that i want to use is: path('search=product=<str:product_selected>genres=<str:genres_selected>movie_tv_genres=<str:movie_tv_genres_selected>non_fiction_genres=<str:non_fiction_genres_selected>game_genres=<str:game_genres_selected>sub_genres=<str:sub_genres_selected>game_sub_genres=<str:game_sub_genres_selected>keywords=<str:keywords_selected>game_keywords=<str:game_keywords_selected>platforms=<str:platforms_selected>game_platforms=<str:game_platforms_selected>', views.find_search, name='find_search'), but it only works if I use a single arguement like this : path('search=product=<str:product_selected>', views.find_search, name='find_search'), path('search=genres=<str:genres_selected>', views.find_search, name='find_search'), path('search=movie_tv_genres=<str:movie_tv_genres_selected>', views.find_search, name='find_search'), path('search=non_fiction_genres=<str:non_fiction_genres_selected>', views.find_search, name='find_search'), path('search=game_genres=<str:game_genres_selected>', views.find_search, name='find_search'), path('search=sub_genres=<str:sub_genres_selected>', views.find_search, name='find_search'), path('search=game_sub_genres=<str:game_sub_genres_selected>', views.find_search, name='find_search'), path('search=keywords=<str:keywords_selected>', views.find_search, name='find_search'), path('search=game_keywords=<str:game_keywords_selected>', views.find_search, name='find_search'), path('search=platforms=<str:platforms_selected>', views.find_search, name='find_search'), path('search=game_platforms=<str:game_platforms_selected>', views.find_search, name='find_search'), path('search=genres=<str:genres_selected>', views.find_search, name='find_search'), here is the views: def find(request): context = { 'product_selected': 'All', 'genres_selected': 'all', 'movie_tv_genres_selected': 'all', 'non_fiction_genres_selected': 'all', 'game_genres_selected': 'all', 'sub_genres_selected': 'all', 'game_sub_genres_selected': 'all', 'keywords_selected': 'all', 'game_keywords_selected': 'all', 'platforms_selected': 'all', 'game_platforms_selected': 'all', 'products': Posts, } return render(request, 'find/find.html', context) in my templates i call this url {% url 'find_search' product_selected genres_selected movie_tv_genres_selected non_fiction_genres_selected game_genres_selected sub_genres_selected game_sub_genres_selected keywords_selected game_keywords_selected platforms_selected game_platforms_selected %} There is probably something obvious that i'm missing here so I hope someone can point it out -
What is the best language for back-end development node js or django or flask
I need to answer for my question for choosing the back-end development language -
Python: Long running streaming task in the server request/response lifecycle
How do I keep a long running script alive outside of the request/response lifecycle when that script is initiated by an HTML/AJAX request? Background: I have a Django app with a specific endpoint that streams results back to the client using StreamingHttpResponse. In general this is working well. I have a series of generators that save each result to the database, yield their result to the StreamingHttpResponse, and the client displays each result appropriately as soon as it is received. The problem arises when the client connection is unexpectedly lost. This causes the script to stop abruptly because Django closes the connection. I would like to come up with some mechanism by which that long running script can continue to execute so that all results can be processed and saved to the database. Then the user can retrieve the results after they regain a connection to the server. Requirement: The solution should allow streaming of results (which we currently have), but also keep the script alive to continue processing results even if the client stream dies unexpectedly. Simplicity of Solution: I would like to keep this solution as simple as possible. It seems like this would be a relatively common …