Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin list filter using a model property
I have a model such as below: class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) number = models.CharField(max_length=36, blank=True, null=True) external_number = models.CharField(default=None, blank=True, null=True, max_length=250) @property def is_external(self) -> bool: return self.external_number is not None And I register my model like below: @admin.register(Order) class OrderAdmin(ReadOnlyIDAdminClass): list_filter = ["number", "is_external"] list_display = ["id", "is_external"] But since is_external is not a db field, I get the following error: (admin.E116) The value of 'list_filter[1]' refers to 'is_external', which does not refer to a Field I have tried something like creating a custom filter: class IsExternal(admin.FieldListFilter): # Human-readable title which will be displayed in the # right admin sidebar just above the filter options. title = 'is external' # Parameter for the filter that will be used in the URL query. parameter_name = 'is_external' def lookups(self, request, model_admin): return ( ('True', True), ('False', False) ) def queryset(self, request, queryset): if self.value(): return queryset.filter(external_number__isnull=False) return queryset.filter(external_number__isnull=True) and then update my Admin: @admin.register(Order) class OrderAdmin(ReadOnlyIDAdminClass): list_filter = ["number", ("is_external", IsExternal)] list_display = ["id", "is_external"] But it raises: Order has no field named 'is_external' which I think makes sense, but is there anyway to do this? I feel like I am messing on … -
Self Teaching Django
What all topics should I learn if I am self Teaching Django ? I am thinking of learning from FREECODECAMP. Can anyone mention what all topics are must ? I appreciate if you can share links of videos which are beginner friendly and if you have any recommendations. -
How do I limit a django model's field choices using one of the previous fields?
The following is in my models.py: class SensorType(models.Model): hardware_type = models.CharField(max_length=100) is_static = models.BooleanField(default=False) # Some other fields class Sensor(models.Model): device_id = models.CharField(max_length=100, primary_key=True) sensor_type = models.ForeignKey(SensorType, on_delete=models.PROTECT) # Some other fields class Asset(models.Model): name = models.CharField(max_length=100) sensor_type = models.ForeignKey(SensorType, on_delete=models.PROTECT) # I need to use this field to filter below sensor = models.ForeignKey(Sensor, on_delete=models.PROTECT, limit_choices_to={'sensor_type': WHAT DO I PUT HERE?},) # Some other fields I need to limit the choices in the sensor field of asset so that only sensors with the sensor_type set in the field immediately above, show up. The reasoning behind this is that there will eventually be many sensors and it would be very useful to filter this. Initially I only need this to work from the admin page but this will eventually extend when I make my Create and Update Views. Is this even possible? I'm essentially trying to access attributes before the object has actually been created. After reading several other questions such as this one I have also looked into ModelChoiceField but the same issue exists of trying to access the form data before it has been submitted. I'm very open to changing the model structure if that is what is required. -
Django - Pass a file to a session in form_valid
I have the following code in views.py: class UploadFile(CreateView): form_class = UploadFileForm template_name = "tool/upload.html" success_url = reverse_lazy('tool:edit_columns') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['file'] = self.request.session['file'] return context def form_valid(self, form): form.instance.name = form.instance.file.name row_number = form.instance.header_row file = form.instance.file df = pd.read_csv(file) names = list(df.columns) return super().form_valid(form) And this code in forms.py: class UploadFileForm(forms.ModelForm): class Meta: model = CheckFile fields = ['file', 'header_row', ] I want to pass the file object and the columns names to the page edit_columns.html. I've been looking for infos and I think I have to use a session to pass the file object but with the code I tried, I have the following error: KeyError: 'file' Could you please help me? Thanks! -
Django: Is there a way to store request session in each tab
I have a use case with an admin who can access the user area when they click the link, it will open their area (user area is a separate app). Using jwt access admin logs in to user app. When doing that admin sessions gets expired. Is there a way to hold the admin session in the current tab when the user is opened on the new tab? -
Send current logged in user from Django backend to React frontend using axios
I am trying to send current logged in username from django backend to React frontend. I have created an endpoint currentuser/ that works perfectly fine in backend, it returns the expected result but when I call this api endpoint in React using axios,null value is returned there. Here's the code for backend #view.py from django.contrib.auth import get_user_model from rest_framework import serializers from rest_framework.response import Response from rest_framework.views import APIView User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username') class LoggedInUserView(APIView): def get(self, request): serializer = UserSerializer(request.user) return Response(serializer.data) #urls.py urlpatterns = [ path('currentuser/', views.LoggedInUserView.as_view(), name='currentuser'), ] Here's the result when calling the api directly Here's the code for frontend class App extends React.Component { state = { users: [], } getUsers() { axios.defaults.headers.common['Content-Type'] = 'application/json'; axios.get(`http://localhost:8000/currentuser/`) .then(res => { console.log("res :", res); const user = res.data; console.log("response from backend", user); this.setState({ users: user }); console.log(this.state.users); }) .catch(err => { console.log("error:", err); }); console.log(this.state.users); } constructor(props) { super(props); this.getUsers(); } render() { return (.....) } }; export default App; Here's the result when calling the api from the frontend Any suggestions would be appreciated -
django navbar not across the top, showing top left box instead
when viewing my django app in the laptop it is showing the menu as expected acress the width of the screen but when trying to run that menu in the mobile it is shown as a small box on the top left of the screen. How to fix that? <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> </li> </ul> <div class="form-inline my-2 my-lg-0"> {% if user.is_authenticated %} so whay is that happening? how to fix that? Thanks. -
how to load a select widget with queryset data in django forms
I'm trying to load a dynamic select widget in my form with queryset data using the following code: forms.py class TransactionForm(forms.Form): # Payment methods payment_meth = [] # form fields trans_amount = forms.IntegerField(label="Amount", min_value=0) payment_method = forms.CharField( label='Payment method', widget=forms.Select( choices=payment_meth ) ) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) username = self.request.user.username self.get_mm_details = MMDetails.objects.filter(username=username) self.get_card_details = CardDetails.objects.filter(username=username) # add payment methods details to a dictionary for method in self.get_mm_details: entry = () entry += (method.method_name,) entry += (method.method_name,) self.payment_meth.append(entry) for method in self.get_card_details: entry = () entry += (method.method_name,) entry += (method.method_name,) self.payment_meth.append(entry) super(TransactionForm, self).__init__(*args, **kwargs) View.py form = TransactionForm(request=request) What can I do to make it work -
How to convert already exiting FBV to CBV in Django
everyone, happy year to you all! Please guys pardon me if this question seems easy for anyone. I just started learning Django last month. So, I'm pretty new to how to switch things together. I have created an FBV called article_view which actually works as expected. However, as I continue to learn I came to realize that CBV has the magic one that'll not only shorten my codebase but also comes with tons of methods that make me live longer :). So I decided converting my FBV to CBV will be the right to do also use that to practice my Django learning. So I created a CBV called ArticleView and added some context but for some reason, I can't seem to figure out how to fully replicate the FBV to CBV. Please I will greatly appreciate it if someone can help me with this. I have been struggling with this for almost a week trying to figure it out by myself and no luck. So I've come to the terms that I need some help. Funtion Based View: def article_view(request): articles = Article.objects.all().order_by('-published_on') this_page = request.GET.get("page", 1) pages = Paginator(articles, 5) try: page_obj = pages.page(this_page) except PageNotAnInteger: page_obj = … -
How to take requested data as json object in django views?
I'm submitting my form from postman. But i'm getting all key values as a list. I don't know why, how can i get key values without list. here is request.data i'm getting: {'from_email': ['dummyfirst54@gmail.com'], 'to_email': ['coolahmed21@gmail.com'], 'subject': ['hey man whats up ?'], 'html_body': [<InMemoryUploadedFile: email_test_template.html (text/html)>]} I'm expecting it to be like following. {'from_email': 'dummyfirst54@gmail.com', 'to_email': 'coolahmed21@gmail.com', 'subject': 'hey man whats up ?', 'html_body': <InMemoryUploadedFile: email_test_template.html (text/html)>} i'm requesting in a following way. -
My models are not getting displayed in html file
its showing blankspace for there value . i gave them value in admin panel admin.py models.py views.py index.html settings.py -
How to change the display format of datetime fields in the Django admin interface?
I already read in the django documentation that you have to change it in the settings and set USE_L10N to False. So i did it accordingly in settings.py: USE_L10N = False DATETIME_FORMAT = 'd.m.Y - H:i:s' USE_TZ = True USE_I18N = True TIME_ZONE = 'CET' LANGUAGE_CODE = 'en-us But my the datetime field of my objects are still displayed like this in the admin interface: 2022-01-18 15:00:56.421123+00:00 So why is the datetime still not displayed according to my settings.py, but like Y-m-d H:i:s.u? In my models.py i implemented __str__(self) like this: def __str__(self): return self.created my model: class My_model(models.Model): created = models.DateTimeField(auto_now_add=True) What am I missing here? -
Django: How to use an annotation from a parent queryset?
I have an Item class which can be annotated using a custom queryset add_is_favorite_for method: class ItemQuerySet(QuerySet): def add_is_favorite_for(self, user): """add a boolean to know if the item is favorited by the given user""" condition = Q(id__in=Item.objects.filter(favoriters=user).values("id")) return self.annotate(is_favorite=Condition(condition)) # True or False class Item(Model): objects = Manager.from_queryset(ItemQuerySet)() It works as expected. For example: >>> user = User.objects.get(id=1) >>> Item.objects.add_is_favorite_for(user) # each item has now a `is_favorite` field Now, I want to add a Factory Model and link Item Model to it this way: class Factory(Model): pass # ... class Item(Model): objects = Manager.from_queryset(ItemQuerySet)() advised_in = models.ForeignKey( Factory, on_delete=models.CASCADE, related_name="advised_items", ) I'd like to be able to return a Factory QuerySet, whose advised_items fields will all contain the is_favorite annotation too. I don't know how to do this, I saw no example of such a thing in the doc, maybe I missed it? -
why I am getting only one result only from the youtube api
I have a list of video ids as strings of different videos of youtube,but when I am fetching the data for all the video ids I am getting result for only last video. Here is my code : search_url = 'https://www.googleapis.com/youtube/v3/videos' parameter = { 'key' : settings.YOUTUBE_DATA_API_KEY, 'part' : 'snippet', 'id' : ','.join(video_id) } data = requests.get(search_url,params=parameter) results = data.json()['items'] In the above code the video_id is a list containing video ids. I am getting a csv file which which has youtube video urls , and I am taking the video id from it and appending them in video_id list as: rows = [] video_id = [] file = request.FILES["file"].readlines() for f in file: rows.append((f.decode('utf-8'))) for row in rows[0:len(rows)-1]: video_id.append((row[-13:])) video_id.append((rows[len(rows)-1][-11:])) The complete code is : def home(request): if request.method == 'POST': rows = [] video_id = [] file = request.FILES["file"].readlines() for f in file: rows.append((f.decode('utf-8'))) for row in rows[0:len(rows)-1]: video_id.append((row[-13:])) video_id.append((rows[len(rows)-1][-11:])) print(len(video_id)) for v in video_id: print(v) search_url = 'https://www.googleapis.com/youtube/v3/videos' parameter = { 'key' : settings.YOUTUBE_DATA_API_KEY, 'part' : 'snippet', 'id' : ','.join(video_id) } data = requests.get(search_url,params=parameter) results = data.json()['items'] channel_list = [] for result in results: data = { 'channel_name' : result['snippet']['channelTitle'] } channel_list.append(data) for list in channel_list: print(list) … -
Django Firebase Gmail Authentication
i'm creating a web app with django and i'm using firebase. i can authanticate with an e-mail and i can see my users on firebase console. i'm using firebase-admin for authantication and database operations. its working correctly. but i want to add gmail auth on my app. i added gmail authentication but its working with django-retsframework and i can see my gmail users in django admin panel. there is a problem, i cant use django rest framework here. i have to use only firebase. and i couldn't add my gmail users on firebase i have some ideas but i'm not sure for they are safe. as you know i can see credentials gmail users and i can take email and ID fields, and create one firebase auth. as i said i'm not sure this is safe. if this idea is not safe how can i save my gmail users with credentials like e-mail users ?? -
Djnago make an inner join using another inner join
How could I make inner joins in tables that share same FK. here is an example of some models: models.py class Property(models.Model): name = models.CharField(blank=True, max_length=1024) address = models.ForeignKey(Address, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) ... class Address(models.Model): country = models.CharField(blank=True, max_length=1024) state = models.CharField(blank=True, max_length=1024) ... class Category(models.Model): code = models.CharField(blank=True, max_length=1024) location = models.CharField(blank=True, max_length=1024) ... class Reservation(models.Model): check_in = models.DateField(blank=True, null=True) check_out = models.DateField(blank=True, null=True) property = models.ForeignKey(Property, on_delete=models.CASCADE) class Category_month_price(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) month = models.PositiveSmallIntegerField(blank=True, null=True) i'd like to create a view for category_month_price with all properties with same category_id and check if they don't have any check_in or check_out in a range period. Can i achieve this using inner joins with queryset.select_related? if yes, how could i do that? -
What method can I use to develop session control using Django?
Currently in the company I have developed about six applications with Django, these applications are managed in different databases since they are focused on different departments. They are asking me that access to these applications be done through a single credential, that is, if a user must handle two applications, they should not have two different access credentials, but rather they can access both applications with a single credential. I have consulted various sources, one person recommended me to develop an application that is only responsible for access, but I am a bit disoriented with this problem. I appreciate the help! -
why can't I import my models in Python shell?
I don't even know what this is. Works fine when I runserver. But I get an Error when trying to import in the Python Shell. My app is called auctions and my models.py (using AbstractUser) file is: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64, blank=True) image = models.ImageField(upload_to="portraits", blank=True, default="default.jpg") def __str__(self): return f"{self.username}" class Category(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64) description = models.CharField(max_length=255, blank=True) def __str__(self): return f"{self.name}" class Item(models.Model): id = models.AutoField(primary_key=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="inventory") name = models.CharField(max_length=64) description = models.CharField(max_length=255) image = models.ImageField(blank=True, default="Megamind.jpg") starting_bid = models.PositiveIntegerField(default=0) category = models.ForeignKey(Category, on_delete=models.CASCADE, default="1", related_name="stuff") active = models.BooleanField(default=True) favorited = models.ManyToManyField(User, blank=True, related_name="favorites") def __str__(self): return f"{self.name} of {self.owner}" -
Django: Uploading Avatar Imagefile to media-Folder of Custom User Profile is not working
I'm currently trying to create a Custom User Model for being able to add a Avatar-Imagefield to ever User. Therefore I've created a Model Profile with avatars as the directory (media/avatars/) for all Images: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField('Avatar', upload_to="avatars", default="avatars/profil_picture_icon.png") I created the needed classes ProfileInline and UserAdmin: class ProfileInline(admin.StackedInline): model = Profile can_delete = False class UserAdmin(BaseUserAdmin): inlines = (ProfileInline,) admin.site.unregister(User) admin.site.register(User, UserAdmin) I also defined the media-directory inside the settings: MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' After that, I created a Form ProfileForm, where the User can upload the Image and a postsavereceiver to create a basic Profile-Model every time I'm creating a new User: class ProfileForm(forms.ModelForm): class Meta: model = models.Profile exclude = ('user',) def post_save_receiver(sender, instance, created, **kwargs): if created: user_profile = models.Profile(user=instance) user_profile.save() post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL) Inside my Template I then created a form with the Avatar-ImageField and a Save-Button to Upload that Image: <form action="/profil/" method="post" id="avatar_form"> {% csrf_token %} <img style="border-radius: 100px" id= "Profil_Image" src=" {{ user.profile.avatar.url }}"> {% load widget_tweaks %} {{ profile_form.avatar|add_class:"profile_form" }} <button id="update_button" style="left: 1210px; top: 385px" type="submit" form="avatar_form" name="avatar_update_btn" value="">Speichern</button> </form> Lastly inside my views.py the User can Update the Default-Image elif … -
Pass Context from serializer to serialzier
How can i pass context from 1 serializer to another like sub_variant = SubVariantSerializer( source='subvariant_set', many=True, context={"variant_id": ?} # i want to pass variant_id here ) I know serializer.SerializerMethodField() but dont want to use it here. Please suggest is it possible to send context serializer to serializer in below code? or how can i pass variant_id in further serializer MY CODE: # MODELS class Variant(models.Model): variant_id = models.AutoField(primary_key=True) category_id = models.ManyToManyField(Category) variant_name = models.CharField(max_length=100) class SubVariant(models.Model): sub_variant_id = models.AutoField(primary_key=True) variant_id = models.ManyToManyField(Variant) sub_variant_name = models.CharField(max_length=100) # SERIALZIER class SubVariantSerializer(serializers.ModelSerializer): new_field = serializer.SerializerMethodField() class Meta: model = SubVariant fields = "__all__" def get_new_field(self, obj): print(self.context['variant_id']) return self.context['variant_id'] class VariantServiceSerializer(serializers.ModelSerializer): sub_variant = SubVariantSerializer( source='subvariant_set', many=True, context={ "variant_id": ?? variant_id ?? }) class Meta: model = Variant fields = "__all__" -
Automatically check a directory in Django and read the file only once
How do I write a program in Django that always checks a specific directory? If a file is added, it only reads it once and does not read it again? The following program is inside a Python app and I do not know how to write like this inside Django and it reads directory files every 5 seconds. I want to read it once and after 5 seconds a new file was added to read it def uptime_bot(path_root): postfix_json = os.path.join(path_root, '*.json') postfix_csv = os.path.join(path_root, '*.csv') while True: try: if postfix_json: for filename in glob.glob(postfix_json): with open(filename) as file: file_data = json.load(file) for key, val in file_data.items(): for i, doc in enumerate(file_data[key]): print(doc) print(Collection.insert_one(doc)) if postfix_csv: for filename in glob.glob(postfix_csv): with open(filename) as file1: content = [] df = pd.read_csv(filename, index_col=None) content.append(df) data_frame = pd.concat(content) data = [] headlist = [] final_result = [] for index, row in enumerate(data_frame): headlist.append(row) for index, row in enumerate(data_frame.values): res = {} for i in range(len(headlist)): res.update({headlist[i]: row[i]}) final_result.append(res) print(final_result) print(Collection.insert_many(final_result)) except: print('Error:Some json file data is duplicate!') time.sleep(5) path_root = 'Data/js' uptime_bot(path_root) -
Djagno and ElasticSearch how to allow search with typos
I'm fairly new to elastic search and I want to enable searching with typos (max of 2 letters) example input: gpple result: google ///////////// input: convarsetyon (3 letters typos, meant to be : conversation ) result: none my backend is Django and the way i communicate with elastic search is via elasticsearch-dsl I tried to implement add fuzziness attribute to the wildcard query but it resulted in an error views.py: class SearchRecipes(ListAPIView): serializer_class = RecipeSearchSerializer def get_queryset(self, *args, **kwargs): word = self.kwargs['word'] recipeQueryset = RecipeDocument.search().query('wildcard',title=f'*{word}*').sort("-score") return recipeQueryset documents.py autocomplete_analyzer = analyzer('autocomplete_analyzer', tokenizer=tokenizer('trigram', 'edge_ngram', min_gram=1, max_gram=20), filter=['lowercase'] ) @registry.register_document class RecipeDocument(Document): title = fields.TextField(required=True, analyzer=autocomplete_analyzer) class Index: name = 'recipes' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, 'max_ngram_diff': 20 } class Django: model = Recipe fields = [ 'score', ] Anyone have a clue how to do this? thanks in advance -
How to add CSP for Django CKEditor
I'm not using CDN or any link for CKEditor but I have PIP installed it using pip install django-ckeditor. I have added all necessary CSPs and CKEditor configurations in settings.py file but CKEditor is not working in html. Please help me fix it. -
C# developer switching to Python
I've been working with .NET for the last 10 years. Recently I switched to a new company that is using Python. I'm looking for a book or web series that can explain the intent of Pythons designer as well as the inner workings of the language. Something along the lines of C# in depth by Jon Skeet. I'm currently reading Effective Python by Brett Slatkin which is incredibly helpful but it doesn't seem to touch on the languages design decisions. Honestly a lot of what I'm reading seems like the wild west of programming (I guess that's to be expected from a duck typed language). Material that incorporates duck vs static type would appreciative as I can use help with the paradigm shift needed between the 2. I'd also be interested in any material that could be helpful with Django architecture and best practices. I've noticed that my company has many apps in the same project, something that I've never seen in .NET (I've always moved common libraries into a Nuget and then created separate repos and solutions for each service). I understand there may be advantages to doing so in python (debugging across multiple apps from one IDE and … -
How to send data from one consumer to another consumer
This is a consumer which serves data to other clients. class GetLocationConsumer(AsyncConsumer): data = '' async def websocket_connect(self, event): self.bus = self.scope["url_route"]["kwargs"]["bus"] print(self.bus) #self.user = self.scope["user"] self.bus_room = self.bus self.channel_name = self.bus_room await self.channel_layer.group_add(self.bus_room, self.channel_name) await self.send( { "type": "websocket.accept", } ) await self.send( { "type": "websocket.send", "text": "connected", } ) async def websocket_receive(self, event): self.user = self.scope["user"] print(self.user) print(f'{randint(1,100)}{event["text"]}') await self.channel_layer.group_send( self.bus_room, { "type": "send_message", "text": event["text"], }, ) async def send_message(self, event): # print("message hit") await self.send( { "type": "websocket.send", "text": event["text"], } ) async def websocket_disconnect(self, event): await self.send({"type": "websocket.send", "text": "Connection close"}) await self.send({"type": "websocket.close", "text": "Connection close"}) This is another consumer which will receive location data from a client. class SetLocationConsumer(AsyncConsumer): async def websocket_connect(self, event): self.token = self.scope["url_route"]["kwargs"]["token"] print(self.token) if self.token is None or self.token == '': await self.send({ "type": "websocket.close", "text": "No token provided", }) self.user = await self.check_token(self.token) if self.user is AnonymousUser: await self.send({ "type": "websocket.close", "text": "Invalid token", }) self.bus = self.scope["url_route"]["kwargs"]["bus"] self.bus_room = self.bus self.channel_name = self.bus_room await self.channel_layer.group_add(self.bus_room, self.channel_name) await self.send({ "type": "websocket.accept", }) async def websocket_receive(self, event): await self.channel_layer.group_send( self.bus_room, { "type": "send_message", "text": event["text"], }, ) async def websocket_disconnect(self, event): await self.send({ "type": "websocket.send", "text": "Connection close" }) …