Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to transfer data of a table from Html to view.py (Python)
I'm using Django and I want to transform some data into view.py. I would like to know if there is a guide or method to do it. Let's say I want to transform the following into view.py <table class="table table-bordered table-striped"> <thead> <!-- Columnas de la tabla --> <tr> <th scope="col">Nombre huesped</th> <th scope="col">Rut huesped</th> <th scope="col">Telefono</th> <th scope="col">N° de habitacion</th> <th scope="col">Tipo de plato</th> <th scope="col">borrar</th> </tr> </thead> <tbody id="filas"> <!-- Fila 1 de la tabla --> </tbody> </table> -
Django not serving text content
Summary: The purpose of this particular app is to just show some lorem ipsum text on the home page, like a blog post. Django is not serving my blog post content. I know the problem is either with my views.py or urls.py (or both). Details: I’ve got the data declared inside my models.py. I’ve got my views.py to instantiate the model. I migrated sqlite and successfully logged into the Admin Dashboard and entered some placeholder data. I’m trying to get Django to serve the placeholder content that I entered into the Admin Dashboard, but instead it’s blank. Here is my what my test case looks like: https://i.imgur.com/IuOl3G4.jpg To describe it, you can see The Blog Post, Date, Image, and Body Text HTML heading elements parsed, but none of the content is showing. Here is my app’s urls.py: from django.urls import path, include from . import views urlpatterns = [ path('', views.mortems, name='home'), ] I’ve tried swapping out the quotation marks for the first path() parameter with alls/landings. I’ve tried swapping the name parameter from home to mortems. I also tried using mortem (without the s). None of these changes help. I've also tried Googling (with variations): 'body text django not … -
Opening specific pdf files from database in django
What I want to do is to access a file by its name from a Database and show it onscreen in a new window. I have this working locally if i store the file in my project and not in my DB. I have done this by: Views.py def show_file(response): pdf = open( `chartsapp/faults.pdf`, 'rb') response = FileResponse(pdf) return response Url.py path('show_file/', views.show_file), html <input type="button" value="Show Report" onclick="window.open('show_file')"> My code above will open my locally store faults.pdf, and who it in a new window called show_file. Taking this as a baseline i have been trying to swap out chartsapp/faults.pdf for the path to my database. So I thought that the following would access my faults.pdf which has been stored in my database called 'UploadedFile`: Views.py def show_file(response): pdf = open( UploadedFile.the_file('faults.pdf'), 'rb') response = FileResponse(pdf) return response I thought this should work because i am first accessing my Database called UploadedFile, then the the_file object, the entry called faults.pdf. But I am missing something as this does not work. -
Why is my generic.DetailView not populating my detail template with the correct object?
I am new to Django and am creating a simple project where a user can log in, view their page, and then view their contacts and contact lists. To do this I have a page called 'AddressBook', where the user's contact lists and contacts are displayed, with links to each contacts detail page. The problem is, though, that although every single link is generated correctly, once on the contact detail page which follows any given link, the resulting detail page only shows information for the contact with pk = 1. I have no idea why this is happening or a way to go about fixing it. For example, I have a contact named John Smith who has a pk of 4 or something. I expect to click the link in addressbook.html (which has a url of localhost:8000/profile/1/mycontacts/4 since I am the user with a pk of 1). This is indeed the link rendered in the browser, and the url that it directs me to. When I am there I would expect the resulting contact-detail page to populate with John Smith's information. Instead, it populates with the contact who has a pk of 1 - every single time, no matter what … -
How to update Django template context with an AJAX call (without refreshing the page)?
I have a HTML template with a selector widget. I also have context variable called test_instance (used on the Info Card section) <!------------- TEST ID selector -------------> <div class="row test-selector-row"> <div class="col-lg-4 col-md-6"> <select id="test-selector" class="select2 form-control custom-select" style="width: 100%; height:36px;"> <option></option> {% for domain, tests_list in test_selection_data.items %} <optgroup label={{ domain|title }}> {% for test in tests_list %} <option value={{ test.test_id }}> {{ test.test_id }}: {{ test.ab_test_name }} </option> {% endfor %} </optgroup> {% endfor %} </select> </div> </div> <!------------- Info Card -------------> <div class="row" id="validation"> <div class="col-12"> <div class="card wizard-content"> <div class="card-body" style="display:none;"> <div class="page-header-styling"> <h4 class="card-title"> Test #{{ test_instance.test_id }} - {{ test_instance.ab_test_name }} </h4> {% if test_instance.end_date %} <h5 class="card-subtitle" style="color: #747779;">Start Date: {{ test_instance.start_date|date:"Y-m-d" }} / End Date: {{ test_instance.end_date|date:"Y-m-d" }} </h5> <font size="3" style="color:#00560f;"> Test was opened for {{ test_instance.start_date|timesince:test_instance.end_date }} </font> {% else %} <h5 class="card-subtitle" style="color: #747779;">Start Date: {{ test_instance.start_date|date:"Y-m-d" }} </h5> <font size="3" style="color:#00560f;"> Test is Still Running </font> {% endif %} </div> <div class="release-notes-form-header-class" id="release-notes-form-header-id"> {% include "release_notes/release_notes_form_header.html" %} </div> </div> </div> </div> </div> Note that the "card-body" is hidden on page load. A view on views.py that is getting an item from DB by its ID. # Ajax View … -
Search Query by Date Django
I have a search bar that sends the query to an endpoint. The endpoint filters through objects and updates the frontend. This is the filtering: for word in query.split(): objects = Object.filter( Q(name__icontains=word) | Q(date__icontains=word) ) As you can see, I am filtering date. How can I make it so that if I search January, all of the dates in January come up. Or if I search 07/18/2005, any objects with that date show up. Thanks! -
Can't find model's fields on admin - Django
The problem is this: Screenshot As you see here, I can't even find a place (fields) to add. I'll show you the models and admin files. And This is the models.py file: from django.db import models from django.contrib.auth import get_user_model # Create your models here. User = get_user_model() class BmiCal(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) weight = models.FloatField() height = models.FloatField() bmi = models.FloatField() date = models.DateField() class Meta: app_label = 'bmi' def __str__(self): return self.user + " : " +self.bmi And this my admin.py file: from django.contrib import admin from .models import BmiCal # Register your models here. class BmiAdmin(admin.ModelAdmin): readonly_fields = ('weight','height','bmi', 'date',) admin.site.register(BmiCal,BmiAdmin) enter code here -
get_field Not Working Django Rest Framework Serializer
In serializers.py class WordSerializer(serializers.Serializer): word = serializers.CharField(max_length=100) definition = serializers.CharField(allow_blank=True, allow_null=True) synonym = serializers.ListField(child=serializers.CharField(max_length=100), allow_null=True) sentence = serializers.CharField(allow_blank=True, allow_null=True) user = serializers.PrimaryKeyRelatedField(queryset=User) currently_studying = serializers.BooleanField(default=False) def get_synonym(self, obj): print(obj.data) return obj.data.synonym.split('\n') When I created an instance of the serializer, the get_synonym function wasn't called. Is there anything wrong in this code? How do I fix this problem? -
Converting complex raw SQL query into Django ORM
How I can convert following raw SQL query into Django ORM. I have models like this: class PhoneNumberPlacement(models.Model): phone_number = models.ForeignKey(PhoneNumber, null=True, blank=True, on_delete=models.CASCADE) class PhoneNumber(models.Model): id = models.AutoField(primary_key=True) provider = models.ForeignKey(Provider, null=True, blank=True, on_delete=models.CASCADE) class AgencyState(models.Model): agency = models.ForeignKey(Provider, on_delete=models.CASCADE) class AgencyHours(CachedModel): agency = models.ForeignKey(Provider, db_index=True, on_delete=models.CASCADE) Currently, this query calculates weight based on some conditions and get phone with max weight. SELECT SUBSTR(MAX(CONCAT(total_weight, placement_id)), 4), SUBSTR(MAX(CONCAT(total_weight, phone)), 4), SUBSTR(MAX(CONCAT(total_weight, open)), 4), SUBSTR(MAX(CONCAT(total_weight, close)), 4), SUBSTR(MAX(CONCAT(total_weight, timezone)), 4) FROM ( SELECT DISTINCT LPAD(ROUND( CASE WHEN pnp.state_id IS NULL THEN 100 WHEN pnp.state_id = ast.state_id THEN 101 ELSE 0 END + CASE WHEN pnp.carrier_id IS NULL THEN 40 ELSE 0 END + pnp.weight * 20 ), 3, '0') AS total_weight, pnp.placement_id, COALESCE(pn.ivr_number, agency_number) AS phone, ah.open, ah.close, ah.timezone FROM phone_number_placement AS pnp INNER JOIN phone_number AS pn ON pnp.phone_number_id = pn.id LEFT JOIN agency_hours AS ah ON pn.provider_id = ah.agency_id AND DAYOFWEEK(CONVERT_TZ(UTC_TIMESTAMP(), 'UTC', ah.timezone)) = ah.day_of_week AND TIME(CONVERT_TZ(UTC_TIMESTAMP(), 'UTC', ah.timezone)) BETWEEN ah.open AND ah.close LEFT JOIN agency_state AS ast ON ast.agency_id = pn.provider_id AND ast.state_id = %s AND ast.active_nst + ast.active_std + ast.active_prf > 0 WHERE pnp.weight > 0 ) AS c GROUP BY placement_id; I tried but I totally … -
Timezone is UTC infact of changing it in settings.py file
My app is showing the timezone.now() as UTC time when I see it in Heroku scheduler. Also I built a custom manage.py command to test it but it still shows UTC time. Here is my settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True Here is my personalied manage.py command managemet/commaands/abhiwaqt.py from django.core.management.base import BaseCommand, CommandError from django.apps import apps from Directory.utils import * class Command(BaseCommand): help="Refresh models and its fields." def handle(self,*args, **options): try: print(timezone.now()) except: raise CommandError("Something went wrong") Infact of setting TIME_ZONE='Asia/Kolkata' I am getting this issue. -
Cannot list S3 objects in Celery worker with Django
I'm building a scheduler in Django with Celery worker and beat. And I'm trying to list all objects in a S3 folder by using Boto3: for file in files: blabla However, it stopped at for loop without any error messages. I've also set CELERY_ACCEPT_CONTENT = ['pickle', 'json'] and permissions and policy for my S3 bucket seem to be configured correctly. Is there anyone who knows the reason why the issue happened, please? -
Django forms not being tranlated
I am trying to use gettext in Django to translate forms. But for some reason, it does not work. It only works when I set LANGUAGE_CODE = 'ar' Other parts of the template are being translated successfully. Django version 3.0.7 Form difination class productform(forms.Form): name = forms.CharField(label=gettext("Name")) description = forms.CharField(label=gettext("Description"),required=False) def is_valid(self): if not super().is_valid(): return False if product.objects.filter(name__exact=self.cleaned_data['name']).exists(): return False return True How the form is used <div class="container"> <form method="POST" enctype="multipart/form-data" class="post-form"> {% csrf_token %} {{form.as_p}} <button type="submit" class="save btn btn-default">{% trans "Save" %}</button> </form> </div> Any idea where I failed to get it to work? -
pip3 install bpy Building wheel for bpy (setup.py) ... error Failed to build bpy
Failed to build bpy. Watch this prbolem her https://i.stack.imgur.com/fO52E.png -
Django InlineFormset_Form not displaying errors
I am using multiple embedded forms/inline formsets in a template which has been able to handle everything fine, except the concept of rendering a form error. When validating there exists an error in the form_invalid function I get the following info: [{}, {'__all__': ['An enrollment record already exists for 0-2']}, {}] HTML: <div class="form-group"> <legend>Enrollment</legend> {{ enrollment.management_form }} <div id="id_roomenrollment_set_form"> <table> {% for eForm in enrollment.forms %} <table class='no_error'> {{eForm.non_field_errors}} {{eForm.errors}} {{ eForm }} </table> <hr> {% endfor %} </table> </div> Form Valid/Invalid: ''' Sets the variables to their respective 'instance' objects. This passes the information from the context dictionary to the variable instance, try and catch to validate for both populated forms and non populated forms ''' def form_valid(self, form, note, enrollment, mealCount): self.object = form.save() try: note.instance = self.get_object() #creates note object for saving enrollment.instance = self.get_object() mealCount.instance = self.get_object() except Exception: note.instance = self.object enrollment.instance = self.object mealCount.instance = self.object ages = set() #checking for unique enrollments by age group. for enrollmentForm in enrollment: ageGroup = enrollmentForm.cleaned_data['age_groups'] if (ageGroup in ages): enrollmentForm.add_error(None, ValidationError(_('An enrollment record already exists for %(value)s'), params={'value': ageGroup})) return self.form_invalid(form, note, enrollment, mealCount) else: ages.add(ageGroup) enrollment.save() note.save() mealCount.save() return HttpResponseRedirect(self.get_success_url()) ''' Passes back the … -
How can I change the color on the like button in django?
I did create (like and dislike) in my project and I need it when someone clicks on the button. the color will change to blue I saw something like that where I could create a variable called something like: is_liked = False, and I can place that in HTML by context to trigger it in (if condition) but it's not working with me so, How can I run the color on the like button? views.py # Detail question and Create comment class QuestionDetail(DetailView, SingleObjectMixin): template_name = 'community/question_view.html' slug_field = 'ask_slug' slug_url_kwarg = 'user_slug' model = UserAsking queryset = UserAsking.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['my_question'] = UserAsking.objects.get(title=self.object) self_post = UserAsking.objects.get(title=self.object) post_slug = UserAsking.objects.get(ask_slug=self_post.ask_slug) context['summation'] = post_slug.likes.count() - post_slug.dislikes.count() context['comment_form'] = CommentForm comments_count = Comment.objects.filter(userasking=UserAsking.objects.get(title=self.object)) context['comments_count'] = comments_count.count() # liked_post = User.objects.get(username=self.request.user.username).likes.exists() # context['liked_post'] = liked_post # disliked_post = User.objects.get(username=self.request.user.username).dislikes.exists() # context['disliked_post'] = disliked_post return context def post(self, request, user_slug, *args, **kwargs): my_question = UserAsking.objects.get(ask_slug=user_slug) userprof = UserProfile.objects.get(userasking__ask_slug=user_slug) comment_form = CommentForm(request.POST, instance=request.user) name = "%s %s" % (self.request.user.first_name, self.request.user.last_name) username = self.request.user.username logo = self.request.user.userprofile.logo.url c = CommentForm(self.request.POST).add_error('comment', 'error') if comment_form.is_valid(): comment_form = Comment.objects.create(comment=self.request.POST.get('comment', None), userasking_id=my_question.id, userprofile_id=userprof.id, name=name, username=username, logo=logo, comment_slug=my_question.ask_slug ) comment_form.save() return redirect('community:question_view', comment_form.userasking.ask_slug) return render(request, 'community/question_view.html', {'comment_form': … -
Django REST: Custom field, list may not be empty
I'm trying to add the employees field to my custom user model in Django REST 2.2. This is how I implemented my custom user (first answer). The employees field is just a list of custom users (so it's related to itself, with a many-to-many relationship). When I try to add a custom user model from the django interface, it says "this list may not be empty". How can I make it so it can be empty? users/models.py class CustomUser(AbstractUser): employees = models.ManyToManyField("self", related_name='employees') users/serializers.py class CustomRegisterSerializer(RegisterSerializer): employees = serializers.RelatedField(read_only=True, many=True, required=False) def get_cleaned_data(self): data_dict = super().get_cleaned_data() data_dict['employees'] = self.validated_data.get('employees', '') return data_dict class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('id', 'email', 'employees') employees is not supposed to be read_only but if I remove it, I get the following error: AssertionError: Relational field must provide a `queryset` argument, override `get_queryset`, or set read_only=`True`. What does this mean exactly? How can I solve it? -
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend’ ^ SyntaxError: EOL while scanning string literal
hi i am getting the following error EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend’ ^ SyntaxError: EOL while scanning string literal my email settings under settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/mail_app/'), ] # email settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend’ EMAIL_HOST = 'smtp.dreamhost.com’ EMAIL_USE_TSL = True EMAIL_PORT = 465 EMAIL_HOST_USER = 'dm@matrixhrservices.com' EMAIL_HOST_PASSWORD = 'Test2020' -
Model for Category> SubCategory>Sub-sub Category>Product in Django
I created a model in Django with Category > SubCategory > Sub-sub Category > Product in Django , but not enough sure is it the right way of doing it. here it is: class Category(models.Model): name = models.CharField(max_length=200) date_created = models.DateTimeField(auto_now_add=True) class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete = models.SET_NULL, null=True) name = models.CharField(max_length=200) date_created = models.DateTimeField(auto_now_add=True) class ProductCategory(models.Model): category = models.ForeignKey(SubCategory, on_delete = models.SET_NULL, null=True) name = models.CharField(max_length=200) date_created = models.DateTimeField(auto_now_add=True) class Product(models.Model): category = models.ForeignKey(ProductCategory, on_delete = models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True) photo = models.ImageField(upload_to="products/%y/%m/%d/", null=True) cover_photo = models.ImageField(upload_to="products/%y/%m/%d/", null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=False) Please view the code and tell me its potential errors. Thanks ... -
Reverse for 'delete_task/{{todo.id}}' not found. 'delete_task/{{todo.id}}' is not a valid view function or pattern name
I am new in django and I have following issue after running: Reverse for 'delete_task/{{todo.id}}' not found. 'delete_task/{{todo.id}}' is not a valid view function or pattern name. In my template file index.html I have: <form action="{% url 'delete_task/todo.id'%}" method="post" class = 'delete-link'> {% csrf_token%} <button type="submit">Delete</button> </form> My urls.py: urlpatterns = [ path('delete_task/<int:todo_id>', views.delete_task, name='delete_task'), ] My views.py: def delete_task(request, task_id): return HttpResponse(task_id) #the delete_task block is just for test Thank you -
Custom url based off single html input without JS
So I have probably the simplest task you could ever wish for with an html form that I cannot solve. I want to input a brand name into a search bar, click submit and it redirect to the url/brand/[input] I already have a working view for the urls setup in django. How would I structure the form to actually create my desired url? <form method="GET" action=""> <input type="text" name="brand" id="brand" placeholder="Search..." aria-label="Search"> <button type="submit">Search</button> </form> -
Page previous in Detail View for Detail View - Django
I'm have a page Detail View with a button with link for Detail View. But like the url need a PK, i cannot set PK per be a Detail View. How can I define a url for the previous page without the PK ? In Template <button id="botaoVoltar" type="submit" class="mb-10 btn btn-light"><a href="{% url 'relatorio' ??? %}">Voltar</a> </button> In urls path('relatorios/relatorio/<int:pk>', RelatorioView.as_view(), name='relatorio') Exception: NoReverseMatch Exception Value: Reverse for 'relatorio' with no arguments not found. 1 pattern(s) tried: ['relatorios/relatorio/(?P[0-9]+)$'] -
removing model fields from third party apps in django
I had installed dj-places app into my django project to have PlacesField() to autocomplete the locations field in my model. It did not work as expected. I uninstalled the app and changed the field to models.CharField(). The problem is whenever I am trying to make further migrations I am getting an error. posts\migrations\0007_auto_20200709_1445.py", line 4, in <module> import places.fields ModuleNotFoundError: No module named 'places' How can I resolve this? -
Previously used django-tenants but now looking to switch to hosting standalone apps
So I've been working on an application that was making use of Django tenants but I've realized that's not a feasible option anymore. Different customers want different model options and it started getting very cluttered just adding flags for customization but I thought I could work with it since I really liked the simplicity of django-tenants. However, now I've realized I want to offer customers things like different languages for model classes, customized layouts of pages or added features at an extra fee. They would all rely on the same logic or service I provide but other than that I would want to work together with them on how they want to 'experience' things. So now I've removed all mentions of django-tenants and the app runs like normal for just one test customer but I'm at a standstill trying to decide on how to move forward. Is creating a new app inside the project for every new customer a feasible idea? Instead of sharing a database like in tenants they would all need their own but I would still want to host them on subdomains. If I own example.com and then get a customer X I would want to create … -
React app not communicating wiht django api
I am running two apps on same server, one on port 3000[react] and another on port 8000[django]. react is my frontend that is communicating with backend in django. My domain name linked with this linode is 'example.com' and it is using an ssl certificate from let's encrypt. When i go to my domain via a browser i can access data if i go to http://example.com but if i go on https://example.com it doesn't give any data. I couldn't find any relevant tutorials online regarding this. I am using nginx to point at port 3000. -
Data access permissions table?
I have a web application that uses an API (using Django + DRF) to query a materialized view called Data. I need a way to restrict data requested against the current user (the user that requested the data). This is a simple problem if the rows I was restricting were all a single datatype. For example, I'd just have a permissions table Group Data Permissions --------------------------- group_id field value And then do some inner joins to filter the data. But, the Data table contains a lot of different columns with a lot different datatypes. I have to be able to create and grant permissions to groups for all those columns. That includes giving users permissions to get rows from Data based on a condition. For example, if my Data table has a columns type and date, I need to be able to assign permissions in the form of "allow this user group access to rows where Data.date >= 1/1/2020 and Data.type = 'some_type'". Is this possible to do with a single table?