Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to create a custom admin template url, getting errors Template errors & creating custom admin site errors
I am using this blog: https://medium.com/@adriennedomingus/adding-custom-views-or-templates-to-django-admin-740640cc6d42 Unable to make a custom template view in the Django Admin. I am getting django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet If I comment out the app in the settings.py, I get error admin.site.register(Template, TemplateAdmin) NameError: name 'Template' is not defined. Unable to do: 1) custom_admin_site.register & 2) models.Template is not found. Says there is no Template in models. I have this on admin.py: from django.contrib import admin from django.db import models class TemplateAdmin(admin.ModelAdmin): change_form_template = ‘admin/test_attempt.html’ admin.site.register(Template, TemplateAdmin) # Even the following doesnot work custom_site_admin.register(Template, TemplateAdmin) I have this on views.py: from django.shortcuts import render from django.http import HttpResponse from django.template import loader def preview(self, request, object_id): context = {} load_template = request.path.split('/')[-1] context = { **self.each_context(request), 'title': self.index_title, # Unable to get this app_list as well # 'app_list': app_list, } request.current_app = self.name template = loader.get_template('admin/' + load_template) return HttpResponse(template.render(context, request)) I have this on urls.py: from .views import preview class CustomAdminSite(admin.AdminSite): def get_urls(self): urls = super(CustomAdminSite, self).get_urls() custom_urls = [ path(r’^admin/test/(?P<object_id>\d+)$’, self.admin_view(preview), name=”preview”), ] return urls + custom_urls I have this on my apps.py: class CustomAdminSiteConfig(AdminConfig): default_site = 'batchexits.admin.CustomAdminSite' I have added this in my settings.py registered apps: 'batchexits.admin.CustomAdminSiteConfig', I have read this: … -
Django distinct method
I have this query in my views.py me = StudentsCoreValuesDescription.objects.filter(grading_Period = coreperiod)\ .values('id','Marking','Students_Enrollment_Records').distinct('Students_Enrollment_Records') .order_by('Students_Enrollment_Records') this is the result I just want that for every selection box, the display must be different ID's, To understand more, Please take a look to my admin site, and check the ID, the ID must be unique in the selection Box and the same as the admin site, to function properly when I update the data its looks like it only loop the result of distinct Student name this is my html {% for students in me %} <tr> <td colspan="4" class="names"><input type="hidden" value="{{students.id}}" name="student">{{students.Students_Enrollment_Records}}</td> <td colspan="2"> <select name="marking" > <option value="{{students.Marking.id}}" >{{students.id}}</option> {% for m in marking %} <option value="{{m.Marking}}" >{{m.Marking}}</option> {% endfor %} </select> </td> <td colspan="2"> <select name="marking"> <option value="{{students.Marking.id}}" >{{students.id}}</option> {% for m in marking %} <option value="{{m.Marking}}">{{m.Marking}}</option> {% endfor %} </select> </td> <td colspan="2"> <select name="marking"> <option value="{{students.Marking.id}}" >{{students.id}}</option> {% for m in marking %} <option value="{{m.Marking}}">{{m.Marking}}</option> {% endfor %} </select> </td> <td colspan="2"> <select name="marking"> <option value="{{students.Marking.id}}" >{{students.id}}</option> {% for m in marking %} <option value="{{m.Marking}}">{{m.Marking}}</option> {% endfor %} </select> </td> <td colspan="2"> <select name="marking"> <option value="{{students.Marking.id}}" >{{students.id}}</option> {% for m in marking %} <option value="{{m.Marking}}">{{m.Marking}}</option> {% endfor %} … -
"detail": "Method \"POST\" not allowed."
here i tried with custom user login in djangorestfulapi but i am getting error that "detail": "Method \"POST\" not allowed." . can anybody please explain where i am getting wrong? class LoginAPIView(APIView): def user_login(self,request,format=None): # context = RequestContext(request) if request.method == 'POST': user = ''' SELECT * FROM users ''' # Gather the username and password provided by the user. username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) print("auth",str(authenticate(username=username, password=password))) if user: # Is the account active? It could have been disabled. if user.is_active: login(request, user) return HttpResponseRedirect('/') else: return HttpResponse("xxx") else: # Bad login details were provided. So we can't log the user in. print ("Invalid login details: {0}, {1}".format(username, password)) return HttpResponse("Invalid login details supplied.") -
Django Makemigrations returns ModuleNotFoundError: with module name suffixed by 'django'
I've been following the Python Crash Course 2e tutorial. I encountered a problem with makemigrations function from Django chapter(18). I created first app using startapp, and then tried to call makemigrations. It returns ModuleNotFoundError but it gives an app name suffixed by 'django'. What I did was: python -m venv ll_env ll_env\Scripts\activate pip install django (installed asgiref-3.2.3 django-3.0.3 pytz-2019.3 sqlparse-0.3.1) django-admin startproject learning_log . python manage.py migrate python manage.py runserver This part runs smoothly, webserver works, everything is great. Then I opened another terminal(on project level), and typed: ll_env\Scripts\activate python manage.py startapp learning_logs <edited settings.py to include 'learning_logs'> python manage.py makemigrations learning_logs As a result makemigrations returns this traceback: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Admin\PycharmProjects\djangoproj\ll_env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Admin\PycharmProjects\djangoproj\ll_env\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\Admin\PycharmProjects\djangoproj\ll_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Admin\PycharmProjects\djangoproj\ll_env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Admin\PycharmProjects\djangoproj\ll_env\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen … -
Migration from version 1.8 to 2.2 css is ruined
""" Django settings for Train project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import django.conf.global_settings as DEFAULT_SETTINGS import os from .config import * from django.contrib.messages import constants as message_constants import smtplib BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) admins = [('TRAIN', 'Train@gmail.com')] email_use_tls = True email_host = 'smtp.gmail.com' email_port = 587 email_host_user = 'Train@gmail.com' email_host_password = '*****' default_from_email = email_host_user database_name = '******' database_user = '<DATABASE_USER>' database_pass = '<DATABASE_PASS>' database_host = 'localhost' database_port = '' static_root = '<STATIC_PATH>' media_root = 'mediafiles' # the path where all the uploaded files are stored allowed_hosts = ['localhost', '127.0.0.1', 'train.com', '10.103.10.217'] debug = True search_engine = 'solr' email_cronjob = False db_index_cronjob = True db_workers = 4 MEDIA_ROOT = 'mediafiles' MEDIA_URL = '/mediafiles/' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '******************************' PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__)) SITE_ROOT = os.path.dirname(PROJECT_ROOT) FILE_UPLOAD_TEMP_DIR = os.path.join(MEDIA_ROOT, 'temp') # directory for holding temporary files (database files for upload) # print('FILE_UPLOAD_TEMP_DIR: ' + FILE_UPLOAD_TEMP_DIR) SITE_ID = 1 # SECURITY WARNING: don't run with debug turned on in … -
What's the best database model for product with different sizes and quantity
I have got a table with products that are supposed to have different sizes (S,M,L,XL) and I wanted to have a quantity for every size. Lets say that a have a bike with different frame sizes, and there's a quantity for each size. What would be the best model to get this to work? I am planning to lower the quantity(-1), when the bike is added to the basket. Here's what I currently got in my Models: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) label = models.ManyToManyField(Label, blank=True) slug = models.SlugField(unique=True) description = models.TextField() class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) category = models.ManyToManyField(Category, blank=True) image = models.ImageField(upload_to='bikes') brand = models.ManyToManyField(Brand) -
Django Social auth add new oauth2 user to a group
I have successfully setup oauth2 for Google using the social auth from the website below. https://python-social-auth.readthedocs.io/en/latest/configuration/django.html The system creates a user in the User database visible from admin console. What i am unable to do is add the newly authenticated user to a group called "Guardians". I know this code will do the job but not sure which module to add it in. from django.contrib.auth.models import Group, User user.groups.add(Group.objects.get(name='Guardians')) Please help -
How do you pre-populate a Django form from a model
I have a Django form that is is generated from a model model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) telephone = models.CharField(max_length=15, blank=True) email_address = models.CharField(max_length=30, blank=True) date_of_birth = models.DateField(null=True, blank=True) How can I pre-populate the form when I select user? -
Dynamically filter queryset ModelMultipleChoiceField
I have a ModelMultipleChoiceField named questions which needs a dynamically created queryset. For doing this I would expect to first pass queryset=None then update it in the __init__ method but this returns: AttributeError: 'NoneType' object has no attribute 'count' Forms.py: class BaseQuizCreateForm(forms.ModelForm): title = forms.CharField() receiver = forms.ModelMultipleChoiceField( queryset=None, required=True, widget=forms.CheckboxSelectMultiple,) questions = forms.ModelMultipleChoiceField( queryset=None, # AttributeError 'NoneType' object has no attribute 'count' required=False, widget=forms.CheckboxSelectMultiple,) def __init__(self, *args, **kwargs): self.company = (kwargs.pop('company', None)) super(BaseQuizCreateForm, self).__init__(*args, **kwargs) self.fields['receiver'].queryset = EmployeeType.objects.filter(company=self.company) if self.instance.pk: self.fields['questions'].initial = self.instance.question_set.filter(category=2).select_subclasses() # I need this dynamically created Forms.py which does not filter: class BaseQuizCreateForm(forms.ModelForm): title = forms.CharField() receiver = forms.ModelMultipleChoiceField( queryset=None, required=True, widget=forms.CheckboxSelectMultiple,) questions = forms.ModelMultipleChoiceField( queryset=Question.objects.all().select_subclasses(), required=False, widget=forms.CheckboxSelectMultiple,) def __init__(self, *args, **kwargs): self.company = (kwargs.pop('company', None)) super(BaseQuizCreateForm, self).__init__(*args, **kwargs) self.fields['receiver'].queryset = EmployeeType.objects.filter(company=self.company) if self.instance.pk: self.fields['questions'].initial = self.instance.question_set.filter(category=2).select_subclasses() # I need this dynamically created -
Django sort form fields from two models
I have extended the Django user model with some extra fields models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) telephone = models.CharField(max_length=15, blank=True) email_address = models.CharField(max_length=30, blank=True) date_of_birth = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('telephone', 'email_address', 'date_of_birth') widgets = { 'date_of_birth': forms.DateInput(attrs={'type': 'date'}), } views.py def response_form(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): profile, created = Profile.objects.get_or_create(user=request.user) user_form.save() profile_form.save() messages.success(request, ('Your profile was successfully updated!')) date_of_birth = profile_form.cleaned_data['date_of_birth'] user = profile_form.cleaned_data['user'] context = { 'user': user, 'date_of_birth': date_of_birth } template = loader.get_template('thank_you.html') return HttpResponse(template.render(context, request)) else: messages.error(request, ('Please correct the error below.')) else: user_form = UserForm() profile_form = ProfileForm() return render(request, 'response_form.html', {'user_form': user_form, 'profile_form': profile_form}) When the template is loaded it places the user fields above the profile fields. How can I place the User dropbox above the First name field? -
Django, models form Not saving data in database
I am new to django, I created a form to save Data into my database but it not working corectly, I got no error but data is not sent in database. Thanks for helping! views.py @login_required() def data(request): if request.POST == "POST": form = CreatePost(request.POST) if form.is_valid(): form.instance.author = request.user form.save() return redirect(data) else: form = CreatePost() context = { "form": form } return render(request, "sms/data.html", context) forms.py class CreatePost(forms.ModelForm): class Meta: model = Post fields = ["title", "content"] models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title -
how to register users for tests?
Can you help me? I dont know django-ajax well, also I am new in django. I want to register user to Mock test, so I tried to use below codes. I am not able to realise what my mistakes are. model.py class MockTest(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE) bio = models.TextField(null= True, blank=True) is_free = models.BooleanField() fee = models.DecimalField(max_digits=10, decimal_places=2) time_created = models.DateTimeField(auto_now=False,auto_now_add=True) time_start = models.DateField(auto_now=False, auto_now_add=False, default='') speak_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) registerations = models.ManyToManyField(User, blank=True, null=True, related_name='registerations') def save(self, *args, **kwargs): # new if not self.slug: self.slug = slugify(self.name) return super().save(*args, **kwargs) def __str__(self): return self.name def get_absolute_url(self): return reverse("teacher:mock_view", kwargs={"slug": self.slug}) def total_registers(self): return self.registerations.count() def is_registered(self,request): return self.registerations.filter(id=request.user.id).exists() views.py def register(request): if request.method == 'POST': user = request.user slug = request.POST.get('slug', None) mock = get_object_or_404(MockTest, slug=slug) if mock.registerations.filter(id=user.id).exists(): massage = "You are already registered" else: mock.registerations.add(user) massage = "succes" cxt = {'total_registers': mock.total_registers, 'massage':massage} return HttpResponse(json.dumps(cxt), content_type='application/json') urls.py path('register/', register, name='register') html <input type="button" id="register" class="" name="{{ mock.slug }}" value="Register" /> <script> $('#register').click(function(){ $.ajax({ type: "POST", url: "{% url 'student:register' %}", data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(response) { alert(response.message); alert('Registered people now ' + response.total_registers); … -
Python Django User Membership
I am making an online education website (similar to Lynda.com). I just need the code that enables me to grant access - manually - to users who send me cash money. I'm writing my code using Python Django. Would you help me do it. Thank you. -
How to transfer the data of Arduino to Django app remotely
I'm building a project on Django with Arduino devices connected to it. Do I need an MQTT to transfer data from arduino to django app? or I can use arduino itself to transfer data to django app and btw the arduino is almost 50 meters away from the computer where the django app runs. I'm using Postgresql as Database. -
Django: how to create custom login page with token bases in DjangoRestAPI?
how to create custom login page with token bases in DjangoRestAPI? -
can't send signals to a specific user
i'm sending notifications to a user via django notifications. And i have username regex working on the html so anyone comments with @username it will post and the html is linkable so click on the @username it will take him to the username profile page. Now i am using django signals to match the username and print out the username. but when i use notify to send the notification. it does not work. models.py: class Comment(models.Model): post = models.ForeignKey(post, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE) reply = models.ForeignKey('Comment', null=True, related_name='replies', on_delete=models.CASCADE) content = models.TextField() image = models.ImageField(upload_to='comments-pics', null=True, blank=True) voice_record = models.FileField(upload_to='voice-comments', null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__ (self): return '{}.{}'.format(self.post.title, str(self.user.username)) def save(self, *args, **kwargs): super(Comment, self).save(*args, **kwargs) def Comment_save_receiver(sender, instance, created, *args,**kwargs): if created and not instance.parent: user_regex = r'@(?P<username>[\w.@+-]+)' m = re.search(user_regex, instance.content) if m: try: recipient = User.objects.get(username=m.group('username')) except (User.DoesNotExist, User.MultipleObjectsReturned): pass else: notify.send(instance.user, recipient=recipient, actor=instance.user, verb='mention you in a post', target=instance, nf_type='tagged_by_one_user') post_save.connect(Comment_save_receiver, sender=post) -
Django Rest Framework: Pickle Response
What I'm trying to do is build a custom version of cache_page where I have more control over the cache key, but I'm getting stuck with even the basic caching of my response: from django.core.cache import cache class BaseViewSet(viewsets.GenericViewSet): queryset = models.Items.objects.all() def get_queryset(self): return models.Items.objects.all() def list(self, request, **kwargs): response = Response({}) cache.set('test', response, 10) return response Where the relevant parts of my settings.py are setup as: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', ], 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning' } CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": f"redis://127.0.0.1:6729/1", }, } When I try to call the endpoint I get: django.template.response.ContentNotRenderedError: The response content must be rendered before it can be pickled. Then if I change the line to: cache.set('test', response.render(), 10) I get: AssertionError: .accepted_renderer not set on Response Despite the fact that the API call itself works fine without the caching. cache_page actually works fine, so I know it's possible to cache the response, but I can't figure out what I'm missing. -
DRF how can I return only the first serialized object to the view?
in DRF, is there any way to get a single nested image to show up in a view. In my example you can see that there are 2 photos listed. What would be the best solution to retrieve and display just that first photo? This view would be for a list of houses, and I don't want every pic to be displayed, as there could be some users uploading 30+ photos. "url": "http://127.0.0.1:8000/api/v1/listings/1/", "address": "8753 sherwood dr apt 111", "image_set": [ { "photo": "http://127.0.0.1:8000/media/listing_images/front-view.png" }, { "photo": "http://127.0.0.1:8000/media/listing_images/image34453.png } ] }, class ImageSerializerForListingDetail(serializers.ModelSerializer): photo = serializers.ImageField(use_url=True, allow_empty_file=True) class Meta: model = Image fields = ('photo', ) def get_image_url(self, listing): return listing.photo.url class ListingListSerializer(serializers.HyperlinkedModelSerializer): photo = ImageSerializerForListingDetail(many=True, required=False) class Meta: model = Listing fields = ('url', 'address', 'photo', ) class ListingViewSet(viewsets.ModelViewSet): queryset = Listing.objects.all().order_by('id') permission_classes = [IsOwnerOrReadOnly, ] serializer_classes = { 'list': ListingListSerializer, 'retrieve': ListingSerializer } default_serializer_class = ListingSerializer def get_serializer_class(self): return self.serializer_classes.get(self.action, self.default_serializer_class) def create(self, request, *args, **kwargs): serializer = ListingSerializer(data=request.data, files=request.FILES) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
how do I print queryset dictonary in django template
How do I print the below for loop (last for loop) which is printing all prods in my template? I tried to find answers but I'm nowhere close to finding one. Please help me solve this issue. allProds = [] catalogs = Catalog.objects.all().distinct().order_by('name') categories = Category.objects.all().distinct().order_by('name') for catalog in catalogs: allProds.append(catalog) for category in categories.filter(catalog_name=catalog.id): allProds.append(category) products = Product.objects.values('name','image') .filter(category_name=category) allProds.append(products) for p in range(len(allProds)): print(allProds[p]) -
How can automatically Increase the serial number when user register and i want to dsable some content after some seats filled?
How will i get increment in serial number instantly after new register enter ? How should one disable the registration automatically when the seats are filled ? Now I want to increase the number by 1 for each register. Forms.py from django import forms from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User CHOICES = [ ('',''), ('CT', 'Computer Technology'), ('BCA', 'Bachelor of Computer Application'), ('SS', 'Software Systems'), ('CS','Computer Science'), ('IT','Information Technology'), ('DA','Data Analytics'), ] COURSE = [ ('',''), ('Python','Python'), ('Java','Java'), ('C++','C++'), ] class Registerform(UserCreationForm): username = forms.CharField(label="Roll No",help_text="Enter Valid RollNo") name = forms.CharField(label="Candidate Name", max_length=150) dob = forms.DateField(label="Date of Birth",help_text="MM/DD/YY") email = forms.EmailField(help_text="Enter valid Mail") department=forms.CharField( label="Department", widget=forms.Select(choices=CHOICES)) edc = forms.CharField( label="EDC", widget=forms.Select(choices=COURSE)) password1 = None password2 = None class Meta: model = User fields = ["username","name", "dob", "email","department","edc"] Models.py from django.db import models from django.utils.translation import gettext as _ # Create your models here. class listing(models.Model): username = models.CharField(max_length=150) name = models.CharField(max_length=150) dob = models.DateField() email = models.EmailField() department=models.CharField(max_length=150 ) edc = models.CharField(max_length=300,default="") password1=None password2=None def __str__(self): return self.username I want to show my serial number(It want to incremented automatically) here how can I do this? The serial number also want to store in … -
Need some explanation of django code for model manager
I am following a Django project found on Github. Almost understand everything apart from following model manager. Especially the get_releted_products method. Could you please describe how it will work to get the related product from categories. It will be nice if you also send some documentation that can explain this code as well as the StackOverflow forum. class ProductManager(models.Manager): def all(self,**kwargs): #active return self.filter(active=True,**kwargs) def get_related_products(self,instance): qs1 = self.all().filter(categories__in=instance.categories.all()) qs2 = self.all().filter(default=instance.default) return (qs1 | qs2).exclude(id=instance.id).distinct() class Product(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=500,blank=True,null=True) price = models.PositiveIntegerField() active = models.BooleanField(default=True) categories = models.ManyToManyField('Category',blank=True) default = models.ForeignKey('Category',related_name='default_category',blank=True, null=True,on_delete=models.CASCADE) slug = models.SlugField(max_length=48) objects = ProductManager() -
Django - Correct method of consuming my own REST API internally in the views.py?
I created a Django REST API using serializers, viewsets and routers. My end points looks something like this: http://www.website.com/api/items http://www.website.com/api/items/available serializer.py (omitting imports) class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' viewsets.py (omitting imports) class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer @action(methods=['GET'], detail=False) def most_expensive(self, request): query = self.get_queryset().order_by('price').last() serialized = self.serializer_class(query) return Response(serialized.data) Now I want to able to access this API from my views.py to render the HTML with the available items: This is the way im doing it right now: views.py (omitting imports) class ProductListView(View): template = 'store/product_list.html' def get(self, request): items = requests.get('http://127.0.0.1:8000/api/items/available') context = {'items': items} return render(request, self.template, context=context) Using the requests modules I have a couple of concerns, after measuring I noticed there is a 0.015 second delay for that request to go through and if I ever change the API endpoint I would have to adjust it here since its hard coded. I can get my items using: Item.objects.filter(available=True) Which gives me the result pretty much instantly but I'm writing all the queries twice (once in my API and once in my views.py) Is there a better way of doing this like calling the viewset class directly and getting … -
Python: algorithm deos not works
I want to extract data of django.po file (internationalization) in xls (to discuss with non IT project manager) so first, I want to code a function that will extract lines of django.po in a list of tuples (don't know if it is the easiest way but...) and after, I will use xlwt export data in xls files (each tuple will be written in a line) translation.txt #: .\myproject\settings.py:1 #: .\myproject\settings.py:2 msgid "English" msgstr "Anglais" #: .\myproject\settings.py:3 msgid "French" msgstr "Français" expected result : liste of 2 tuples [ (#: .\myproject\settings.py:1,#: .\myproject\settings.py:2,msgid "English",msgstr "Anglais"), (#: .\myproject\settings.py:3,msgid "French",msgstr "Français"), ] current result : second tuple missing [ (#: .\myproject\settings.py:1,#: .\myproject\settings.py:2,msgid "English",msgstr "Anglais") ] function def translation(): fichier_traduction = r"C:\Users\translation.txt" file = open(fichier_traduction, newline='', encoding='utf-8') reader = csv.reader(file) liste = [] tuple = () for row in reader: if len(row) > 0: tuple = tuple + (row[0],) else: liste.append(tuple) tuple = () return liste -
Dajngo-alluth override signup method in customform
i have a trouble with django-allauth. I create my customform and it works fine, but now i need to override the signup i tried this: class CustomSignupForm(SignupForm): password1 = SetPasswordField(label="Password") password2 = PasswordField(label="Conferma Password") first_name = forms.CharField(max_length=30, label='Nome') last_name = forms.CharField(max_length=30, label='Cognome') data_di_nascita = forms.CharField(max_length=30, label='Data di nascita',widget=forms.TextInput(attrs={'placeholder': 'gg/mm/aaaa'})) citta = forms.CharField(max_length=30, label='Città', required=False) regione = forms.CharField(max_length=30, label='Regione', required=False) stato = CountryField(blank_label='Nazione',blank=True).formfield() termini_e_condizioni = forms.BooleanField(label='termini_e_condizioni',widget=forms.CheckboxInput(attrs={'class':'your_class'})) privacy = forms.BooleanField(label='privacy',widget=forms.CheckboxInput(attrs={'class':'your_class'}), required=False) newsletter = forms.BooleanField(label='newsletter',widget=forms.CheckboxInput(attrs={'class':'your_class'}), required=False) def __init__(self, *args, **kwargs): super(CustomSignupForm, self).__init__(*args, **kwargs) self.fields['password1'].label = "Password" self.fields['password2'].label = "Conferma Password" self.fields['password1'].widget = PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}) self.fields['password2'].widget = PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Conferma Password'}) for field in self.fields: help_text = self.fields[field].help_text self.fields[field].help_text = None if help_text != '': self.fields[field].widget.attrs.update({'class':'has-popover', 'data-content':help_text, 'data-placement':'right', 'data-container':'body'}) def confirm_password(self): print('entered confirm_password') if ("password1" in self.cleaned_data and "password2" in self.cleaned_data): print('password fields found') if self.cleaned_data['password1'] != self.cleaned_data['password2']: print('le password non corrispondono') raise forms.ValidationError(_("You must type the same password" " each time.")) print('passwords equal') return self.cleaned_data["password1"] else: print('passwords not found in form') raise forms.ValidationError(_("Password not found in form")) def signup(self, request, user): print("-------------------------------------------------------------------OK----------------------------------------------") user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() userpost=User.objects.get(username=self.cleaned_data['username']) userpost.personal_data.birthdate = self.cleaned_data['data_di_nascita'] userpost.personal_data.country = self.cleaned_data['stato'] userpost.personal_data.subcountry = self.cleaned_data['regione'] userpost.personal_data.city = self.cleaned_data['citta'] userpost.personal_data.created = timezone.now() userpost.personal_data.save() userpost.markeringpreference.subscribed=self.cleaned_data['newsletter'] userpost.newsletterpreference.subscribed=self.cleaned_data['newsletter'] userpost.markeringpreference.save() userpost.newsletterpreference.save() … -
How to set boolean fields of all but one from the multiple Django formset rows during save
I am updating multiple records from a single form using Django inline formset factory. Multiple number of rows of data are expected to be created by users at once. My model is: class Tariff(models.Model): tariff_item = models.AutoField(primary_key=True, verbose_name='Tariff Item') eff_date = models.DateField(null=True, verbose_name='Eff date') tariff_rate = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True, default=0.00, ...) tariff_is_past = models.BooleanField(default=False) As stated above there can be more than one formset row when the user saves it. The only caveat being: All the rows with data MUST be marked with BOOLEAN FIELD "tariff_is_past" to True, except the last. Presently the boolean fields are being marked manually. As the rows are as yet not part of the table I can not run a query on the rows and set the boolean field to True. Can the scenario be addressed? Can I set Boolean field "tariff_is_past" for all but the last (ordered on the date field "eff_date") row?