Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django translations does not work for html templates
The project running Django 4.1 with the settings below: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.locale.LocaleMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', ... ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.i18n', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LANGUAGE_CODE = 'uk' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = ( os.path.join(BASE_DIR, '/locale'), os.path.join(BASE_DIR, 'apps/hub/locale'), ) LANGUAGES = ( ('uk', _('Українська')), ('en', _('English')), ) I run makemessages and compilemessages and get dajngo.po file with the following content: Two items below are from html and are not changing upon language has changed. #: .\templates\_footer.html:14 .\templates\_header.html:12 msgid "Головна" msgstr "Home" #: .\templates\_footer.html:15 .\templates\_header.html:13 msgid "Про нас" msgstr "About" But this item below does work: #: .\apps\hub\views.py:19 msgid "Выход" msgstr "Exit" All html files except base.html start with {% load i18n %}, have tags {% translate "Головна" %} Do I miss something? -
Django - UpdateView: After update by not superuser person who create get change on none
my problem is when i update my model by class MovieUpdateView(UpdateView) and i am not superuser, person who create get change on None when i want him stay old. Ik that issue is that i only change this field in tempalte only for superuser but don't know how to change it. views: class MovieUpdateView(UpdateView): model = Movie template_name = 'movies_collection/form_movie_update.html' fields = ['title', 'gender', 'youtube_trailer_url', 'user', 'director'] success_url = reverse_lazy('movie-list') template: <form method="post" novalidate> {% csrf_token %} <div class=""> <p> Title: <b>{{ form.title }}</b> </p> <p> Gender: <b>{{ form.gender }}</b> </p> <p> YouTube trailer url: <b>{{ form.youtube_trailer_url }}</b> </p> <p> Director: <b>{{ form.director }}</b> </p> {% if user.is_superuser %} <p> User: <b>{{ form.user }}</b> </p> {% endif %} <button type="submit" class="btn btn-primary btn-block">Submit</button> </form> -
Django Rest Framework - Create object with foregin key relation
I created simple REST API which i want to create product objects. My problem is that API view is not showing me multiple choice field to choose from existing categories. models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Meta: ordering = ('name',) class Product(models.Model): name = models.CharField(max_length=200, unique=True) price = models.PositiveSmallIntegerField(default="") category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, default=None) def __str__(self): return self.name class Meta: ordering = ('name',) serializers.py from rest_framework import serializers from .models import Product, Category class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' views.py from django.shortcuts import render from django.http import HttpResponse from rest_framework import viewsets from .models import Product, Category from .serilaizers import ProductSerializer, CategorySerializer from rest_framework.response import Response from rest_framework.views import APIView class ProductView(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer class CategoryView(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer That is what i get after running server, only two positions -
Django MultiValueField and MultiWidget AttributeError: 'CharField' object has no attribute 'is_hidden'
I am trying to make a field that can select a day of the week and a time of that day. I read the document and this is what I managed to do. class ClassTimeWidgit(forms.MultiWidget): def __init__(self, attrs=None) -> None: widgets = [forms.CharField(), forms.TimeField()] super(ClassTimeWidgit, self).__init__(widgets, attrs) class ClassTimeField(forms.MultiValueField): widget = ClassTimeWidgit def __init__(self, **kwargs) -> None: f = ( forms.CharField(widget=forms.Select(choices=[ ('Monday', 'Monday'), ('Tuesday', 'Tuesday'), ('Wednesday', 'Wednesday'), ('Thursday', 'Thursday'), ('Friday', 'Friday'), ('Saturday', 'Saturday'), ('Sunday', 'Sunday'), ]) ), forms.TimeField(input_formats='%H:%M') ) super().__init__(fields=f, require_all_fields=True, **kwargs) class RequestCourseForm(forms.ModelForm): teacher = forms.ModelChoiceField(queryset=User.objects.filter(profile__teacher_status=True)) class_count = forms.IntegerField(widget=forms.Select(choices=[(10,10), (20,20)])) class_time = ClassTimeField() class Meta: model = Request fields = ['teacher', 'class_count', 'class_time'] Before I had the MultiValueField on its own and it displayed a one-line textbox, so I added the MultiWidget class and it is giving me this error AttributeError: 'CharField' object has no attribute 'is_hidden' I am new to Django, please point out any obvious mistakes that you see, and please let me know if there is a better way to do what I am trying to do. -
Save ImageField to different folders
I have two models that inherit from a Base model as following ''' games = [ ('DND5E', 'Dungeons and Dragons'), ('TOR20', 'Tormenta20'), ] class BaseSheet(models.Model): ... game: str = models.CharField(default='', max_length=5, choices=games) ... class DnDMonster(BaseSheet): ... image = models.ImageField(upload_to='images/monsters/DnD5e') ... class Tor20Monster(BaseSheet): ... image = models.ImageField(upload_to='images/monsters/Tor20') ... ''' The way i'm thinking it, it's more organized that way, so I can place images from different games in different folders, not one giant folder with everything in it I am having some problems when I want my client to see everything that inherits from BaseSheet and the their images, so I want to put this ImageField in the BaseSheet. When I try to do that, it seems I can't put the images in different folder depending on the game the Monster has. Is there a way to do so? Is there a better way to do it? -
Dynamic URL routing from html form within action in Django
I have a simple form which shall take a user input and directly send the user to a dynamic url using the input. Inputing "111" into the form shall send the user to /number_input=111 Somehow i can not get it done, since i do not know how to get direct variable value from the form to the view immediately. I can build it with 2 views but that looks somehow ugly and inconvenient. Here is what i have so far: The Form: (within index.html) <form action={% url 'my_view'%} method="POST"> {% csrf_token %} <p><input type="text" name="inp_number" placeholder="Insert Number"/></p> <p><input type="submit" value="Submit"/></p> </form> views.py: def number_view(request): if request.method == 'POST': context = {'number': request.POST['inp_number']} return render(request, 'number.html', context) urls.py from . import views urlpatterns = [ path('number_input=<int:number>/', views.number_view, name='number_view') ] The dynamic part here (int:number) will make the code fail, since iam not sending a value from the form, right? But i only know how to send static values (i.e. action={% url 'my_view' 111 %}. How can i send direct dynamic values from the form itself (the value that the user inputs in the submit button)? number.html <h2>This page is for number {{ number }}</h2> -
About customizng drop down menu information in django import export module
Please consider this a book library website, I have three models here: models.py class books(models.Model): book_name = models.CharField(verbose_name='book name',max_length=24) book_desc = models.CharField(verbose_name='book description',max_length=240) class classes(models.Model): class_name = models.CharField(verbose_name='class name',max_length=24) class map_book_class(models.Model): book_id = models.ForeignKey(books, on_delete=models.CASCADE, verbose_name='book ID') class_id = models.ForeignKey(classes, on_delete=models.CASCADE, verbose_name='class UID') Here are some simple explains for the model: The first model is for adding new books, including it's name and book description, the model id will be generated automaticly by django. The second model is for adding new categories for the book, for example: recipes, toolbooks... etc. The model id will be generated automaticly by django too. The third model is for a mapping table, which connects the book data added by the first model, and the category data added by the second model together by using ids from above two models as foreign keys. After this, the data should be mapped together like this: John's Story(book name), Adventures(category). My question is, after I successfully built up those three models, and I added following data by using the django admin page. books id book_name book_desc 1 John's Story a story for kids. 2 Best recipes good foods. classes id class_name 1 Adventures 2 Toolbooks By using the … -
Cant connect to mysql [Access denied for user 'root'@'localhost' (using password: YES)] when using pytest to test django project running on wsl2
I'm using wsl2 to run my django project and I'm using dotenv to hide the project credentials like MYSQL database password cause I don't want these data on github enter image description here and this is my settings file enter image description here It was working and I could run my migrations, but the weirdest error I have run into when I tried to use pytest enter image description here when i tried to run tests gives me access denied enter image description here but when I tried to add the password in the database settings enter image description here It connected to my database and my tests passed enter image description here I tried every thing but it was useless, if anyone could help I would be gratefull. -
Why My Django Code Is Not Going To Else Part?
Here Is My views.py Where I written User Login Code And The Promblem I'm Facing Is That The Code Is Working Properly For Authenticating User But When User Enter Wrong Credential then I Want User To Take Him/Her To Register Page But I'm Unable To Take It To Register Page Please Help Me Thorugh This And Let Me Know Where I'm Doing Mistake def user_login(request): if request.method == "POST": fm = AuthenticationForm(request=request,data=request.POST) if fm.is_valid(): uname = fm.cleaned_data['username'] pword = fm.cleaned_data['password'] user = authenticate(username=uname,password=pword) if user is not None: login(request,user) return HttpResponseRedirect('/profile/') else: return HttpResponseRedirect('/register/') else: fm = AuthenticationForm(request) return render(request,'login.html',{'form':fm}) Here Are My urls.py from . import views urlpatterns = [ path('',views.index), path('register/',views.user_register,name='user_register'), path('login/',views.user_login,name='user_login'), path('profile/',views.user_profile,name='user_profile'), ] -
django custom forms with models, also with 'choices' as values, how should I approach this problem?
django forms is giving me a pretty bad headache... I've been struggling with this for 2 hours now. I wanted to make a custom form for a model to be able to add objects to it and also be able to move the fields as I want to (instead of using form.as_p (or form|crispy), I wanted to put the entire form in a grid-like table using a custom pattern, not only putting one under another) but whenever I put a choicefield (which is either a choicefield or a foreignkey) their values are empty and also, 3 out of 4 formfields are actually shown, one remains the default. It contains fields='__all__' with 3 choicefields and 1 floatfield each with a label, nothing more. To show the forms in html I used {% for field in form.visible_fields %} {{ field.label_tag }} {{ field.errors }} {{ field }} {{ field.help_text }} {% endfor %} which works well. Am I trying to solve the problem in a wrong way? I'll come back to this topic tomorrow, I'll need some rest now but I don't understand why passing a choices=TheModel # or # choices=TheModel.ojbects.all() breaks the entire thing. Is there a website or a youtube … -
How do I collect all my Django data from the database before invoking my serializer?
I'm using Python 3.9 and Django 3.2. I have a Django model with a couple of many-to-many relationsips class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) addresses = models.ManyToManyField(Address, through='CoopAddressTags') enabled = models.BooleanField(default=True, null=False) phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone') email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email') web_site = models.TextField() description = models.TextField(null=True) approved = models.BooleanField(default=False, null=True) proposed_changes = models.JSONField("Proposed Changes", null=True) reject_reason = models.TextField(null=True) I can search for my model using a manager class that builds a query like so ... def find( self, partial_name, types_arr=None, enabled=None, city=None, zip=None, street=None, state_abbrev=None ): """ Lookup coops by varying criteria. """ q = Q() if partial_name: q &= Q(name__icontains=partial_name) if enabled != None: q &= Q(enabled=enabled) if types_arr != None: filter = Q( *[('types__name', type) for type in types_arr], _connector=Q.OR ) q &= filter if street != None: q &= Q(addresses__raw__icontains=street) if city != None: q &= Q(addresses__locality__name__iexact=city) if zip != None: q &= Q(addresses__locality__postal_code=zip) if state_abbrev != None: q &= Q(addresses__locality__state__code=state_abbrev) q &= Q(addresses__locality__state__country__code="US") queryset = Coop.objects.filter(q) print(queryset.query) return queryset In my view, I invoke and return the data using coops = Coop.objects.find(...) serializer = CoopSearchSerializer(coops, many=True) in which the serializer looks like class CoopSearchSerializer(serializers.ModelSerializer): ... … -
How to login to django auth account via the ContextTitleMixin
class SurveyListView(ContextTitleMixin, ListView): model = Survey title_page = 'Survey List' paginate_by = app_settings.SURVEY_PAGINATION_NUMBER['survey_list'] paginator_class = NewPaginator def get_queryset(self): user = authenticate(username='guest', password='guest11') self.request.user = user query = self.request.GET.get('q') if query: object_list = self.model.objects.filter(name__icontains=query) else: object_list = self.model.objects.all() return object_list def get_context_data(self, **kwargs): page_number = self.request.GET.get('page', 1) context = super().get_context_data(**kwargs) page_range = context['page_obj'].paginator.get_elided_page_range(number=page_number) context['page_range'] = page_range return context -
How can I optimize response time in this python code? (django)
The get_assets method obtains a list of assets from the database and for each item in the list calls the __build_asset_response method to build a response in dictionary format. However, when there are many assets, the time to do the build_asset_response is very high. Does anyone know a method to optimize the time? def get_assets(user, data): if data.get('asset_id'): assets = Asset.objects.filter(pk__in=data['asset_id']) return [__build_asset_response(asset) for asset in assets] assets = Asset.objects.filter(QueryHelper.filter_by_rol(user)) return [__build_asset_response(asset) for asset in assets] This is the buil_asset_response private method: def __build_asset_response(asset): asset_dict = { 'id': asset.pk, 'name': asset.name, 'accessibility': manage_accessibility.build_accessibility_type_response(asset.accessibility), 'folder': "", 'user_id': { 'id': asset.user.id, 'name': str(asset.user) }, 'organization': { 'id': asset.idOrganization.id, 'name': str(asset.idOrganization), }, 'asset_type_id': asset.idAssetType and __build_asset_type_response(asset.idAssetType) or {}, 'file': settings.MEDIA_URL + asset.archivo.name, 'tag_ids': [tag.name for tag in asset.tag_ids.all()], 'lastModified': timezone.localtime(asset.last_modified_date).strftime("%Y-%m-%d %H:%M:%S"), 'used_in_publication': asset.used_in_publication } if asset.idFolder: folder = manage_folder.build_folder_response(asset.idFolder) else: folder = '' asset_dict.update({ 'folder': folder, }) return asset_dict -
How can I get data to pop up using django
please how can I get attribut id_benevole Class Participer(Models) i need to show it in the pop up i use this method but nothing is displayed Thanks in advance This is -------->Models.py class Participer(models.Model): id_benevole = models.CharField(max_length=150,null=False,blank=False) id_mission = models.CharField(max_length=150,null=False,blank=False) participer = models.ForeignKey(Mission, on_delete=models.CASCADE,null=True,blank=True) # def __str__(self): def __str__(self): return self.id_mission This is ------->Views.py def getLB(request): participerss=Participer.objects.all() context={ 'participerss':participerss } print(participerss) return render(request, 'home/Association.html',context) This is ----------> Association.html {% for miss in missions %} <th scope="row">{{miss.id}}</th> <td>{{miss.nom}}</td> <td>{{miss.domaine}}</td> <td>{{miss.lieu}}</td> <td style="white-space: nowrap;width: 1%;" >{{miss.date_publier}}</td> <td style="text-align: center;">{{miss.nombre_participant}}</td> <td>{{miss.association.association.nom_association}}</td> <td><a type="button" class="btn btn-danger mt-5" data-bs-toggle="modal" data-bs-target="#myModal" class="col-11 text-center mt-3">Voir liste des bénévoles</a></td> <div class="modal mt-5" id="myModal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="d-flex justify-content-center text-danger"> <h4>Liste des bénévoles participants</h4> </div> {% for par in participerss %} <div class="modal-header"> {{par.id_mission}} {{par.id_benevole}} </div> {% endfor %} <div class="modal-footer"> <div class="col-11 text-center mt-3"> <input class="btn gradient-bg" type="submit" value="Confirmer"/> <input type="button" class="btn gradient-bg" data-bs-dismiss="modal" value="Annuler"/> </div> <div> </div> </div> </div> {% endfor %} -
Detected path traversal attempt - Django/Heroku(Bucketeer)
I'm getting this error when trying to upload using FileField. I'm using Bucketeer on Heroku to upload to an AWS bucket. I've seen a few threads on this issue but haven't been able to figure it out. The file upload view: class UploadTicketAttachment(APIView): permission_classes = [] parser_classes = (MultiPartParser, FormParser) def post(self, request, format=None): user = request.user serializer = AttachmentSerialiazer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.validated_data['uploaded_by'] = user serializer.save() return Response(serializer.data['id']) else: return Response(f'{serializer.errors}, attachment upload failed') The model: class Attachment(models.Model): file = models.FileField(upload_to="/ticket_attachments", blank=True, null=True) created_on = models.CharField(max_length=20, null=True) uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, related_name="uploaded_by") parent_ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE, null=True, related_name="attachment") def __str__(self): return self.file.name For the settings/bucketeer configuration I followed which uses django-storages: https://dev.to/heroku/properly-managing-django-media-static-files-on-heroku-o2l I don't think the issue is on that end since I set it up the exact same way in another project and it works fine with the only difference being that the other project uses ImageField instead of FileField. Django version is 4.0.2. Any ideas? Thanks -
My own backend sends two Objects instead of one in http response?
I got a backend in django wich is supposed to send me data, but instead of one object I get two objects (inside of the http response). The weird thing about that, is that it does not happen all the time, sometimes its just one and sometimes there are two... This is how the response looks like (In the network analytics): { "id": 1, "sumScore": 270, "sumRequests": 55, "buttonOne": 55, "buttonTwo": 10, "buttonThree": 10, "buttonFour": 10, "buttonFive": 55, "buttonSix": 55, "buttonSeven": 55, "buttonEight": 10, "buttonNine": 10, "myResult": 4 }{ 'REDIRECT_REDIRECT_UNIQUE_ID': 'YxTgq5gPaMxcbxlxyS6l0QAAAAM', 'REDIRECT_REDIRECT_DOCUMENT_ROOT': '/kunden/homepages/29/d920390454/htdocs/MyWebsite', 'REDIRECT_REDIRECT_UI_SUEXEC_DEFAULT_CHROOT_ID': '14', 'REDIRECT_REDIRECT_UI_SUEXEC_FSTATD_UNIXSOCKET': '/run/ui-fstatd.suexec.socket', 'REDIRECT_REDIRECT_UI_SUEXEC_STATISTICS_UNIXSOCKET': '/homepages/sclientMF/http.sock.bin', 'REDIRECT_REDIRECT_HTTPS': 'on', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_CPU': '40', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_MEM': '768', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_PROCSOFT': '15', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_PROCHARD': '27', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_JIMDO': '800', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_CPU_JIMDO': '60', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_MEM_JIMDO': '768', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_PROCSOFT_JIMDO': '24', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_PROCHARD_JIMDO': '24', 'REDIRECT_REDIRECT_DBENTRY_HOST': 'api.tor-netzwerk-seminarfach2024.com', 'REDIRECT_REDIRECT_DBENTRY_VALUE': '/kunden/homepages/29/d920390454/htdocs/MyWebsite:d0000#CPU 6 #MEM 10240 #CGI 524360 #NPROC 12 #TAID 109180236 #LANG 0 #RSCLVL 300 #CHROOT 15', 'REDIRECT_REDIRECT_DBENTRY_DOCROOT': '/kunden/homepages/29/d920390454/htdocs/MyWebsite', 'REDIRECT_REDIRECT_DBENTRY_HASH': 'd0000', 'REDIRECT_REDIRECT_DBENTRY__CPU': '6', 'REDIRECT_REDIRECT_DBENTRY__MEM': '10240', 'REDIRECT_REDIRECT_DBENTRY__CGI': '524360', 'REDIRECT_REDIRECT_DBENTRY__NPROC': '12', 'REDIRECT_REDIRECT_DBENTRY__TAID': '109180236', 'REDIRECT_REDIRECT_DBENTRY__LANG': '0', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL': '300', 'REDIRECT_REDIRECT_DBENTRY__CHROOT': '15', 'REDIRECT_REDIRECT_DBENTRY': '/kunden/homepages/29/d920390454/htdocs/MyWebsite:d0000#CPU 6 #MEM 10240 #CGI 524360 #NPROC 12 #TAID 109180236 #LANG 0 #RSCLVL 300 #CHROOT 15', 'REDIRECT_REDIRECT_STATUS': '200', 'REDIRECT_UNIQUE_ID': 'YxTgq5gPaMxcbxlxyS6l0QAAAAM', 'REDIRECT_DOCUMENT_ROOT': '/kunden/homepages/29/d920390454/htdocs/MyWebsite', 'REDIRECT_HTTPS': 'on', 'REDIRECT_STATUS': '200', 'UNIQUE_ID': 'YxTgq5gPaMxcbxlxyS6l0QAAAAM', 'HTTPS': 'on', 'HTTP_HOST': 'api.tor-netzwerk-seminarfach2024.com', 'CONTENT_LENGTH': '48', 'HTTP_SEC_CH_UA': '" Not A;Brand";v="99", "Chromium";v="104", "Opera";v="90"', 'HTTP_SEC_CH_UA_MOBILE': … -
How to change membership status from active to expired after subscription end date in django
After the expiry date i would like to change the subscription status to inactive. So what is the best way to achieve this. My Subscription models as follows: class Subscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True) start_date = models.DateTimeField(_('Start Date'), null=True, blank=True) expiry_date = models.DateTimeField(_('Expiry Date'), null=True, blank=True) token = models.TextField(_('Token'), max_length=100, null=True, blank=True) active = models.BooleanField(_('Active'), default=False) Thanks! -
Django: Form submit button not loading blog post {{ post.slug }} value in second form
My Django template renders the post.slug value in the first 'edit' form button correctly but on the modal pop up for the 'delete' it does not. This was working a week or so ago. The 'Edit' button works perfectly, yet with almost identical code, under a Bootstrap modal (for confirmation of the post deletion) the 'Delete' button does not load the value="{{ post.slug }}" my template: {% extends "base.html" %} {% block content %} <div class="post-opinion"> <h3>{{ user }}'s Posts</h3> </div> <div class="container-fluid"> <div class="row"> <!-- Blog Entries Column --> <div class="col-12 mt-3 left"> <div class="row"> {% for post in post_list %} <div class="col-md-4"> <div class="card mb-4"> <div class="card-body"> <div class="image-container"> {% if "placeholder" in post.featured_image.url %} <img class="card-img-top" src="https://codeinstitute.s3.amazonaws.com/fullstack/blog/default.jpg"> {% else %} <img class="card-img-top" src=" {{ post.featured_image.url }}"> {% endif %} <div class="image-flash"> <p class="author">Author: {{ post.author }}</p> </div> </div> <a href="{% url 'post_detail' post.slug %}" class="post-link"> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text">{{ post.excerpt }}</p> </a> <hr /> <p class="card-text text-muted h6">{{ post.created_on}} <i class="far fa-heart"></i> {{ post.number_of_likes }}</p> <div> <form method="post"> {% csrf_token %} <button type="submit" class="btn btn-primary mt-3" value="{{ post.slug }}" name="edit">Edit</button> <button type="button" class="btn btn-danger mt-3" data-toggle="modal" data-target="#delete-confirmation"> Delete </button> </form> </div> </div> </div> </div> {% … -
How can I post data to my view function using AJAX and return html view using the data I send
at java script I have a function and inside the function I have this code. datam = {'username' : username , 'usernameId' : id} url = `http://127.0.0.1:8000/chat/dms/` datam=JSON.stringify(datam) $.ajax({ type: "POST", url: url, data: datam , headers: {'X-CSRFToken': csrftoken}, mode: 'same-origin', contentType: "application/json", cache:false, error: function(xhr, status, error) { console.log('!212') }, complete: function (response) { roomid=response.responseJSON.data console.log(roomid) window.location.href =`http://127.0.0.1:8000/chat/${roomid}/` console.log('completed') } }); and in the views I have this code def chat_room(request ,room_name): oda = room.objects.get(id= room_name) messages = message.objects.filter(room=oda) chat = room.objects.filter(id = room_name).first() print(chat) #return JsonResponse({'room_name' : room_name} ,status= 200) return render(request , 'chatroom.html' , {'a' : chat , 'messages' : messages}) But I cant render the html page ı wanted. Ajax gives error. How Can I render html page using the data That I send via AJAX. How can I post data to my view function using AJAX and return html view using the data I send -
How to add text into a link in src=" "
I have this src="https://open.spotify.com/embed/track/1Go9q6KaCpAsQ0wkZFGzY2?utm_source=generator" and I want it to be like this src="https://open.spotify.com/embed/track/{{ spotify_trackid }}?utm_source=generator" how can I do this using django without it breaking the link? sorry for the bad explanation i'm pretty new to this -
how to return result to html django
I want to make text file contains with b'Y\xf5\x11m' (it's result from encryption). And I want txt file can be downloaded using html. But I got next error when I return it: 'int' object has no attribute 'get' Here's the code: def create_file(f): with open("file.txt", 'w') as file: download = file.write(str(f)) print(download) return download I called that func like this: #in views download = create_file(enc) print(download) #in urls path("create_file", views.create_file, name="create_file"), #in html <a href="{% url 'create_file' %}"> -
django CK-Editor not working in production shared hosting
My Django application has a django-ckeditor which seemed to work fine in the local host but dosent work in the production enviornment . I have used proper static path settings cause all of my other static files are loading properly . but the ck-editor is not working fine . This is my settings.py file . STATIC_URL = '/static/' # Add these new lines STATIC_ROOT = "/home/username/public_html/static/" MEDIA_URL = '/media/' MEDIA_ROOT = "/home/username/public_html/media/" CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_BASEPATH = "/home/username/public_html/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = 'uploads/' This is my wsgi.py file import os from django.core.wsgi import get_wsgi_application from whitenoise import WhiteNoise os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hrnindia.settings') application = get_wsgi_application() application = WhiteNoise(application, root="/home/username/public_html/static/") application.add_files("/home/username/public_html/static/ckeditor/ckeditor/", prefix="more-ck-files/") application.add_files("/home/username/public_html/static/ckeditor/", prefix="more-files/") I have tried out all the other solutions like configuring the path and using whitenoise . But nothing seems to make the ck-editor work . -
Best practice for Python typing out of dictionary (self.fields type in Django ModelForm)
I have a form like this class MerchantBrandsForm(forms.Form): brands = forms.ModelChoiceField(required=True, queryset=None) def __init__(self: merchant: Merchant): self.fields['brands'].queryset = merchant.brands.all() But I have an error with mypy with the queryset as fields has a type Dict[str, Field], which cause error: "Field" has no attribute "queryset". I know I can cast the fields using cast or ignore the typing, but I don't think this is a clean solution. What is the best way to assign brands queryset without ignoring the type or using cast function? -
AttributeError: 'NoneType' object has no attribute 'is_superuser'
I'm working with Django, and I keep getting this error when trying to create a new superuser inside the terminal: AttributeError: 'NoneType' object has no attribute 'is_superuser' I've tried everything I've looked up to fix it. No luck. Also, this code is greyed-out inside my user model, and when I hover over the text it says: Code is unreachable Pylance if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) email = email.lower() user = self.model( email = email, name = name ) user.set_password(password) user.save(using=self._db) return user Here is my full user model: from abc import abstractmethod from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class UserAccountManager(BaseUserManager): @abstractmethod def create_user(self, email, name, password=None): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) email = email.lower() user = self.model( email = email, name = name ) user.set_password(password) user.save(using=self._db) return user def create_realtor(self, email, name, password=None): user = self.create_user(email, name, password) user.is_realtor = True user.save(using=self._db) return user def create_superuser(self, email, name, password=None): user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) # … -
'utf-8' codec can't decode byte 0xa0 in position 0: invalid start byte django
so i have variable contains in bytes and i want to save it to str. but how to do it? i tried various kinds of ways, but always got error 'utf-8' codec can't decode byte 0xa0 in position 0: invalid start byte i want to save the result encrypt file to text file. so i have the proof it the file was encrypt. here;s my ways 1: def create_file(f): response = HttpResponse(content_type="text/plain") response['Content-Disposition'] = 'attachment; filename=file.txt' filename = f print(filename) name_byte = codecs.decode(filename) print(name_byte) return response my ways 2 : def create_file(enc): with open("file.txt", "w", encoding="utf-8") as f: enc = enc.decode('utf-8') f.write(enc) my ways 3: def create_file(f): file = open("file.txt", "w") f = f.decode('utf-8') download = file.write(f) file.close() print(download) return download f = b'\xa0\x0e\xdc\x14' f is the return result of encrypt