Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django redirect and modify GET parameters
I am implementing magic tokens and would like clean URLs. As a consequence, I would like to remove the token from the URL upon a successful user authentication. This is my attempt: def authenticate_via_token(get_response): def middleware(request): if request.session.get('authenticated', None): pass else: token = request.GET.get('token', None) if token: mt = MagicToken.fetch_by_token(token) if mt: request.session['authenticated'] = mt.email if not request.GET._mutable: request.GET._mutable = True request.GET['token'] = None request.GET._mutable = False else: print("invalid token") response = get_response(request) return response return middleware IE, I would like to send /products/product-detail/3?token=piyMlVMrmYblRwHcgwPEee --> /products/product-detail/3 It's possible that there may be additional GET parameters and I would like to keep them. Any input would be appreciated! -
Django/Js Direct to s3 App, Getting the Error: "The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256"
Have read all the posts here and elsewhere on this, tried everything I can find out there, and still can't figure my issue when trying to pass the s3v4 signature version. I get the presigned url ok then get the 400 error when I go to post the files to the bucket. I've used the same setting for a django project that uploads through the sever and have no issues. Am trying to pass the necessary fields in through the view below. Tried passing them in form in the html as well. No matter what I do the 'signature' in the network header logs doesn't change it's format. [![Network Headers Log][1]][1] View to get the presigned url and pass the post form fields: def sign_s3(request): if request.method == 'GET': file_name = request.GET.get('file-name') file_type = request.GET.get('file-type') file = File.objects.create(name=file_name) key = file.key file_url = 'https://{bucket}.s3.{region}.amazonaws.com/{key}'.format(bucket=S3_BUCKET, key=key, region=AWS_S3_REGION_NAME) url = 'https://{bucket}.s3.amazonaws.com'.format(bucket=S3_BUCKET) s3 = boto3.client('s3') presigned_post = s3.generate_presigned_post( Bucket=S3_BUCKET, Key=key, Fields={ "x-amz-algorithm": 'AWS4-HMAC-SHA256', "x-amz-credential": '{key}/{date}/{region}/s3/aws4_request'.format( key=S3_ACCESS_KEY, date=date, region=AWS_S3_REGION_NAME), "x-amz-date": '{date}'.format(date=date), "acl": "public-read", "Content-Type": file_type, }, Conditions=[ {"x-amz-algorithm": 'AWS4-HMAC-SHA256'}, {"x-amz-credential": '{key}/{date}/{region}/s3/aws4_request'.format( key=S3_ACCESS_KEY, date=date, region=AWS_S3_REGION_NAME)}, {"x-amz-date": '{date}'.format(date=date)}, {"acl": "public-read"}, {"Content-Type": file_type}, ], ExpiresIn=3600, ) presigned_post['url'] = url return HttpResponse(json.dumps({ 'data': presigned_post, 'url': file_url })) else: … -
URI Malformed Parcel Relative Module import
Relative import not being formed with correct URI when running parcel build/watch resulting in incorrect /trends/static/src/Shared/SiteHeader.vue not the correct /static/src/Shared/SiteHeader.vue /static/src/app.js … # here is where error is occurring import SiteHeader from './Shared/SiteHeader' … parcel is building off these commands in package.json … "scripts: { "watch": "parcel watch ./static/src/* -d ./static/dist/", "build": "parcel build ./static/src/* -d ./static/dist/", … Expected Behaviour: running npm run build should build my components so there are the main page components (which it does when the line causing the error is gone) AND be able to import from the Shared components What's Actually Happening: running npm run build errors out with /trends/static/src/Shared/SiteHeader.vue: URI malformed visiting mysite.com/static/src/Shared/SiteHeader.vue results in a download of the file notice the uri does not start with /trends, why is /trends being put on the URI? Full Error Trace: /trends/static/src/Shared/SiteHeader.vue: URI malformed at decodeURIComponent (<anonymous>) at HTMLAsset.resolveDependency (/trends/node_modules/parcel-bundler/src/Asset.js:94:22) at HTMLAsset.addURLDependency (/trends/node_modules/parcel-bundler/src/Asset.js:119:38) at HTMLAsset.processSingleDependency (/trends/node_modules/parcel-bundler/src/assets/HTMLAsset.js:99:26) at /trends/node_modules/parcel-bundler/src/assets/HTMLAsset.js:187:43 at traverse (/trends/node_modules/posthtml/lib/api.js:105:26) at traverse (/trends/node_modules/posthtml/lib/api.js:111:5) at traverse (/trends/node_modules/posthtml/lib/api.js:105:17) at traverse (/trends/node_modules/posthtml/lib/api.js:111:5) at traverse (/trends/node_modules/posthtml/lib/api.js:105:17) at Array.walk (/trends/node_modules/posthtml/lib/api.js:39:10) at HTMLAsset.collectDependencies (/trends/node_modules/parcel-bundler/src/assets/HTMLAsset.js:138:9) at HTMLAsset.getDependencies (/trends/node_modules/parcel-bundler/src/Asset.js:81:18) at async HTMLAsset.process (/trends/node_modules/parcel-bundler/src/Asset.js:215:7) at async Pipeline.processAsset (/trends/node_modules/parcel-bundler/src/Pipeline.js:46:7) at async Pipeline.processAsset (/trends/node_modules/parcel-bundler/src/Pipeline.js:74:25) -
How to make the web page title TAB in the browser + the URL changes depends on the title of the article opened, in DJANGO
Hello coders, I am making a blog in Django framework, My problem is that when i make new post or article and i enter to the page of the post ( the single post page ) My blog tab title in the browser doesnt change to the title of the article and the same thing with the URL too thank u all -
How to delete django model data on button click
I am creating a donation application. I have a screen in which people can click on if they want to learn more about a specific donation. On that screen, I have the following button: <button class="btn btn-success"onclick="showAlert()">Accept</button> . When this button is clicked, I bring up a confirmation alert, which is down bellow. (it uses swal to style but functions like a regular alert). When the alert comes up, if the user clicks the ok button, I want to delete the data that they are currently viewing and redirect them to another page. I am struggling with this, because I am not sure how to do this. Many people have said to use AJAX, but it does not seem to work. Javascript alert: swal({ title: "Accept Donation", text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?", icon: "info", buttons: true, }) .then((ok) => { if (ok) { swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", { icon: "success", }); } }); } URL: (This is the unique url that renders the donation) path('donations/<int:pk>/', views.DonationDetail.as_view(), name='donation-detail'), I … -
Django how to delete sender from list
I am using django signals for create an notifications system.I want to delete sender from list if his status sender and receiver same. Let you explain Mr. Jhone send an message to all users and Mr Jhone aslo included in all user group. So I want to remove Mr. Jhone from list of all user. Here I tried this code but didn't work: if sender in notifications: #here I am trying to remove sender from notifications list notifications.remove(Notifications(sender=sender, receiver= receiver,text_preview=text,notification_type="global_noti")) here is my full code: def global_noti(sender, instance, *args, **kwargs): global_notify = instance sender =global_notify.user receivers = User.objects.all() text = global_notify.text if global_notify.is_published == 'global_notification': notifications=[] for receiver in receivers: notifications.append(Notifications(sender=sender, receiver= receiver,text_preview=text,notification_type="global_noti")) if sender in notifications: #here I am trying to remove sender from notifications list notifications.remove(Notifications(sender=sender, receiver= receiver,text_preview=text,notification_type="global_noti")) Notifications.objects.bulk_create(notifications) -
Using django-filter generic view and paginate_by, how to build the pagination urls?
First time using django-filter, so I might be using it wrong. I'm basically trying to mimic Django Admin filtering, using a generic FilterView, setting filterser_class and adding paginate_by filters.py class ProductFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains', label='Filter by Title') categories = django_filters.AllValuesFilter( field_name='categories__name', label="Filter by Category", widget=django_filters.widgets.LinkWidget(attrs={'class': 'list-menu'}), ) brand = django_filters.AllValuesFilter( field_name='brand__short_name', label="Filter by Brand", widget=django_filters.widgets.LinkWidget(attrs={'class': 'list-menu'}), ) class Meta: model = Product fields = ['categories', 'brand', 'name'] views.py class ProductFilterView(FilterView): filterset_class = ProductFilter paginate_by = 20 product_filter.html <section class="section-content padding-y"> <div class="container"> <div class="row"> <aside class="col-md-3"> <div class="card"> <form method="get"> {% csrf_token %} {% for field in filter.form.visible_fields %} <article class="filter-group"> <header class="card-header"> <a href="#" data-toggle="collapse" data-target="#collapse_1" aria-expanded="true" class=""> <i class="icon-control fa fa-chevron-down"></i> <h6 class="title">{{ field.label_tag }}</h6> </a> </header> <div class="filter-content collapse show" id="collapse_1"> <div class="card-body"> {{ field }} </div> <!-- card-body.// --> </div> </article> <!-- filter-group .// --> {% endfor %} <input type="submit" class="btn btn-block btn-primary" value="Filter"/> </form> </div> <!-- card.// --> </aside> <!-- col.// --> <main class="col-md-9"> <header class="border-bottom mb-4 pb-3"> <div class="form-inline"> <span class="mr-md-auto">{{ filter.qs | length }} products found </span> </div> </header><!-- sect-heading --> <div class="row"> {% for obj in page_obj %} <div class="col-md-4"> <figure class="card card-product-grid"> <div class="img-wrap"> <img src="/media/{{ obj.productimage_set.first.image|default:'products/missing.png' }}"> </div> <!-- img-wrap.// … -
next steps after deploying Django and react app to Azure app service
I am failry new to Clouad Service and I have a React and Django web app running on Azure app service. Thing that I have done already. Django and react app up and running fine locally. 2 docker Images with 2 containers deployed into Azure App service. I have one azure resource registry and 1 app service with two docker containers (frontend and backend) Both react and django are up and running in azure app service and are accessible using similar to following urls. frontend.azurewebsites.net #This is just a sample name djangorestapi.azurewebsites.net #This is just a sample name I wanna publish this to public using domain. I am aware that I have to buy a domain and stuff. I would really appreciate if somebody can point out what are the next steps to follow. I wanna make it available to public. Also, with new changes I need to fix my React restapi endpoits which I made it using Django Rest Framework. -
Dynamic URL for user profiles /Django
I trying to make dynamic URL for my users page For Example: mypage/profiles/(username) I trying a < str> tag in my urls path but it not works. I have it usernames but i dont this send to url here i am getting this error: NoReverseMatch at / Reverse for 'users' with no arguments not found. 1 pattern(s) tried: ['users/(?P[^/]+)$'] VİEWS: from django.shortcuts import render def users(request,username): username = request.user # it's works return render(request, "profiles.html") URLS: from django.urls import path from . import views urlpatterns = [ path('users/<str:username>',views.users, name="users"), ] -
How to use inter-process communication in django with discord.py and discord-ext-ipc
I'm currently using discord-ext-ipc as an inter-process communication (IPC) extension for discord.py and linked this with quart-discord. Quart is an asyncio reimplementation of Flask and can natively serve WebSockets and other asynchronous stuff. I can so easily use a Web-Frontend as a Dashboard to interact with the discord users on a guild. Doing fun stuff like, using the discord role model for a permission model at the dashboard. Recently I stumbled over django and got hooked up with that powerful framework. As a learning project, I wanted to port the current working project into django but I stumbled over some impasses. First the working example with discord-ext-ipc and quart-discord: bot.py import logging import discord from discord.ext import commands, ipc intents = discord.Intents.default() logging.basicConfig(level=logging.DEBUG) TOKEN = DISCORD_TOKEN class MyBot(commands.Bot): def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.ipc = ipc.Server(self,secret_key = IPC_SECRET_KEY) async def on_ready(self): """Called upon the READY event""" print("Bot is ready.") async def on_ipc_ready(self): """Called upon the IPC Server being ready""" print("Ipc server is ready.") async def on_ipc_error(self, endpoint, error): """Called upon an error being raised within an IPC route""" print(endpoint, "raised", error) my_bot = MyBot(command_prefix = ">", intents = intents, chunk_guilds_at_startup = False) @my_bot.ipc.route() async def get_guild_ids(data): final = [] for guild in … -
How to add Query String Auth on all files in Django with Amazon S3
I am using Django with Amazon s3 with Libraries(django-storages boto3) To be specific the base.css is being served and fonts.css is not being served(Err 403). This is happening in Django Admin Console. I have confirmed that the fonts.css is in the bucket The problem being these files don't have query string auth # This is working GET https://bucket-name.s3.amazonaws.com/static/admin/css/base.css?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AFD34GE4VTLUKQOTHAW7%2F20210726%2Fus-east-2%2Fs3%2Faws4_request&X-Amz-Date=20210726T193438Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=815bd068805f60f90c6acf27b24028424e85afbf7ba2939b51471cab2ba8e8b9 # This isn't working GET https://bucket-name.s3.amazonaws.com/static/admin/css/fonts.css Almost all static files are being served The fonts.css is not in the HTML page source and maybe is being called from a JS code that is not appending the Query String Auth Also when I shift from S3 to django default storage, it works perfectly fine. -
Django Slugs as principal url
I want to do the following, so that the profile of each registered user can be seen as follows: http://127.0.0.1:8000/username/ I was able to achieve this, the problem is when wanting to create another page, for example http://127.0.0.1:8000/explore/ Django consider "explore" as a user and throw me a 404 error. this is my urls.py urlpatterns = [ path("<slug:slug>/", PerfilView.as_view(), name="perfil"), path("explore/", UserListView.as_view(), name="explore"), ] Am I doing it the right way or am I unable to do this with django? Regads -
Replace Default PK slug with Multiple Lookup Fields for ModelViewSet
I have two slugs, against which I run queries. Thanks to base class MultipleFieldLookupMixin, which my view class is inherited from and thus allows me to have multiple lookup_fields. We know that when ModelViewSet is used with DefaultRouter, appends a pk at the end of URL, which I don't want. For example, when I do this: router = DefaultRouter() router.register(r'organization', OrganizationModelViewSet, basename='organization') urlpatterns = [ path('viewset/', include(router.urls)), path('viewset/<str:device>/<str:start_time>/', include(router.urls)) ] it gives me the URL mydomain.com/viewset/<str:device>/<str:start_time>/organization/<int:pk>/ I don't want this pk at the end. If we can remove organization, that's even better. I want the endpoint to be, mydomain.com/<str:device>/<str:start_time>/. More playing around, I learned that adding extra_kwargs like this in my serializer class, extra_kwargs = { 'url': {'lookup_field': 'start_time'} } and modify lookup_fields in view class, with singular lookup field, like lookup_field, with value let's say, start_time. To clarify, changing lookup_fields = ["device", "start_time"] with lookup_field = "start_time" and also modify the URL accordingly by removing the start_time slug, then URL becomes mydomain.com/viewset/<str:device>/organization/<str:start_time>/ modify singular lookup_field with org, apparently gives us more or less the desired URL, but doesn't get the job done because we have a single lookup_field now! mydomain.com/viewset/str:device/organization/str:start_time/ If we edit this line router.register(r'organization', DeviceActivityModelViewSet, basename='device_activity') to … -
How to implement only accepting username and token as request in django view and not password?
I have created a custom User model in Django that has username, email, password and some other fields. I am using jwt token which can be acquired from /token after providing valid username and password of a user. I have created a serializer for /authstatus and implemented it's view in views.py. Currently it works only when both username and password are provided with authentication token as header. Is there any way to ask only username and not password from user as a request for /authstatus? Code: Serializer: class AuthSerializer(serializers.ModelSerializer): password = serializers.CharField( required=True, style={"input_type": "password"}, write_only=True ) class Meta: model = get_user_model() fields = ["id", "username", "password", "auth_status"] read_only_fields = ["id"] Any help will be appreciated. Thank you! -
Add general [to all models] queryset method
I can create a new class from models.QuerySet to override a specific model queryset manager, but is it possible to write a method that applies to all models? For example: Every time i need to see the unique values of a variable, i need to write (*using SQLite) list(map(lambda v: v[my_var], qs.values(my_var).distinct().order_by())) But it would be nice to have something like my_queryset.unique_values(my_var) # Returns [value1, value2, value3, ...] Without having to specify it to every model -
How can i make a move button for a site created in django, html and python
How can i make a move button for a site created in django, html and python. To make myself better understood. I want to add the questions in categories. example: test 1 - 5 questions test 2 - 5 questions and so on but when I add the questions, they run one after the other this is the source - https://github.com/akashgiricse/lets-quiz -
TypeError: dispatch is not a function React and Redux
I get an error when I delete some lead(item). It deletes from the database but not from UI and gives this error dispatch is not a function. //lead.js from /action export const deleteLead = (id) => { return (dispatch) => { axios .delete(`/api/leads/${id}/`) .then((res) => { dispatch({ type: DELETE_LEAD, payload: id, }); }) .catch((err) => console.log(err)); }; }; //Frontend file import { getLeads, deleteLead } from "../../actions/leads"; <button onClick={deleteLead(lead.id)} className="btn btn-danger btn-sm"> Delete </button> -
How Do I connect a .tech domain to Heroku
I have entered the heroku apps dns to the .tech CNAME form in the Value box. My domain name worked after 10 minutes, but then it stopped working. Should I wait 24 hours (although the domain name has worked) or is there something I have done wrong? .tech CNAME panel: heroku panel: chrome tab: The only thing I have done is input the Heroku App DNS into the Value input in the CNAME form. Any help would be much appreciated. Thanks -
Django getting error when trying to save AbstractUser model
I want to save this AbstractUser in my model. class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) when trying to save before go makemigrations getting this error django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'auth.User.groups' clashes with reverse accessor for 'members.User.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'members.User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'auth.User.user_permissions' clashes with reverse accessor for 'members.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'members.User.user_permissions'. members.User.groups: (fields.E304) Reverse accessor for 'members.User.groups' clashes with reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'members.User.groups' or 'auth.User.groups'. members.User.user_permissions: (fields.E304) Reverse accessor for 'members.User.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'members.User.user_permissions' or 'auth.User.user_permissions why getting this error? how to solve it? I also tried to change model name class GlobalUser(AbstractUser) but getting same error -
RetrieveUpdateDestroy and get_queryset how works
i am learning drf and i little confused in the urls.py i have path('todos/<int:pk>', views.TodoRetrieveUpdateDestroy.as_view()), on the views.py class TodoRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView): serializer_class = TodoSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): user = self.request.user return Todo.objects.filter(user=user) by logic i would add to filter like pk = self.kwargs[‘pk’] to send only one element Todo but it works and send only that ‘id=pk’ post without adding additional filter.Can u explain why please and how works RetrieveUpdateDestroy and get_queryset) -
Why drf add underlines to serialized dictfield?
I use djangorestframework==3.9.4, I can't realize why drf changes serialized data (add underlines to field names before numbers and uppercase) # views.py: class RetrieveUpdateJsonFields(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): queryset = JsonFieldObject.objects.all() serializers = { 'default': JsonFieldRetriveSerializer, 'update': JsonFieldUpdateSerializer, } def get_serializer_class(self): return self.serializers.get(self.action, self.serializers['default']) # serializers.py: class JsonFieldUpdateSerializer(serializers.ModelSerializer): id = serializers.IntegerField() context = serializers.JSONField() class Meta: model = JsonFieldObject fields = ('id', 'context') def validate(self, data): """ for trace """ print(data["context"]) return data I try send put request, that contains next data: { "id":1, "context": { "floor_field": 27, "square2": 222, "oneAs": "Hello" } } in serializer I expected this: {'id': 1, 'context': {'floor_field': 27, 'square2': 222, 'oneAs': 'Hello'}} but got: {'id': 1, 'context': {'floor_field': 27, 'square_2': 222, 'one_As': 'Hello'}} how can I disable this behavior? -
Django Rest Framework serializer nested objects internal server error 500
I have three models like those: class Ambulance(models.Model): ambulance_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ambulance_name = models.CharField(max_length=255) forms = models.ManyToManyField(Form) class Form(models.Model): form_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) form_title = models.CharField(max_length=255) class Page(models.Model): page_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) page_title = models.CharField(max_length=100, default='Untitled Page') form = models.ForeignKey( Form, related_name='pages', on_delete=models.CASCADE, null=True ) And the serializers as follow: class AmbulanceSerializer(serializers.ModelSerializer): forms = FormSerializer(read_only=True, many=True) class Meta: model = Ambulance fields = fields = ['ambulance_id', 'ambulance_name', 'forms'] class FormSerializer(ModelSerializer): pages = PageSerializer(many=True, read_only=True) class Meta: model = Form fields = ['form_id', 'form_title', 'pages'] class PageSerializer(ModelSerializer): class Meta: model = Page fields = '__all__' They were working and give me the nested object that I wanted but after adding many-to-many relationships, it gives me an internal server error 500 and it didn't tell me what the problem was, after debugging I found the problem occurs when calling AmbulanceSerializer(ambulance) or FormSerializer(form) Could someone give me some hint? and what the problem actually! -
Azure AD with Django Rest Framework and React [dj-rest-auth allauth]
I'm trying to integrate Azure AD to an existing Django Rest Framework project. I found dj-rest-auth as a great solution for this purpose. It uses django-allauth. I managed to configure it on my Django project, but I have no idea which is the next step. So for now I have configured: urlpatterns = [ ... path(r'auth/azure', AzureLogin.as_view(), name='azure_login') ] which created a new endpoint with 3 optional parameters: access_token, code and id_token. I have also register an app on Azure Active Directory, but I have no idea how to proceed. Note: I am using React for front-end. -
Django Calendar Recommendation - HTMLCalendar no Weekly View
Disclaimer - New to programming, Python and Django. I have been researching calendar solutions for my Django website and immediately thought that the Python included HTMLCalendar would do what I needed. I have been reading the docs and can't seem to find a formatweek method for viewing a single week. There is formatmonth, formatyear and formatyearpage but no week. :( This is the documentation I have been looking at. Is there a better place? https://docs.python.org/3/library/calendar.html Thanks in advance for any direction. -
How can i get a single object?
Model: class Contacts(models.Model): libId = models.ForeignKey(verbose_name='Библиотека', to=Libraries, on_delete=models.CASCADE) name = models.CharField('ФИО', max_length=257, blank=True) position = models.CharField('Должность/название отдела', max_length=257) phoneNum = models.BigIntegerField('Номер телефона', validators=[MaxValueValidator(79999999999)]) def __str__(self): return self.name Serializer: class ContactsSerializers(serializers.ModelSerializer): class Meta: model = Contacts fields = '__all__' I can get all objects from that model: class ContactsView(generics.ListAPIView): serializer_class = ContactsSerializers queryset = Contacts.objects.all() But how can i get one from user input?