Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add fields in Serializer dynamically
I have a View in which I receive the request and it returns the serialized data views.py class AllotmentReportsView(APIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request): sfields = request.GET['sfields'] #I can get the fields in params serializer = AllotReportSerializer(items, many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) serializer.py class AllotReportSerializer(serializers.ModelSerializer): send_from_warehouse = serializers.SlugRelatedField(read_only=True, slug_field='name') transport_by = serializers.SlugRelatedField(read_only=True, slug_field='name') sales_order = AllotSOSerializer(many=False) flows = AllotFlowsSerializer(many=True) class Meta: model = Allotment fields = ( 'transaction_no', 'dispatch_date', 'sales_order', 'is_delivered', 'send_from_warehouse', 'transport_by', 'flows', ) Instead of defining the fields in serializer can I pass the fields dynamically from the view sfields and pass them to the serializer ? -
html table too wide on iPhone devices
First of all let me say that this is my first web application, I'm not familiar with html and css so be patient if I write nonsense. Using Django, I created a web application to manage the reservations for tennis courts. For each court, there is a page that show the days of current month into a "calendar" created using a table element. In each cell there is a button that allow to see the reservations registered for that day. Everything works perfectly on PC and Android devices, but the problem cums when I browse my website on Apple devices (I tried 2 different models of IPhone). In the pictures below you can see that the table resizes perfectly on the Android device, while it is too large on the iPhone. Searching on internet for some tips I see that someone suggest to properly manage the "viewport" into the html of the page, and this is what I've done: <meta name="viewport" content="height=device-height, width=device-width, initial-scale=1"> Someone suggest to apply different scale transformations to resize the objects in page for small screens. I tried also this solution, it works perfectly on Android devices but nothing to do on IPhone. Below what I've … -
Get data from django database model
I have a django model, PhoneNumberVerification. It has two columns: phone number, and code. I want to be able to get the code if I am given a phone number. Essentially, search the table for which row has the phone number as my phone number, and fetch the code for that given row. I could write SQL for this, but I do not know how to execute that to fetch data in django models, and I was wondering if there was a better non-sql way to do this. My model: class PhoneNumberVerification(models.Model): phone_number = models.TextField(max_length = 20, blank = False, unique = True) code = models.CharField(max_length = 8, blank = False) What I want: from .models import PhoneNumberVerification def get_code(phone_number): # do some stuff return code -
What django/python tools should I use to draw objects [closed]
I want to create a django app that will use user input to draw objects. The idea is it will look like a very basic furniture planner. User provides room dimensions -> app displays simple rectangle. User inputs location of window -> app displays small rectangle at the location inside the room. User chooses furniture from the list and writes where should it be placed -> another rectangle shows on the graph. It should be very simple, no bells and whistles. I'm trying to figure out what technologies should I use. I am familiar with Django well enough to stick to it but what tools should I utilize for drawing? For now I'm thinking about matplotlib, what do you think? -
AWS Stepfunction GET Request 404's for object just created by POST
I have a webapp that has a POST request to create an object in the DB. After this, a post_save signal is used to kickoff an AWS step function. This stepfunction then tries to do a GET for the object that was just created. Every single time it seems to fail, and I'm having a hell of a time debugging since I can't just use pdb for something that only runs when deployed onto AWS. Is there something I'm missing here? Why am I getting this race condition or eventual consistency issue? What is the best way to ensure that the GET will find the object that was created by the POST? The FileRequest View contains the post_save hook that kicks off the AWS Step function from django.db import transaction from django.db.models.signals import post_save from core_api.models.file_request import FileRequest import boto3 ... ... ... @receiver(post_save, sender=FileRequest, dispatch_uid="file_request_unique_id") def _stepfunction_handler(sender: Type=FileRequest], instance:=FileRequest, created: bool, **kwargs) -> None: arn = "blablabla" file_id = instance.id client = boto3.client("stepfunctions") payload = { "input": json.dumps( {"input": {"file_request_id": file_id}} ), "stateMachineArn": arn } def execute_sfn(): client.start_execution(**payload) transaction.on_commit(execute_sfn) # I figured this would start the sfn only after the object is saved, but it does not seem to … -
Is there a way to selected field to search in Django admin?
Is there a good way to have a tick list under the search field which would allow user to select which field specifically to search? Or do I have to manually implement it? -
Overriding the get_queryset method in Django Admin
Please tell me why this design might not work: class FastCountQuerySet(QuerySet): def count(self): pass @admin.register(ItemOOSLog) class ItemOOSLogAdmin(ImportExportModelAdmin): def get_queryset(self, request): qs = super(ItemOOSLogAdmin, self).get_queryset(request) return qs._chain(__class__=FastCountQuerySet) I need to use my FastCountQuerySet class instead of QuerySet when using the get_queryset method. I found that this can be implemented through qs._chain(__class__=FastCountQuerySet), but it doesn't work, the regular QuerySet is used. -
how to Show like exist or not in serializer based on request.data in django
i have a post model and like model with ForeignKey. in API user will give the user session id . i want to show the user liked a post or not based on the session id in when i list all post . for example . when we open instagram we can as user which post we liked or not in the heart icon . models.py class Post(models.Model): title = models.CharField(max_length=150) image = models.FileField( upload_to="post/",) class PostLike(models.Model): like = models.CharField(max_length=10) user = models.ForeignKey(Customer,on_delete=models.CASCADE,related_name='post_likes') post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='likes') views.py @api_view(["POST"]) def post(request): if request.data != {}: session_id = request.data["session_id"] user = Customer.objects.filter(session_id=session_id) if user.count() != 0: posts = Post.objects.all() like_exist = PostLike.objects.filter(user = user).exists() serializer = PostSerializer(posts, many=True,context= {"like_exist":like_exist) return Custom_Response(request, news_serializer.data) serializer.py class PostSerializer(serializers.ModelSerializer): like_exist = serializers.SerializerMethodField("like_exist_") class Meta: model = News fields = ["title","image","like_exist"] def like_exist_(self,obj): is_liked = self.context.get("like_exist") return is_liked db post id title image 1 1st "" 2 2nd "" post_like id like post_id user_id 1 1 1 1 2 1 2 1 3 1 1 2 if api input session_id 10000 ,it's customer 1 so i want to show like this API "data": [ { "id": 1, "title": "trend post 1", "like_exist":true , }, { … -
Django save() method doesn't save in upload_to function
I have a issue in my code. I have a user model and it has a profile_image field with ImageField. I defined a profileImageRoot() function and equalized it to upload_to argument of ImageField. I have profile_image_count IntegerField and it increases 1 unit when image is uploaded in profileImageRoot(). I try save the value of profile_image_count on my database but save() method doesn't save. My source code: User model: class User(AbstractBaseUser): username = models.CharField(max_length=20, unique=True, verbose_name="Username") email = models.EmailField(unique=True, verbose_name="Email", help_text="Email you actively use") first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) date_of_birth = models.DateField(blank=False) date_created = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) profile_image = models.ImageField(upload_to=profileImageRoot) profile_image_count = models.IntegerField(default=0) spent_money = models.FloatField(default=0) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ('username', 'first_name', 'last_name', 'date_of_birth') def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True def get_full_name(self): return f"{self.first_name} {self.last_name}" def is_birthday(self): if timesince(self.date_of_birth, datetime.today()) == datetime(day=0, month=0): return True else: return False def verify(self): self.is_verified = True def __str__(self): return self.get_full_name() profileImageRoot(): def profileImageRoot(instance, filename): user = User.objects.get(pk=instance.pk) ext = filename.split(".")[-1] user.profile_image_count += 1 print(user.profile_image_count) user.save() return f"{user.username}/profile_image/{user.profile_image_count}.{ext}" -
how to access the json data sended as a response in django on the frontend
I have a contact page I want the person can send me contact request if he is validating email first so for that i disable the submit button and added a button to send otp that works fine def contact_otp(request): if request.method=="POST": body = json.loads(request.body) email = body['email'] otp = OTP.objects.create() otp.save() body = f"The Otp To conferm your email is {otp.token}" send_mail( 'verification', body, f'{EMAIL_HOST_USER}', [f'{email}'], fail_silently=False ) data = { "data":f"{otp.token}" } return JsonResponse(data) after sending the opt i want to verify the otp in frontend and enable the submit button once it is very but sadly when i try access the data it says undefined .then((response) => response.json()) .then((data) => { console.log(data) }) i have used this same kind of script in payment where after success payment it get redirected now i had to access the data in the frontend so that i can verifyy it -
request.GET.get(' ') returns None
I have the following URL: http://127.0.0.1:8000/application_form/Network%20Adminstrator/ The URL is generated with: path('application_form/<str:job_title>/', views.ApplicationForm.as_view(), name='application_form') I keep on trying get_data = self.request.GET.get('job_title') and am expecting to get Network Adminstrator but instead it returns None My urls.py: urlpatterns = [ path('application_form/<str:job_title>/', views.ApplicationForm.as_view(), name='application_form'), ] views.py: class ApplicationForm(CreateView): model = Requirements form_class = ApplicationForm template_name = 'requirements/job_specs.html' # Passes the request object to forms def get_form_kwargs(self): kwargs = super(ApplicationForm, self).get_form_kwargs() kwargs['request'] = self.request return kwargs forms.py: class ApplicationForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(ApplicationForm, self).__init__(*args, **kwargs) get_data = self.request.GET.get('job_title') print(get_data) dic = {'job_title__job_title': get_data} self.fields['qualifications'].queryset = Requirements.objects.get(**dic) class Meta: model = Applicants fields = ['email', 'qualifications'] email = forms.EmailField(label='', max_length=100, required=True, widget=forms.TextInput( attrs={'class': 'form-group form-control input-lg ', 'placeholder': 'Email'}), ) qualifications = forms.ModelMultipleChoiceField(queryset=None, widget=forms.CheckboxSelectMultiple) Any thoughts or ideas? I am still a bit new to programing in Django and I would really appreciate your time and knowledge. -
django.request logger to find "Synchronous middleware … adapted" for Django async
I've set up a trial async view in my Django app but the view continues to render in sync. As per Django docs, I'm checking that my Middleware isn't causing the issue: Middleware can be built to support both sync and async contexts. Some of Django’s middleware is built like this, but not all. To see what middleware Django has to adapt, you can turn on debug logging for the django.request logger and look for log messages about “Synchronous middleware … adapted”. There's already been a Stack Overflow question to elaborate on using the logger to find which middleware is prevent async from working, but the answer is incomplete. This is what I have in my settings, as per the above Stack Overflow answer: settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django.request': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'propagate': False, }, }, } And my view: views.py from time import sleep import asyncio import logging logger = logging.getLogger("info") # --- Views from django.db import transaction @transaction.non_atomic_requests async def async0(request): #loop = asyncio.get_event_loop() #loop.create_task(lets_sleep()) await asyncio.sleep(1) logger.debug('in index') logger.info('something') return HttpResponse("Hello, async Django!") I've restarted the built in Django server, … -
Using RabbitMQ with Celery in Django post_save
I am applying asynchronous task handling using Celery on my Django Project. My project's logic:, from frontend side, there is a table with rows each having an upload button. User clicks on it and a payload is sent to backend containing a url that contains a file. File is recieved in django views. And saved into database, table Run. Immediately object is saved a post_save signal is triggered to run a celery task. The task to be performed is, fetch a list of runs with specific status. For each run, perform a task of downloading the file. I would like to perform this asynchronously in case there is more than one run. Keeping in mind user can click upload for more than one row from frontend. I am setting up RabbitMQ as my broker. I have rabbitMQ installed and running. I have set the CELERY_BROKER_URL='amqp://localhost' too in settings.py. I am a little lost on what I should do next in my configurations, could I get some guidance. I think I need to configure celery worker on my tasks. Below is my code so far : views.py #view that saves to database class RunsUploadView(APIView): serializer_class = RunsURLSerializer def post(self, request, *args, … -
Error: djdt is not defined how to solve this?
I just upgraded django 2.1 to django 3.0.14: then I got this error ModuleNotFoundError: No module named 'django.utils.lru_cache' in django-debug-toolbar, so I upgraded my django-debug-toolbar 1.9.1 to django-debug-toolbar 2.0 and run python manage.py collectstatic and clear cache from browser after that above error is resolved but debug-toolbar is not showing and in console got the error: toolbar.js:306 Uncaught ReferenceError: djdt is not defined how to resolve this error? I already have:: INSTALLED_APPS = [ # ... "debug_toolbar", # ... ] STATIC_URL = "static/" from django.urls import include, path INTERNAL_IPS = [ # ... "127.0.0.1", # ... ] urlpatterns = [ # ... path('__debug__/', include('debug_toolbar.urls')), ] -
Django: TemplateSyntaxError-Could not parse the remainder
My template gets a queryset named qs.value sent from the views.py, I can display the value using {{qs.value}} anywhere in the template, but using it in an if statement raises an error. {% if {{qs.value}} > 0 %} <!--do something--> <h3 class="text-success">{{qs.value}}</h3> {% else %} <!--do something else--> <a href=""><button class="btn btn-primary">Else</button></a> {% endif %} The error: Could not parse the remainder: '{{qs.value}}' from '{{qs.value}}' What am I doing wrong? -
How can add auto complte filter django?
adding auto complte filter for django models using django filter? django-admin-autocomplete-filter installed, and may i know how to write code ? my filter class PlayerFilter(django_filters.FilterSet): name = django_filters.ModelChoiceFilter(label='Name' ,queryset=Player.objects.all()) team__name = django_filters.ModelChoiceFilter(label='Team',queryset=Team.objects.all() ) team__game__name = django_filters.ModelChoiceFilter(label='Game',queryset=Game.objects.all() ) team__company__name = django_filters.ModelChoiceFilter(label='Company',queryset=Company.objects.all()) class Meta: model = Player fields =['name','team__name','team__game__name','team__company__name'] -
TypeError: django.db.models.manager.BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method() got multiple values
I am facing a problem while giving PUT request. url is : http://127.0.0.1:8000/api/v1/products/products/product-slug-9/ the error is :TypeError: django.db.models.manager.BaseManager._get_queryset_methods..create_method..manager_method() got multiple values for keyword argument 'product' models.py class Product(models.Model): """ This is The Product table contining all product items. """ name = models.CharField(max_length=255) title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) brand = models.ForeignKey(to='brands.BrandProfile', on_delete=models.DO_NOTHING, related_name='brand_product') # brand=models.CharField(max_length=30) category = models.ForeignKey( to='products.Category', on_delete=models.DO_NOTHING) # sizes = ArrayField( # models.CharField(max_length=10), # ) # colors = ArrayField( # models.CharField(max_length=56) # ) is_available = models.BooleanField(default=True) market_price = models.IntegerField() selling_price = models.IntegerField() description = models.TextField() # stock_status , visibility_status # product won't delete if category deleted, we have to do it manually. visiblity = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created_at',) verbose_name = "Product" verbose_name_plural = "Products" def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(str(self.name.lower()) + str(uuid.uuid4())) return super().save(*args, **kwargs) def __str__(self): return str(self.title) @property def discount_percent(self): if self.selling_price: discount_percent = 100 - \ (self.selling_price * 100) / self.market_price return int(discount_percent) return 0 class ProductImage(models.Model): """ The Product Image Table """ product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='product_images') image = models.ImageField( upload_to=brand_product_image_file_path, blank=False, null=False) product_color = models.CharField(max_length=56) alt_text = models.CharField(max_length=24) is_featured = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = … -
Form not posting data to database in django
I have a django model form to register a new user into Users table in Django. I have selected fields which I want to use. The form is showing correctly on the html page but the problem is when I submit the form, the data is not saved in the database. I tried to get the field values using name = request.POST['field'] and use print(name) all the data is being printed on the console. Below is my code forms.py class UserForm(UserCreationForm): first_name = forms.CharField(required=False, label='First Name', widget=forms.TextInput( attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'})) last_name = forms.CharField(required=False, label='Last Name', widget=forms.TextInput( attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'})) email = forms.EmailField(required=False, label='Email Address', widget=forms.TextInput( attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'})) username = forms.EmailField(required=False, label='Username', widget=forms.TextInput( attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'})) password = forms.EmailField(required=False, label='Password', widget=forms.PasswordInput( attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'})) password1 = forms.EmailField(required=False, label='Confirm password', widget=forms.PasswordInput( attrs={'style': 'font-size:medium', 'class': 'form-control form-control-sm'})) class Meta: model = User fields = ('first_name', 'last_name', 'email', 'username', 'password','password1') My UserForm(): class is implementing UserCreationForm in the forms.py class UserForm(UserCreationForm): . views.py def reg(request): if request.method=='POST': form= UserForm(request.POST) if form.is_valid(): user = form.save() group = Group.objects.get(name="patient") user.groups.add(group) return redirect('profile') else: form=UserForm() head = 'Create user account' title = 'Consultation | create account' … -
How to change the parameter dynamically in pd.DateOffset in python code?
date_ranges_values = request.POST['range'] ft = [df.index[-1]+ DateOffset(date_ranges_values =lambda x:x)for x in range(0,24))] -
How can I resolve the dist/css/404 error locally in django?
Attempting to upload a dist file built with vue to python backend. I set the structure like this in the django. /backend/shopee/base.py STATIC_URL = "/dist/" STATIC_ROOT = ( os.path.dirname(Path(__file__).resolve().parent.parent.parent) + "/frontend/dist/" ) DEBUG = True INSTALLED_APPS = [ "frontend.dist", ... ] FRONTEND_DIR = ( os.path.dirname(Path(__file__).resolve().parent.parent.parent) + "/frontend" ) TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(FRONTEND_DIR, "dist")], "APP_DIRS": True, "OPTIONS": { "context_processors": [ ... ], }, }, ] and urls.py urlpatterns = [ path("", index, name="index"), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) If runserver is set in this way, an error occurs in localhost/8000. Did I make a mistake? -
how to just access the count of products through another model which are connected by foreign key
class Category(models.Model): category_name = models.CharField(max_length=50, unique=True) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) product_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) Here what i want is just the number of the product present in each category just the number of product i know i have can fire somequery cat = Category.objects.all() run loop for cat prod_cat = Product.object.filter(category=cat) But i belive its not the efficient way to achive this -
Generating elements in Django from Python list
Im havin trouble generating elements from a for loop via iteration of a py list in Django. Using Metro UI as front end framework. import os img_dir = os.listdir("static/img/sasha_banks") #print(img_dir) # <img src="{% static 'img/sasha_banks/sasha_banks5.jpg' %}"> def sasha_files(): sasha_dir = [] for img in img_dir: sasha_dir.append(f'img/sasha_banks/{img}') print(sasha_dir) sasha_files() Above python script works i jist cant seem to get to that sasha_dir list. The commented was the hard coded django that works, im just trying to read the directory, pushthe filepath and concat the files in dir and then iterate that list to create -
Update None values in django Database
I have field in django model city which stored None but i want to update it how can i update the field data with respect to user id I tried a=Model.objects.filter(id=1).update(City = 'Vatican') this returned 1 -
Syndication Feed View RSS to File
I'm using django as my web frontend for my podcast. I use a CDN for hosting all my media, and lately I have wanted that same CDN to host my RSS Feed, not directly django. The current setup has some basic well known primitives: path('podcast.xml', SubscribeFeed(), name='episode_feed'), Some additional context; SubscribeFeed is a Syndication Feed (https://github.com/django/django/blob/main/django/contrib/syndication/views.py#L27) that is based off of the https://docs.djangoproject.com/en/4.0/ref/contrib/syndication/#custom-feed-generators And it looks somewhat like: class iTunesFeed(Rss201rev2Feed): content_type = 'application/xml; charset=utf-8' def root_attributes(self): attrs = super().root_attributes() attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd' return attrs < ... Ripped right from the custom feed generators with a ton of extra elements for the specific podcast category and such ... > class SubscribeFeed(Feed): title = "My Cool Podcast" description = About.objects.first().about author_email = "podcast@gmail.com" author_name = "John Doe" feed_type = iTunesFeed def item_pubdate(self, item): return item.pub_date < ... More stuff that isn't relevant ... > Just to be clear this view works perfectly with Django serving the podcast RSS. It works in all major platforms and is very nice. My problem/question is that: I want to generate/render this view to a text file, the purpose being; I host media on a CDN, I would also benefit myself to put this RSS Feed on … -
Django update_or_create using foreying key objects
My app have two models, PortfolioAsset and Transction. I am trying to use update_or_create in the transaction to find if the object PortfolioAsset exist with the selected parameters. If it exist to update, if not to create. But i am getting this error: Cannot assign "(<PortfolioAsset: PortfolioAsset object (11)>, False)": "Transaction.portfolio_asset" must be a "PortfolioAsset" instance. This was the exisiting object that i would like to update in this example. PortfolioAsset class PortfolioAsset(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1) asset = models.ForeignKey(Asset, on_delete=models.CASCADE) shares_amount = models.DecimalField(max_digits=18, decimal_places=0) def validate_unique(self, *args, **kwargs): super().validate_unique(*args, **kwargs) if self.__class__.objects.\ filter(portfolio=self.portfolio, asset=self.asset).\ exists(): raise ValidationError( message='This asset already exists in this portfolio.', code='unique_together', ) and Transactions: class Transaction(models.Model): OrderChoices = ( ('Buy', 'Buy'), ('Sell', 'Sell'), ) portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1) asset = models.ForeignKey(Asset, on_delete=models.CASCADE, default=1) portfolio_asset = models.ForeignKey(PortfolioAsset, on_delete=models.CASCADE, editable=False) shares_amount = models.DecimalField(max_digits=18, decimal_places=0) order = models.CharField(max_length = 8, choices = OrderChoices) def save(self, *args, **kwargs): self.portfolio_asset = PortfolioAsset.objects.update_or_create(portfolio=self.portfolio, asset=self.asset) if self.order == 'Buy': self.portfolio_asset.shares_amount += self.shares_amount if self.order == 'Sell': self.portfolio_asset.shares_amount -= self.shares_amount self.portfolio_asset.save() super(Transaction, self).save(*args, **kwargs) What am i doing wrong? Thanks