Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Beautiful Soup - Extract data only contain td tag (without tag like div, id, class....)
I'm new to Beautiful Soup, and I have data like this, which contain 3 set of user data(for this case). I want to get all the information for each USER_ID and save to database. User ID Title Content PID(not every user has this row) Date URL <table align="center" border="0" style="width:550px"> <tbody> <tr> <td colspan="2">USER_ID 11111</td> </tr> <tr> <td colspan="2">string_a</td> </tr> <tr> <td colspan="2"><strong>content: aaa</strong></td> </tr> <tr> <td colspan="2"><strong>date:</strong>2020-05-01 00:00:00 To 2020-05-03 23:59:59</td> </tr> <tr> <td colspan="2"><strong>URL:https://aaa.com</strong></td> </tr> <tr> <td colspan="2">&nbsp;</td> </tr> <tr> <td colspan="2">&nbsp;</td> </tr> <tr> <td colspan="2">USER_ID 22222</td> </tr> <tr> <td colspan="2">string_b</td> </tr> <tr> <td colspan="2"><strong>content: bbb</strong></td> </tr> <tr> <td colspan="2"><strong>date:</strong>2020-05-01 00:00:00 To 2020-05-03 23:59:59</td> </tr> <tr> <td colspan="2"><strong>URL:https://aaa.com</strong></td> </tr> <tr> <td colspan="2">&nbsp;</td> </tr> <tr> <td colspan="2">&nbsp;</td> </tr> <tr> <td colspan="2">USER_ID 33333</td> </tr> <tr> <td colspan="2">string_c</td> </tr> <tr> <td colspan="2"><strong>content: ccc</strong></td> </tr> <tr> <td colspan="2"><strong>date:</strong>2020-05-01 00:00:00 To 2020-05-03 23:59:59</td> </tr> <tr> <td colspan="2"><strong>PID:</strong><strong>ABCDE</strong></td> </tr> <tr> <td colspan="2"><strong>URL:https://ccc.com</strong></td> </tr> <tr> <td colspan="2">&nbsp;</td> </tr> <tr> <td colspan="2">&nbsp;</td> </tr> </tbody> </table> My problem is, All the data are inside td only, and do not contain div name and no parent tag. I can't separate into 3 set of data. I have try the following code, it can find all the USER_ID, but … -
How to change the value of related model
This line of code is iterating through the related queryset: order = Order.objects.get(user=self.request.user, ordered=False) for order_item in order.items.all(): order_item.item.quantity += 1 Its changing the value of quantity (I can see that using (print(order_item.item.quantity)), but it doesn't save in the database. I have tried order.save(), but the value stays the same (before +=1). What I have to do to save new value to the database? -
How do I change a value in django database on button click in HTML?
I have a booleanField in my hostelApplication model, I want to change that field using html button, but I don't know much about js. Please anyone tell me what I am doing wrong. here is my models.py, I have shown only necessary fieds. class hostelApplication(models.Model): hostelName = models.CharField(verbose_name='Select Hostel', max_length=20, choices=hostels, default='shivalik') isApproved = models.BooleanField(default=False) def __str__(self): return self.hostelName I have added my url path in urls as url(r'^ajax/change_status/$', views.ajax_change_status, name='ajax_change_status') here is my html file {% for application in applications %} {% csrf_token %} <div class="table-content"> <div class="table-row"> <div class="table-data">{{application.hostelName}}</div> <div class="table-data">{{application.dateApplied}}</div> <div class="table-data"> <button type="button" class="btn btn-info" id="state">Approve</button> </div> </div> {% endfor %} I have added this js script in this template on the top <script> $("#state").on('click', function () { var username = $(this).val(); var isApproved = true // or false, you have to set it var id = application.id // you have to set it $.ajax({ url: '/ajax/validate_username/', data: { 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(), 'isApproved': isApproved 'id': username }, dataType: 'json', success: function (data) { if (data.success) { alert("ajax call success."); // here you update the HTML to change the active to innactive }else{ alert("ajax call not success."); } } }); }); </script> -
Clearing the Session failure: Django Form to pickled ML prediction
I currently have a pickled model for predicting survivability of Titanic based on user inputs of a Django form. After a few days at this, I am now able to finally get a response to the front end of whether someone survived! After submission, i use django.contrib message to send a "survived" or "perished" underneath the form. However, after the first submission, the fields clear in the form, but when i try to enter in new values and submit, i get a '_thread._local' object has no attribute 'value' error. form, error Now, if i restart the django server and refresh the page, i can run the POST again, but just not consecutivetly on the same session. so i dug around and someone had a statement included in a similar project where they "from kera import backend as K" and then added below right before the return in the function: K.clear_session() But when i put that into my code, I get the same Attribute Error as before but i get it on the first form submission, rendering it copletely useless. So, how can I use the form to repeatedly query the model with each use being independent. the outcome of the … -
queryset based on related model
I've got two models. One (FAQ) is related to the other (FAQCategory). I'm trying to develop a queryset of FAQCategories that are assigned to FAQs, but only if at least one of the FAQs has both the question and answer filled in. class FAQCategory(models.Model): title = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.title class FAQ(models.Model): category = models.ForeignKey(FAQCategory, on_delete=models.SET_NULL, null=True, blank=True) question = models.CharField(max_length=100, null=True, blank=True) answer = models.TextField(max_length=10000, null=True, blank=True) For example, we have 3 FAQCategories 1) General 2) Shipping 3) Warrenty 1) General is not assigned to any faqs. It should not show up in the queryset 2) Shipping is assigned to a FAQ instance, but that FAQ doesn't have an answer on it. Shipping should not show up in the queryset 3) Warrenty is assigned to a FAQ. That FAQ has both an answer and a question value. As a result, Warrenty should appear in the queryset. How would I write this in django? Thanks! -
how to render common things in footer.html in django
i am new here in django, i have setup the layout, which contains index.html, header.html and footer.html, in footer.html i want to set dynamically phone number, email and address, i can see i can pass it through context from views.py, but footer.html will include in all the templates, so if i will write code in views.py in every function i need to write it, which is not good, so what i want, i want to create one common function and i want to call it from footer.html, is that the right way to do so ? or if you have any other idea then please let me know how to do that ? here i have added my footer.html views.py def index(request): portal_contact_email = preferences.MyPreferences.portal_contact_email context = {'portal_contact_email': portal_contact_email,} return render(request, 'mysite/index.html', context) footer.html <footer class="bg-dark footer-section"> <div class="section"> <div class="container"> <div class="row"> <div class="col-md-4"> <h5 class="text-light">Email</h5> <p class="text-white paragraph-lg font-secondary">{{ portal_contact_email }} </p> </div> <div class="col-md-4"> <h5 class="text-light">Phone</h5> <p class="text-white paragraph-lg font-secondary"></p> </div> <div class="col-md-4"> <h5 class="text-light">Address</h5> <p class="text-white paragraph-lg font-secondary"></p> </div> </div> </div> </div> <div class="border-top text-center border-dark py-5"> <p class="mb-0 text-light">Copyright @<script> var CurrentYear = new Date().getFullYear() document.write(CurrentYear) </script> {# a theme by <a href="https://themefisher.com">themefisher.com</a>#} </p> </div> … -
How to extend signup model of django-allauth and add firstname and lastname fields?
I am using django-allauth app and to extend user model I added firstname and lastname in models.py as below: class CustomUser(AbstractUser): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) then added its associated form in forms.py within accounts app: class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email', 'first_name', 'last_name', 'username') finally customized the urls.py file within accounts app and added a view to use customized above stated form and model: urlpatterns = [ path('signup/', SignupView.as_view(), name='sign_up'), ] and in views: class SignupView(CreateView): model = CustomUser form_class = CustomUserCreationForm template_name = 'account/signup.html' I passed the form in template and it is not showing firstname and lastname fields. -
Django Rest Framework and React Front End: How to serve sensitive images only to the user that has the correct Token authentication?
My understanding is that on a normal React website all the media will be served from the same server than the front-end files (HTML, CSS and Javascript). The REST API backend will only provide links to where those images are stored, and it will be served and displayed by the front end. The problem is if those images are private and only one user should be able to see them. If someone gets ahold of the image link and opens it they would be able to see the image. How do modern websites get around this problem? What would be the workflow between Django and React to keep the user's images safe and private? Can the private images be stored in the REST API server and only be sent as a response to a user if it has the proper token? Many thanks in advance! -
How to get a specific foreign key value
My models.py look like that: class Order(models.Model): items = models.ManyToManyField(OrderItem) class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) class Item(models.Model): quantity = models.IntegerField(default=1) In my function I have access to the Order table and I am trying to get information about the quantity of Item. I tried that: order.items.item.quantity, but I get that error: 'ManyRelatedManager' object has no attribute 'item' How would I get the quantity number from Item table? -
Django User not Logging in After Being Created Using Registration Form
I am pretty new at Django and I just got my project onto a Ubuntu server using nginx and uwsgi. When I try to login using a user I created on the front-end, Django tells me that either the username or password was incorrect. These problems did not occur when working on localhost, only now in production. I am just using the base django user model creating my users in views.py class CreateUser(FormView): def get(self, request): form = UserCreationForm context = {'form': form} return render(request, 'VR360/register.html', context) def post(self, request): form = UserCreationForm(request.POST) if form.is_valid(): user = user_form.save(commit=False) user.set_password(user_form.cleaned_data['password'] user.save() messages.success(request, 'User was saved') print("Creating the user was successful") return HttpResponseRedirect("main:homepage") else: for msg in form.error_messages: print(form.error_messages[msg]) messages.error(request,':( Your passwords do not match or it did not meet the below criteria') return redirect("main:register") I know that the user is being saved to the database because 'meme' was created using the registration page >>> from django.contrib.auth.models import User >>> def username_present(username): ... if User.objects.filter(username=username).exists(): ... return True ... ... return False ... >>> username_present('meme') True >>> I authenticate the user using django's login.html {% block content %} {% if form.errors %} <p> An error occured :(</p> <p>Your username and password didn't … -
Django registration serializers
Hello every one i need to make three apis for Login , registration and logout...can i make three api with these one serializer...? serializers.py from django.contrib.auth.models import User from rest_framework import serializers from rest_framework.authtoken.models import Token class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'password'] extra_kwargs = {'password': {'write_only': True, 'required': True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) return user views.py from django.contrib.auth.models import User, Group from rest_framework import viewsets from .serializers import UserSerializer # from rest_framework.authentication import TokenAuthentication # from rest_framework.permissions import IsAuthenticated class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # authentication_classes = (TokenAuthentication,) # permission_classes = (IsAuthenticated, ) urls.py from django.urls import include, path from rest_framework import routers from .views import UserViewSet from rest_framework.authtoken.views import ObtainAuthToken router = routers.DefaultRouter() router.register(r'registration', UserViewSet) urlpatterns = [ path('', include(router.urls)), path('signIn/', ObtainAuthToken.as_view()) ] -
Django Simple Captcha HTML5 Validation Errors
I am not sure if the project maintainer for django-simple-captcha needs to fix their code to be HTML5 valid or if there is a way to fix the HTML5 validation errors using rendering method below. I would appreciate any assistance. https://django-simple-captcha.readthedocs.io/en/latest/advanced.html#rendering https://github.com/mbi/django-simple-captcha/blob/master/captcha/templates/captcha/hidden_field.html https://github.com/mbi/django-simple-captcha/blob/master/captcha/templates/captcha/field.html https://github.com/mbi/django-simple-captcha/blob/master/captcha/templates/captcha/text_field.html Attribute autocorrect not allowed on element input at this point. <input type="text" name="captcha_1" class="form-control mt-2" placeholder="Solve the captcha" required id="id_captcha_1" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false"></p> Attribute required not allowed on element input at this point. <input type="hidden" name="captcha_0" value="e83b1ca0e5149574b9b19098074dd3de390b339f" class="form-control mt-2" placeholder="Solve the captcha" required id="id_captcha_0"> Attribute placeholder is only allowed when the input type is email, number, password, search, tel, text, or url. <input type="hidden" name="captcha_0" value="e83b1ca0e5149574b9b19098074dd3de390b339f" class="form-control mt-2" placeholder="Solve the captcha" required id="id_captcha_0"> -------------- Forms.py: class CustomCaptchaTextInput(CaptchaTextInput): template_name = 'custom_field.html' class ContactForm(forms.Form): captcha = CaptchaField(widget=CustomCaptchaTextInput) def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.fields['captcha'].widget.attrs['class'] = 'form-control mt-2' self.fields['captcha'].widget.attrs['placeholder'] = 'Solve the captcha' self.fields['captcha'].label = "Enter the correct captcha as shown in the image" -------------- custom_field.html: {% load i18n %} {% spaceless %} <label class="control-label">{{ label }}</label> <img src="{{ image }}" alt="captcha" class="captcha" /> <br/> <audio class="w-100 mt-2" controls> <source src="{{ audio }}" /> … -
Limit mptt tree manager to only one tree node
using MPTTModelAdmin and DraggableMPTTAdmin through django admin is there any option to force only ONE TREE in the object? expected result: User should not be able to create any new Root Node or move an existing node to become a Root Node By manipulating the model, I can achieve some way around it, but it will casue throuble for future migrations class MySingleTree(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') #blank=False will prevent creating multiple root; null=False will prevent moving to become new root Thank you -
How do I run pytest for one testcase in a Django app when I have been using "python manage.py test" all this time?
Django v2.2 I have been writing my test case for 2 years now this way: from django.test import override_settings from rest_framework.test import APIClient, APITestCase from someapp.tests.factories import ( OrganizationFactory, ) class SomeTestCase(APITestCase): def setUp(self): self.maxDiff = None self.organization = OrganizationFactory(name="ENP", domain="localhost") @override_settings(ALLOWED_HOSTS=["*"]) def test_something(self): self.assertTrue(True) then I run python manage.py test logical.path.to.SomeTestCase.test_something --keepdb the --keepdb is to avoid thrashing the test database and rebuild from scratch My config.settings.test.py is """ With these settings, tests run faster. """ from .base import * # noqa from .base import env # GENERAL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = False # https://docs.djangoproject.com/en/dev/ref/settings/#secret-key SECRET_KEY = env("DJANGO_SECRET_KEY", default="lKwzkRnq8dksTthPauE61WrNPVwA3HdnJtQ9HuIyCpBib5zCY06tFsD5TUpNlCnO") # https://docs.djangoproject.com/en/dev/ref/settings/#test-runner TEST_RUNNER = "django.test.runner.DiscoverRunner" # CACHES # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#caches CACHES = { "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "LOCATION": "" } } # PASSWORDS # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"] # TEMPLATES # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#templates TEMPLATES[0]["OPTIONS"]["debug"] = DEBUG # noqa F405 TEMPLATES[0]["OPTIONS"]["loaders"] = [ # noqa F405 ( "django.template.loaders.cached.Loader", [ "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ], ) ] # EMAIL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#email-backend EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend" # https://docs.djangoproject.com/en/dev/ref/settings/#email-host EMAIL_HOST = "localhost" # https://docs.djangoproject.com/en/dev/ref/settings/#email-port EMAIL_PORT = 1025 # Your stuff... # ------------------------------------------------------------------------------ The python manage.py test command worked Now i write a new test using pytest import pytest pytestmark … -
Reverse for 'probability' with arguments '('',)' not found. 1 pattern(s) tried: ['probabilities/(?P<probability_id>[0-9]+)$']
I have just started using django and have hit a road bump. I am trying to associate a probability.id with a url and keep receiving a "NoReverseMatch at /probabilities/". Every time I click the "Probabilities" link on my index page it crashed with aforementioned error. I am using django 3.0. Trace Back My trace back is telling me the error is within the " href="{% url 'probability_analysis_app:probability' probability.id %}">{{proability}}" in the template, probabilities.html I have tried configuring urls.py and have made sure my path is defined I have tried searching this error with more or less detail (None have helped me fix this issue) urls urls views views template template -
django runserver works, but with daphne there's an error
I have a django website with channels for websockets that is working on my local machine. I can call python manage.py runserver and the site runs fine, the frontend websocket connection can send and receive from the backend server. However, when I wrap the django code in a daphne call, it throws an error: daphne -b 0.0.0.0 backend.app_proj.asgi:application File "c:\projects\injurycheck\v1\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "c:\projects\injurycheck\v1\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "c:\projects\injurycheck\v1\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Program Files\Python38\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 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'pipeline' Can anyone say why the site builds correctly under runserver, but inside daphne it can't find an app that is actually included in INSTALLED_APPS? -
Django: the particuler user(driver) is not selected when submitting the post onto the database
am working on a project where I am using two main modules a normal user(Loader) and a Driver where loader can post their load and driver ship that load to starting to the final destination ... now I have a few problems while using two foreign keys in my model. one model for the post(where user post that load) and driver see that post and add their price to that post now I created a new model for a price where I inherit post model and user (driver) in my price model but when a driver submits their price ..the particular login driver is not selected in the database (admin). here is my post model.py (loader(user)) class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, unique=True) receiver_name = models.CharField(max_length=150) sending_item = models.CharField(max_length=150) image_of_load = models.ImageField(default='',null=True) weight = models.CharField(max_length=150) metric_unit = models.CharField(max_length=30, default='') quantity = models.PositiveIntegerField() pick_up_time = models.DateField() drop_time = models.DateField() amount = models.CharField(max_length=150, null=True) paid_by = models.CharField(max_length=150) created_at = models.DateTimeField(auto_now=True) published_date = models.DateField(blank=True, null=True) def __str__(self): return self.user.username def publish(self): self.published_date = timezone.now() self.save() def approve_prices(self): return self.prices.filter(approved_price=True) def get_absolute_url(self): return reverse("Loader:my_job", kwargs={"pk": self.pk}) here is my price … -
Is it pythonic/Djangoic for Model A's methods to reference Model B?
Presume I have these classes: class Book(models.Model): title = models.CharField() authors = models.ManyToManyField(Author) def display_text(self): return f"{self.title} by {','.join([x.name for x in self.author_set.all()])}" class Author(models.model): first_name = models.CharField() last_name = models.CharField() def name(self): return f"{self.first_name} {self.last_name}" Is it normal/acceptable/the standard way of doing things to have the attributes of one model refer to another this way? This is a heated debate at work, with the two sides being "don't do that, it can promote query count leaks" and "this is much more readable than most alternatives". Is there a community-standard take on this problem? -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'DCountry'
I am getting the captioned error whenever i try the below code: DCountryObj = DCountry.objects.filter(CountryCode=NewInputRefObj.CountryCode).get() I dont quite understand what its talking about because I am simply taking the countrycode from one object to use in a filter for another model object creation. See relevant models: class DCountry(models.Model): CountryCode = models.IntegerField(primary_key=True) Country = models.CharField(max_length=15) SPI = models.IntegerField() def __str__(self): return self.Country NewInputRefObj refers to a object made from the following model: class InputRef (models.Model): CountryCode = models.ForeignKey(DCountry, on_delete=models.CASCADE) Please point me in the right direction for what I should try here because i dont understand why its saying it has an issues with int()??? -
Django: Adding data to many to many fields
Everytime I try to add data to my many to many fields in Django, it just adds all the existing data from the relating table. I was researching possible solutions and I was thinking I could possibly overwrite the save method but there did not seem to be a clear way to do that. I need to be able to add a list of songs ids (our_id) to Playlist tracks and add multiple users to the Playlists users field. models.py from django.db import models from django.contrib.auth.models import User import uuid # Create your models here. class Track(models.Model): track_name = models.CharField(max_length=500) album_name = models.CharField(max_length=500) artist_name = models.CharField(max_length=500) album_pic = models.CharField(max_length=500) our_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) spotify_url = models.CharField(max_length=500, default=None) apple_url = models.CharField(max_length=500, default=None) def __str__(self): return self.track_name class Playlist(models.Model): playlist_name = models.CharField(max_length=500) tracks = models.ManyToManyField(Track, default=None) users = models.ManyToManyField(User, blank=True, default=None) def __str__(self): return self.playlist_name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) target = models.ForeignKey(User, related_name='followers', on_delete=models.CASCADE) follower = models.ForeignKey(User, related_name='targets', on_delete=models.CASCADE) playlists = models.ManyToManyField(Playlist, default=None) def __str__(self): return self.user.username views.py def add_to_playlist(request): # 1) get the track name that is selected # 2) Get the track ID for that track # 3) Add that ID for each of the playlists if … -
Check User Perms Django
I am trying to use Django's default permissions to only show the link to the blog post page if they have the blog post permissions. The wonderful Django documentation provides the following: Assuming you have an application with an app_label foo and a model named Bar, to test for basic permissions you should use: add: user.has_perm('foo.add_bar') change: user.has_perm('foo.change_bar') delete: user.has_perm('foo.delete_bar') view: user.has_perm('foo.view_bar') My app is named about Here is my model: # models.py class BlogPost(models.Model): title = models.CharField(max_length=120) description = models.TextField(max_length=250, null=True) image = models.ImageField(upload_to='blog/main') content = HTMLField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) draft = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.id}) Here is my HTML where I am trying to filter # base.html {% if user.has_perm('about.add_blogPost') %} <li {% if url_name == 'post' %}class="nav-item active"{% else %}class="nav-item"{% endif %}><a href="{% url 'post' %}" class="nav-link">Add Post</a></li> {% endif %} Whenever I follow it just as the documentation has written, I get: Could not parse the remainder: '('about.add_blogPost')' from 'user.has_perm('about.add_blogPost')' What am I doing wrong? -
Use Custom manager methods for data migrations in Django
I have a queryset class CustomQuerySet(models.query.QuerySet): def a(self): return 'something' class CustomQuerySetAllObjectsQuerySet(CustomQuerySet): def xyz(self): return 'something' class Custom(RemoteObjectQuerySet): all_objects = CustomQuerySetAllObjectsQuerySet.as_manager() I want to use the manager methods in my data migration. I read that we can use use_in_migrations = True to be set on Manager. But here since I am using as_manager(), will it still inherit this use_in_migrations. Also, how do I verify if I can use these manager methods for data migration. -
django queryset can not distinct the result with using Subquery?
I want to aggerate the work count of using the same video resource, and the user count that need distinct user. then I tried two method but got the different result. PROBLEM IS: the two qsets result is different. qset1 is correct, but qset2 is wrong that can not exclude the same users. MY QUESTION IS: what should I do if not to use RawSQL like qset1, and can get the right result. #models concerned class Video(models.Model): name = models.CharField(max_length=100, verbose_name=_('video name')) class Work(models.Model): video = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='works_of_video', verbose_name=_('video')) maker = models.ForeignKey(User, on_delete=models.CASCADE, related_name='works_of_maker', verbose_name=_('maker')) #rawsql for get_queryset() video_sql = u'''SELECT COUNT(*) AS "num" From (SELECT DISTINCT maker_id FROM "video_manage_work" U0 INNER JOIN "video_manage_demouser" U2 ON (U0."maker_id" = U2."id") WHERE (U0."video_id" = ("video_manage_video"."id") AND U2."gender" IN (%s)) )''' #views concerned def get_queryset(request): what_gender = (0, 1) vall = Video.object.all() works = Work.objects.filter(video=OuterRef('pk')).filter(maker__gender__in=what_gender) works_makers = works.values('maker','video').distinct() # the next annotate use RawSQL of video_sql qset1 = vall.annotate(works_num=Subquery(works.values('video').annotate(num=Count('*')).values('num'), output_field=IntegerField()))\ .annotate(makers_num=RawSQL(video_sql, (gender_str,))) # the next annotate use Subquery that try to distinct queryset that excluded the same users qset2 = vall.annotate(works_num=Subquery(works.values('video').annotate(num=Count('*')).values('num'), output_field=IntegerField()))\ .annotate(makers_num=Subquery(works_makers.values('video').annotate(num=Count('*')).values('num'), output_field=IntegerField())) return render(request, 'video_manage/video_data.html') ''' ######sql sentenc of qset2 created by django: SELECT "video_manage_video"."id", "video_manage_video"."name", (SELECT COUNT(*) AS "num" … -
Django: Unsure why I'm getting CSRF error
I'm writing a Django app and my registration page raises a 403 error: Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect. Here's the view: def register(request): form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') return render(request, "register.html", {'form' : form}) Here's the form in the relevant template: {% block content %} <form method="POST"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }} {{ field }} </p> {% endfor %} <button type="submit" class="button">Register</button> </form> {% endblock %} Some relevant facts: (1) No other pages on my site throw this error even though many require CSRF tokens. (2) The code I use to insert the CSRF token is the same in this template as in others (unless my triple-checking has failed me). (3) [probably relevant?] This is the only form I'm importing directly into views.py without modifying first in forms.py. So, two lines of views.py are: from django.contrib.auth.forms import UserCreationForm [...] from foo.forms import FooForm, FooBarForm, UploadFooForm Any and all help appreciated. I've tried most of what I think are the obvious debugging steps (removing the {% csrf_token %} line, reading the debug output and ensuring [I think] that those … -
Is there a way to rename a file that i just uploaded to the django admin to something specific every time I add a file?
I'm trying to add a way to rename my filefields in the django admin after i upload them. I already created my own action: class renameFile(admin.ModelAdmin): actions = ['rename_file'] def rename_file(modeladmin, request, queryset): #queryset.update() rename_file.short_description = "Rename selected file" Where I commented queryset.update() i'd like to replace that with a way to rename my file in the django admin. Something like when you select the file and click rename selected file and hit 'Go', it brings up a box with a field that i can write something to rename it. Is this even possible? Im not sure if the django admin is so flexible with those kind huge modifications. Any help would be very much appreciated!