Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: automatically detect the tenant media folder when reading csv in Views.py
In my multi-tenant django app, the user needs to upload a file to the server. this file is then used in a view. my view uses pd.read_csv() to read the file uploaded, however I cannot find anywhere what to use inside of the brackets to automatically look inside of this particular tenant media folder. Thanks to django documentation, I was able to seperate my tenants within the media folder but I still don't how to write the path inside of the pandas.read_csv() Any help would be appreciated, thank you! -
Original exception text was: 'QuerySet' object has no attribute 'name' using django rest framework
I'm learning Django and i got to this error and I couldn't find the solution. Here are my models class Retailer(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) website = models.CharField(max_length=255) def __str__(self): return str(self.id) class Product(models.Model): id = models.AutoField(primary_key=True) price = models.IntegerField(default=None, null=True) name = models.CharField(max_length=255) retailer = models.ForeignKey(Retailer,on_delete=models.CASCADE,related_name='retailer_info') is_active = models.BooleanField(default=False) def __str__(self): return str(self.id) And here are my serializers class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class RetailerSerializer(serializers.ModelSerializer): products = ProductSerializer(many=True, read_only=True) class Meta: model = Retailer fields = ['name', 'website', 'products'] And here's my view class RetailerList(APIView): def get(self, request): retailer = Retailer.objects.all() serializer = RetailerSerializer(retailer) return Response(serializer.data) And here's my url path('retailer', views.RetailerList.as_view()), But when I submit a get request on 127.0.0.1:8000/retailer i get this error: AttributeError at /product Got AttributeError when attempting to get a value for field name on serializer RetailerSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'name'. What's the problem? -
Django creating .row for every post
i first time writing in django. When i trying to post-template, this code create a new <div class="row"></div> for every post. How i fix that? <div class="container news-card"> {% for post in post_list %} <div class="row" stlye="max-width"> <div class="card" style="width: 300px; height: 440px; margin-top: 60px; margin-left: 20px;"> <div class="card-img-top m-fix"><img src="https://telgrafs.com/assets/src/news-col1-row1-card-image.png"></div> <div class="card-text news-category">Ekonomi</div> <div class="card-title news-ct">{{ post.title }}</div> <div class="ccard-text news-ctext up-fix">{{post.content|slice:":200" }}</div> <div class="card-img-bottom author-image"><img src="https://telgrafs.com/assets/src/profile-kaa.png"></div> <div class="card-author-name">{{ post.author }}</div> <div class="card-post-time">{{ post.created_on}} </div> <a href="{% url 'post_detail' post.slug %}" class="card-text pb-more">DEVAMINI OKU &rarr;</a> </div> </div> {% endfor %} </div> {%endblock%} -
How to get a selected object in a form.Models using ModelChoiceField object
from bootstrap_modal_forms.mixins import PopRequestMixin, CreateUpdateAjaxMixin from bootstrap_modal_forms.forms import BSModalForm from django.contrib.auth import get_user_model class CommentForm(BSModalForm, PopRequestMixin, CreateUpdateAjaxMixin,): created_by = forms.ModelChoiceField(label="", widget=forms.HiddenInput, queryset=get_user_model().objects.all(), disabled=True,) paragraph = forms.ModelChoiceField(label="", required=False, queryset=MeetingReportContent.objects.none(), to_field_name="pk", disabled=False,) def __init__(self, *args, **kwargs): super(CommentForm, self).__init__(*args, **kwargs) self.fields['paragraph'].queryset = MeetingReportContent.objects.filter(pk=PARAGRAPH_SELECTED_HERE) class Meta: model = MeetingReport_Comment fields = ['paragraph', 'created_by', 'content_comment', ] exclude = [ 'accepted', 'timestamp'] I'm trying to get only the paragraph selected for the queryset, but get many errors... -
How can I temporarily save selected data from one table to another without overwriting the previous data?
I have an html table where I need to transfer or copy a row of data from this table to another table of the same structure that I call cart in my database. To do this, I would like that when I click on the button (+) of a given row, to add the corresponding data in the cart table. This is my template <form type="post" action="" style="margin: 0" > <label for="code" class="nav-link">Référence </label> <div class="col-sm-9"> <input id="productCode" type="text" name="productCode" placeholder="Entez le code du produit ..." onkeyup="myFunction()"> </div> </form> <table class="table table-bordered" id="productsTable" width="400"> <thead> <tr> <th>ID</th> <th width="10%">Code</th> <!-- <th width="16%">Catégorie</th> --> <th width="50%">Libéllé</th> <!-- <th width="12%">Marque</th> --> <th width="11%">Date entrée </th> <th width="11%">Qté initiale </th> <!-- <th width="12%">Quantity </th> --> <!-- <th width="12%">Qtité finale </th> --> <th>PU</th> <!-- <th>Statut</th> --> <th style="align-self: center;">Actions</th> </tr> </thead> <tbody> {% if products|length < 1 %} <tr> <td colspan="20" class="text-center">Aucune donnée trouvée, veuillez ajouter quelques données!</td> </tr> {% else %} {% for product in products %} <tr> <td>{{ forloop.counter }}</td> <td>{{ product.code }}</td> <!-- <td>{{ product.category }}</td> --> <td>{{ product.name }}</td> <!-- <td>{{ product.brand }}</td> --> <td>{{ product.date_entry }}</td> <td>{{ product.quantity_entry }}</td> <!-- <td>{{ product.quantity }}</td> --> <!-- <td>{{ product.final_stock }}</td> --> … -
Adding filtering options in Django - does not work properly
I'm trying to flirt my queryset depending on what I have in the database. I created a function in which query is my all queryset and filters my object (conditions). query = Shop.objects.all() filters = get_object_or_404(Filters, id=1) def shop_filters(query, filters): if filters.category_car: query.filter(category=1) if filters.category_computer: query.filter(category=2) if filters.category_phone: query.filter(category=3) return query It seems my function is not working at all. Despite the conditions, none of them works. My queryset still remains the same length. It seems that my queryset that I let into the function comes out the same. How to solve this problem? -
Range of models ORM django
how can I add range base ORM of some models? from .models import UsersLog if request.method == 'POST': login = request.POST.get('flogin') response_data = {} response_data['result'] = 'Failed' lengthBase = UsersLog.objects.get() for i in lengthBase: // I got 3 users so I want lengthBase equal 3 -
intellisense python suggestion
hey everybody i'm just started learning django and have a problem with vs-code it's seems that vs-code dosent suggest me some of the modules which i called in the program enter image description here as you can see vs-code should start to suggesting me name of the lists that i wrote before in the modules but it wont do the job ps: my cousin doing same thing but his vs-code seems to do the job perfectly -
Parse the request data in viewset and send it to different serializers in Django REST Framework
I have a problem with parsing request.data in viewset. I have a model that can add multiple images depending on a product. I want to split the image from the incoming data, send product data to ProductSerializer, and after that send image to its serializer with product data and save it. I have two model, simply like this: def Product(models.Model): name = models.CharField(max_length=20) color = models.ForeignKey(Color, on_delete=models.CASCADE) def Color(models.Model): name = models.CharField(max_length=15) def Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to='product_pics/') The request I want to send to the Product (127.0.0.1:8000/products/) is simply like: { "name": "strawberry", "color": { "name": "red" }, "productimage_set": [ {"image": "<some_encode_image_data>"} ] } There is nothing special in the serializer, it just extracts the tags link, so I did not write it. How do I send multipart/form-data and how can I parse it in the viewset? or what is the solution? -
Why user_permissions does not return any thing?
Here is my scenario: from django.contrib.auth import get_user_model from django.contrib.auth.model import Permission, Group from django.contrib.contenttypes.models import ContentType user = get_user_model().objects.create(email='example@google.com') group = Group.objects.create(name='group1') content_type = ContentType.objects.get( app_label=get_user_model()._meta.app_label, model=get_user_model()._meta.model_name ) permission = Permission.objects.create( name='perm1', codename='perm1', content_type=content_type ) group.permissions.add(permission) user.groups.add(group) Question: So why this query doesn't have any results: user.user_permissions.all() Output <QuerySet []> settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
ModelAdmin method stops when I reference too deeply
My model has a bunch of websites, each referencing a set of email_addresses. An email should be sent to the email_address of each website, so the email_message and email_address objects share a ManytoMany relationship. I would like to access the properties of the website of the email_address of the email_message, and I would like to do this in the ModelAdmin of an email_message. So there are multiple levels of references being used here. This is a highly simplified version of my code so please let me know if you need to see something I've omitted. models.py class Email_message(models.Model): email_addresses = models.ManyToManyField(Email_address, related_name='email_messages') subject = models.CharField(max_length=50) body = models.TextField() date_time = models.DateTimeField(null=True, blank=True) class Email_address(models.Model): address = models.EmailField() contact_name = models.CharField(max_length=50, null=True, blank=True) website = models.ForeignKey(Website, on_delete=models.CASCADE, related_name='email_addresses', null=True) class Website(models.Model): domain = models.URLField(default=None) searches = models.ManyToManyField(Search, related_name='websites', blank=True) def __str__(self): return self.domain @property def get_likely_location(self): searches = self.searches.all() locations = [] for search in searches: if search.location is not None: locations.append(search.location) return max(set(locations), key = locations.count) admin.py class Email_messageAdmin(admin.ModelAdmin): fields = ['id', 'email_addresses', 'date_time', 'subject', 'body', 'preview_random_email'] readonly_fields = ['id', 'preview_random_email'] def preview_random_email(self, obj): print("This always prints") test = obj.email_addresses.first().searches.all() print("If things are working, this will print") return format_html(test) I'd … -
Django. Where from my forms.py shall know, that the user has changed the application language?
I have a working application in English. I have started translating it into second language. I have created a language selection menu, which changes the language and it works for templates. In order to translate the fields in the tables (models) I have installed django-modeltranslation and translated all the fields via admin interface. The problem is that my forms.py returns always english text and does not switch to the second language irrespective of the language settings. from django import forms from .models import Application from django.utils.translation import gettext as _ class InputDataWaterForm(forms.Form): '''Application''' choices = list(Application.objects.values_list('id','application')) application = forms.ChoiceField(choices = choices, initial="1", label=_("Specify application:")) ... With the function translation.get_language() in the forms.py I see that the language setting within my forms.py is always en-us. When I force language change within the forms.py via translation.activate("ru"), it perfectly works. Where from my forms.py shall know, that the user has changed the application language? Thank you. -
Cyrillic turned to a question mark | Django template HTML metatags
So after deployment my cyrillic description in html metatags turned into question marks. It works fine on my localhost. Im passing html metatags through admin panel as a model so I can change my metatags after deployment easily, in addition to internationalization purposes. Using MySQL Django 2.2.5/Python 3.7.5 models.py class Metatags(models.Model): metatags_en = models.TextField(verbose_name='English Metatags', null=True) metatags_ru = models.TextField(verbose_name='Russian Metatags', null=True) metatags_uz = models.TextField(verbose_name='Uzbek Metatags', null=True) metatags_oz = models.TextField(verbose_name="O'zbek Metatags", null=True) metatags_en_blog = models.TextField(verbose_name='English Blog Metatags', null=True) metatags_ru_blog = models.TextField(verbose_name='Russian Blog Metatags', null=True) metatags_uz_blog = models.TextField(verbose_name='Uzbek Blog Metatags', null=True) metatags_oz_blog = models.TextField(verbose_name="O'zbek Blog Metatags", null=True) class Meta: verbose_name_plural = _("Metatags") base.html {% for x in metatags %} {% if current_lang == 'en' %}{{x.metatags_en|safe}} {% elif current_lang == 'ru' %}{{x.metatags_ru|safe}} {% elif current_lang == 'uz' %}{{x.metatags_uz|safe}} {% elif current_lang == 'oz' %}{{x.metatags_oz|safe}} {%else%}{{x.metatags_ru}} {%endif%} {%endfor%} metatags I'm using in cyrillic <!-- Primary Russian Meta Tags --> <meta name="title" content="Лорем ипсум долор"> <meta name="description" content="Лорем ипсум долор сит амет, пер цлита поссит ех."> <meta name="keywords" content="Лорем ипсум долор сит амет"> <meta name="robots" content="index, follow"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="revisit-after" content="1 days"> <meta name="author" content="Лорем"> -
PK not set to model entity after `.save()` in Django
I encountered the error save() prohibited to prevent data loss due to unsaved related object 'artwork'., while trying to add (not update) an Artwork. Originating from this function on ArtworkManager: def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) obj.save() # obj.id is empty here? try: latest_state = ArtworkState.objects.filter(artwork=obj).latest() except ArtworkState.DoesNotExist: latest_state = None if (latest_state is None or obj.state != latest_state.state): ArtworkState.objects.create( artwork = obj, created_by = request.user, state = obj.state ) The obj.save() seems to work but the obj pk/id does not get set. Artwork has the pk field: id = models.IntegerField(primary_key=True, help_text='') I understand the above error, we canno save a relation that has no primary key. I thought to mitigate that by obj.save()? -
Django: feed path based on category
In my blog I would like to have a feed generator for new posts based on the categories. I've two simple model in models.py: class Category(models.Model): category_name = models.CharField(....) slug_category = models.SlugField(....) publishing_date = models.DateTimeField(....) def __str__(self): return self.category_name def get_absolute_url(self): return reverse("single_blogcategory", kwargs={"slug_category": self.slug_category}) class Post(models.Model): title = models.CharField(....) slug_post = models.SlugField(....) description = models.TextField(....) draft = models.BooleanField(....) category = models.ForeignKey(Category, ....) publishing_date = models.DateTimeField(....) def __str__(self): return self.title def get_absolute_url(self): return reverse("single_blogpost", kwargs={ "slug_post": self.slug_post, "slug_category": self.category.slug_category, }) In views.py I have this situation: post_filter = BlogPost.objects.filter(Q(draft=False) & Q(publishing_date__lte=timezone.now())) def categoryList(request): category_list = BlogCategory.objects.all() context = {"category_list": category_list} return render(request, "blog/list_categories.html", context) def singleCategory_postList(request, slug_category): category = get_object_or_404(BlogCategory, slug_category=slug_category) blogpost_full = post_filter.filter(category=category) paginator = Paginator(blogpost_full, 10) page = request.GET.get("pagina") post_list = paginator.get_page(page) context = { "category": category, "post_list": post_list, } return render(request, "blog/single_category.html", context) def singlePost(request, slug_post, slug_category): category = get_object_or_404(BlogCategory, slug_category=slug_category) blogpost = get_object_or_404(post_filter, slug_post=slug_post) category_blogpost = BlogPost.objects.filter(category=category) context = { "category": category, "blogpost": blogpost, "category_blogpost": category_blogpost } return render(request, "blog/single_post.html", context) This is feed.py: class RssSiteNewsFeedBlogCategory(Feed): title = "Nuovo articolo online!" link = "/sitenews/" description = "Ultime news" def items(self): return BlogCategory.objects.filter(slug_category=slug_category).order_by('-publishing_date')[:5] def item_title(self, item): return item.title def item_pubdate(self, item): return item.publishing_date def item_description(self, item): return … -
Django: real time database using channels
I'm looking into channels lately in Django and from what I see in all the examples it is used for chat like applications. But I was wondering if I can use it to push notifications about database changes. So for example, what if my "view" consumer would poll the database and push notification every time it changed to the client. It is as if all clients of that page connect to the same chat room and wait for "posts" from the server. I know I can poll from the client using Ajax but I was wondering if I can use Django channels for that and have the server do the polling. -
django what do i need for authentication after login?
I followed the example in: https://docs.djangoproject.com/en/3.0/topics/auth/default/#django.contrib.auth.login from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid login' error message. This code doesn't seem to return any token or some sort to the client but just a redirection. In other codes where django checks authentication, django checks request.user.is_authenticated. Do i need to set this by myself? from django.conf import settings from django.shortcuts import redirect def my_view(request): if not request.user.is_authenticated: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) To get authenticated by decorators such as @login_required or have proper value for request.user.is_authenticated, what do I need to send and receive from the client(ReactJS)? -
Django insert one-to-one field only with its primary key?
When I try to create a basic post, it requires me to pass all the information about the author. post request body: { "author": { "id": 1 }, "title" : "title1", "content": "content1" } error message: { "author": { "username": [ "This field is required." ], "password": [ "This field is required." ], "profile": [ "This field is required." ] } } Is it possible to assign author only by its user id like I tried in the example above? class BasicPost(models.Model): author = models.OneToOneField(User, null=True, on_delete=models.SET_NULL, related_name='author') title = models.TextField() content = models.TextField() created_at = models.DateTimeField(default=timezone.now) modified_at = models.DateTimeField(default=timezone.now) -
Loop through django queryset in Javascript
I'm new to Django and I need to use some JS for my site, but i'm having a hard time understanding it. This is my view, where i am passing 'seats' to my template seats = Seat.objects.filter(screen = screen) seats = serializers.serialize('json', list(seats), fields = ('position', 'status')) context = {'seats': seats} return render(request, 'cart/choose_seat.html', context) This is 'seats' printed What i want to do is print the position of each seat object. So far, i've only written this: <script> var seats = "{{seats}}"; function position() { for (var i=0; i<seats.length; i++){ var obj = seats[i]; document.write(obj) } } </script> So, what should i do to print position? Thanks in advance -
Is bash_profile a shared file? Can SECRET_KEYs be shared between 2 projects?
Working on deploying the two Django projects I've developed, I deployed the first one and ran atom ~/.bash_profile in command line venv to set my SECRET_KEY and DEBUG values. I was able to deploy that app and its up and running fine. Then I went to deploy my second project and used the same command line script to open bash_profile and the SECRET_KEY and DEBUG values from the previous project is what came up. Is bash_profile a shared file? Am I supposed to have the same SECRET_KEY values for two different projects? -
Django FileResponse from io.BytesIO()
I have a view that serves PDF files, but I would like to modify the metadata of the pdfs before sending them. This is what I have so far: import i from django.http import FileResponse, StreamingHttpResponse from PyPDF2 import PdfFileReader, PdfFileWriter def doc_view(request): handle = open("documents/foo.pdf", "rb") base_pdf = PdfFileReader(handle) output_pdf = PdfFileWriter() for page in base_pdf.pages: output_pdf.addPage(page) stream = io.BytesIO() output_pdf.write(stream) stream.seek(0) return FileResponse(stream.read(), content_type="application/pdf") Running stream.read() manually returns a bytes object, which looks like it is ASCII encoded (but not certain of that). The view completes successfully, and returns a 200, but the PDF received by the browser cannot be displayed (it seems to be corrupted somehow). -
Django Rest Framework — no module named rest_framework
I am build a backend for my Nuxt.js project and I installed the following packages: django django-rest-framework django-cors-headers I installed them using pip3 but when I am trying to run migrations I get the following error: ImportError: No module named 'rest_framework' I checked my settings.py and I have everything as it should be. Do you guys have an idea how to solve this? -
Retrieve and update field of a model on views and display updated field in template
I am working on a view that retrieves the field(user's score) that is declared in a model, where I will also update the field(user's score) after a simple if-else statement, then display the field in template. But now, in the template's text area, where I put the result, it is now only showing userScore: userScore object (1), False, instead of the value of the user's score. So, how can I retrieve the score of the user from the model and update the field in views? morse_logs/game1.html {% block content %} <title>GAME 1</title> <h1>GAME 1</h1> <h2>1 + 1 = ?</h2> <form action="" method="get" > <input type="number" id="ans1" name="ans1"/><br><br> <button type="submit" name="game1Answer">Submit</button><br><br> <textarea rows="10" cols="50" name='a2' > {{currentS}} </textarea> </form> </div> {% endblock content %} morse_logs/views.py @login_required() def game1(request): if request.user and not request.user.is_anonymous: user = request.user #else: #Throw some raised exception here as the user is not valid... """The Game 1 page""" def verifyGame1(val1): user_score = userScore.objects.get_or_create(user=user) if val1 == 2: #user's score declared in model increase 5points #display correct and 5 points added to user user_score.score += 5 #user_score = str(user_score) user_score.save() return user_score else: #user's score declared in model has no point #display incorrect and 1 point added to … -
Executing a function from a third party package when a Record/Domain model is saved
I've been stuck on this for over a day now. Here is the function I want to execute: https://github.com/gnotaras/django-powerdns-manager/blob/master/src/powerdns_manager/utils.py#L551 rectify_zone As you can see, it saves the model, so if I put it in save(), or a presave or postsave signal, it will result in infinite recursion. In the package, a signal is automatically executed when a Domain or Record is saved in the admin, but not anywhere else. I want to be able to run rectify_zone outside of the admin. At the moment I'm stumped. Can anyone help? Thanks in advance. -
Error : MultiValueKeyError at /quiz/2/11 'choice'
I am creating a multi-choice quiz app, I have created a view which shows the question and its 4 option I have given radio button to each option but is giving me this error:MultiValueDictKeyError at /quiz/2/11/ 'choice' views.py def question_detail(request,question_id,quiz_id): q = Quiz.objects.get(pk=quiz_id) que = Question.objects.get(pk=question_id) ans = que.answer_set.all() selected_choice = que.answer_set.get(pk=request.POST['choice']) if selected_choice is True: come = que.rank came = come + 1 later_question = q.question_set.get(rank=came) return render(request,'app/question_detail.html',{'que':que , 'later_question':later_question, 'ans':ans}) else: come = que.rank later_question = q.question_set.get(rank=come) return render(request, 'app/question_detail.html', {'que': que, 'later_question': later_question, 'ans': ans}) question_detail.html <form action="{% 'app:detail' quiz_id=quiz.id question_id=que.id %}" method="post"> {% csrf_token %} {% for choice in que.answer_set.all %} <input type="radio" name="choice" id="choice{{forloop.counter}}" value="{{choice.id}}"> <label for="choice{{forloop.counter}}">{{choice.answer}}</label> {% endfor %}