Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3, request.POST didnt save when i filter the user with request.user
im trying to filter the user that only display the current user login. after im found the solution how to filter the user but didnt save to db forms.py class EnrollmentForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(EnrollmentForm, self).__init__(*args, **kwargs) self.fields['user'].queryset = User.objects.filter(username=user) class Meta: model = Enrolled fields = ['schedule', 'user'] views.py def StudentEnroll(request): if request.method == 'POST': form = EnrollmentForm(request.POST) if form.is_valid(): form.save() return redirect('student-schedule') else: form = EnrollmentForm(request.user) return render(request, 'main/student_enroll.html', {'form': form}) -
Validating Entered Data with custom constraints in Django Forms in __init__
In my project, the user is entering data in a settings page of the application and it should update the database with the user's settings preference. I read this answer by Alasdair and how using the __init__() will allow to access the user's details. I was wondering if it's possible to return data from __init__() so I can validate the entered data before calling the save() function in the view? This is what I tried (and did not work). I am open to going about this in a better approach so I appreciate all your suggestions! Forms.py class t_max_form(forms.ModelForm): side = None def __init__(self, *args, **kwargs): side = kwargs.pop('side', None) super(t_max_form, self).__init__(*args,**kwargs) if side == "ms": self.fields['hs_max_sessions'].widget.attrs.update({'class':'form-control', 'readonly':True}) self.fields['ms_max_sessions'].widget.attrs.update({'class':'form-control mb-3'}) elif side == "hs": self.fields['hs_max_sessions'].widget.attrs.update({'class':'form-control'}) self.fields['ms_max_sessions'].widget.attrs.update({'class':'form-control', 'readonly':True}) else: self.fields['hs_max_sessions'].widget.attrs.update({'class':'form-control'}) self.fields['ms_max_sessions'].widget.attrs.update({'class':'form-control'}) #Trying to validate the data here valid_session_count = settings.objects.first() if(side == "ms"): input_sessions = self.fields['ms_max_sessions'].widget.attrs['readonly'] if(input_sessions > valid_session_count.max_sessions): self.add_error("ms_max_sessions", "You have entered more than the limit set by the TC. Try again") elif(side == "hs"): input_sessions = self.cleaned_data['hs_max_sessions'] if(input_sessions > valid_session_count.max_sessions): self.add_error("hs_max_sessions", "You have entered more than the limit set by the TC. Try again") else: input_sessions = self.cleaned_data['ms_max_sessions'] + self.cleaned_data['hs_max_sessions'] if(input_sessions > valid_session_count.max_sessions): self.add_error("hs_max_sessions", "You have entered more than … -
Given an encrypted string in the database, can somebody help me crack this password?
I have uploaded an application on heroku following a course in udemy. The lesson asked me to download an example database uploaded by them and link it with my own application. The application has a sign in page which authenticates itself with auth_user in the database. However, the password is encrypted. as such, i am stuck at the sign in page. I cannot create a new account for the application or write columns into the database, and the author of the udemy course has been uncontactable thus far. Querying the database yielded the account information. However, the password has been encryted, and i have no way of decrypting it. Can anyone help me with this? the password is: pbkdf2_sha256$30000$GBQUIvjRTK1b$JACrwzhRoiSXovL1Sf2A7LiWjZgmUlvTz3thWBRxMfs= this is the account information -
django ORM: get all the fields of model with positive value in one field
I am trying to query all the objects in a model that have a positive value in one particular field. I have not been able to find anywhere whether there is a way to use greater than signs in django. I have tried doing by sorting the column that interests me and removing the 0 values in that column in order to the overcome the greater than. First it seems over complicated, and second it does not work. here is the query: count_orders = replenishment.objects.order_by(F('StockOnOrder')).desc().exclude('StockOnOrder' = 0) I also need to count the positive rows in this field and it does not work either as following: count_orders = replenishment.objects.order_by(F('StockOnOrder')).desc().exclude('StockOnOrder' = 0).count() I am wondering if by chance this is the proper way to do it, or if there is something more intuitive and simple. -
Getting data from related tables using Django ORM
Using the Django ORM, how does one access data from related tables without effectively making a separate call for each record (or redundantly denormalizing data to make it more easily accessible)? Say I have 3 Models: class Tournament(models.Model): name = models.CharField(max_length=250) active = models.BooleanField(null=True,default=1) class Team(models.Model): name = models.CharField(max_length=250) coach_name = models.CharField(max_length=250) active = models.BooleanField(null=True,default=1) class Player(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING ) number = models.PositiveIntegerField() age = models.PositiveIntegerField() active = models.BooleanField(null=True,default=1) Note that this Player model is important in the application as it's a major connection to most of the models - from registration to teams to stats to results to prizes. But this Player model doesn't actually contain the person's name as the model contains a user field which is the foreign key to a custom AUTH_USER_MODEL ('user') model which contains first/last name information. This allows the player to log in to the application and perform certain actions. In addition to these base models, say that since a player can play on different teams in different tournaments, I also have a connecting ManyToMany model: class PlayerToTeam(models.Model): player = models.ForeignKey( Player, on_delete=models.DO_NOTHING ) team = models.ForeignKey( Team, on_delete=models.DO_NOTHING ) tournament = models.ForeignKey( Tournament, on_delete=models.DO_NOTHING ) As an example of … -
Using Validators in Django not working properly
I have recently learning about Validators and how they work but I am trying to add a function to my blog project to raise an error when a bad word is used. I have a list of bad words in a txt and added the code to be in the models.py the problem is that nothing is blocked for some reason I am not sure of. Here is the models.py def validate_comment_text(text): with open("badwords.txt") as f: CENSORED_WORDS = f.readlines() words = set(re.sub("[^\w]", " ", text).split()) if any(censored_word in words for censored_word in CENSORED_WORDS): raise ValidationError(f"{censored_word} is censored!") class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=300, validators=[validate_comment_text]) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) -
Updating and Deleting Comments for Posts in Django
I have added a Comment system to posts in a Blog Project and I am trying to add an option to update and delete the comments by the users. I am trying to use the same concept as creating a Post and building a Class Based Views for these comments, creating a commment is working fine and it is appearing correctly, the only obstacle I am facing is the slug, when a user clicks on update or delete it is showing an error Cannot resolve keyword 'slug' into the field. Choices are content, created, id, post, post_id, updated, user, user_id which makes sense since there is no Slug in the comment Model. My question is how do refer back to the same page post.slug in the template without getting this error Here is the models.py class Post(models.Model): slug = models.SlugField(blank=True, null=True, max_length=120) ------------------------------------------------------------ class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=300, validators=[validate_comment_text]) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) Here is the views.py class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment form_class = CommentForm def form_valid(self, form): post = get_object_or_404(Post, slug=self.kwargs['slug']) form.instance.user = self.request.user form.instance.post = post return super().form_valid(form) def form_invalid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('blog:post-detail', … -
Django pagination python dictionary
I hope you well. I’m developing a web using python and Django. I will love to paginate my dictionary “image_set_list” in order to see one element in one page, I mean, one element per page. The problem is that when I get the page, the result is None and pagination is not working. This is my view.py from django.shortcuts import render from django.http import HttpResponse import json from pathlib import Path import os from django.core.paginator import Paginator def detection_detail(request): # data planogram, bounding_boxes with open('detection/data.json', 'r') as json_file: data = json.load(json_file) # data image planogram image_name_location = data['image'] image_planogram = os.path.basename(image_name_location) # data product images with open('detection/data_product_images.json', 'r') as json_file: data_product_images = json.load(json_file) data_product_image = {x["id"]: x for x in data_product_images} images_reference = [] list_images = [] for product in data['bounding_boxes']: product_id = product['class'] product_ids = product['class_list'] image_p = data_product_image[product_id]["image_file"] image_p_list = [data_product_image[id]["image_file"] for id in product_ids] images_reference.append(image_p) list_images.append(image_p_list) image_set_list = {images_reference: list_images for images_reference, list_images in zip(images_reference, list_images)} #PAGINATION!! paginator = Paginator(image_set_list , 1) page = request.GET.get('page') print('page', page) #result is -> None set = paginator.get_page(page) context = { 'list_images': list_images, 'images_reference': images_reference, 'image_planogram': image_planogram, 'image_set_list': image_set_list, 'image_p_list': image_p_list, 'set': set} return render(request, "detection/detection_detail.html", context) And this is my … -
django how to use range inside of kwargs
I am trying to filter my queryset between two dates and I can't seem to figure out why this isn't working. Here is my code kwargs = { '{0}__{1}'.format(arg1, 'exact'): arg2, '{0}__{1}'.format('deleted', 'isnull'): True, '{0}__{1}'.format('event_date', 'range'): {date1, date2} } table = GeTable(Ge.objects.filter(**kwargs)) I want to be able to filter my queryset to only records between date1 and date2. Can someone point me in the right direction? -
Defining GOOGLE_APPLICATION_CREDENTIALS on elasticbeanstalk env breaks S3 connection
I have a django app deployed using elasticbeanstalk. I installed firebase admin sdk which requires GOOGLE_APPLICATION_CREDENTIALS field to be filled with path to credential. The problem is that right after I define GOOGLE_APPLICATION_CREDENTIALS on elasticbeanstalk console, Django's connection to S3 all breaks. What is happening and how to fix this? -
Page not found (404) Request Method:
please help me. I don't know why can't see the detail of product when i click a product. both first list work good just when i need to see detail of product in second list(filtered list) an 404 error shows. thanks here is my code below: my urls: from django.urls import path from . import views app_name = 'shop' urlpatterns = [ path('', views.HomeView.as_view(), name='home'), path('categories/<category>/', views.ProductListView.as_view(), name='product-list'), path('categories/<int:pk>/', views.ProductDetailView.as_view(), name='product-detail'), ] views: from django.shortcuts import render, get_object_or_404, get_list_or_404 from django.views import generic from .models import Category, Product class HomeView(generic.ListView): model = Category template_name = 'home.html' class ProductListView(generic.ListView): template_name = 'product_list.html' def get_queryset(self): self.category = get_object_or_404(Category, title=self.kwargs['category']) return Product.objects.filter(category=self.category) class ProductDetailView(generic.DetailView): model = Product template_name = 'product_detail.html' product_list.html {% extends 'base.html' %} {% load static %} {% block title %} Welcome | Global Market {% endblock %} {% block content %} {% for product in product_list %} <a href="{% url 'shop:product-detail' product.pk %}"> <div class="card bg-light mb-3" style="max-width: 18rem;"> <div class="card-header">{{ product.title }}</div> <img class="card-img-top" src="{{ product.image.url }}" alt="{{ product.title }}"> <div class="card-body"> <p class="card-text">{{ product.description }}</p> </div> </div> </a> {% endfor %} {% endblock %} product_detail.html {% extends 'base.html' %} {% load static %} {% block title %} Welcome … -
Django - use middleware to block debug data on some cases
I'm using Django in debug mode in dev environment. When some views fail, it returns the debug page (not debug_toolbar, just the page with list of installed apps, environment variables, stack trace, ...) In my middleware, I have some cases (specific URLs, specific users, ...) where I want to remove this data and just return the raw response. How should I do that? currently my best idea is to just: response.data = {} return response But I'm not sure if it's the proper way to do that, whether it covers all cases and so on. I just want to use a middleware to control in some cases and avoid the DEBUG mode for them. -
Right Approach to Schedule a job in Django/Python
If you have built an application using Django 3 and MySQL 8. How would you schedule a job with "Right Approach" and why? I am guessing by using the inbuilt sched module. What are the merits and demerits of using sched, cron and APScheduler? -
Django Accessing Parent Data in templates from child data
So I've been search and trying to solve this question for hours and hours and I cant' seem to find an answer. I have 2 different models flights and Destinations. The Destination is the Parent model, A flight can only have one destination but the Destination can have many flights (one to many relationship). I would like to access this parent model on the details page of of the flight model. This details page is generated via the url routing and the slug of the flight. Here is what I have for the for the models, views and templates. models: class Flight(models.Model): title = models.CharField( null=True, max_length=60, blank=True) slug = models.SlugField(max_length=100, null=True, blank=True) flight_destination = models.ForeignKey(Destination, null=True, blank=True, on_delete=models.SET_NULL) class Destination(models.Model): title = models.CharField( null=True, max_length=60, blank=True) featuredimage = models.ImageField(null=True, blank=True, upload_to ='media/') slug = models.SlugField(max_length=100, null=True, blank=True) Each of these classes has an id for its primary key and I've connected all my flights to the correct destination. Here is what I have for my view. def flight_detail(request, slug): return render(request,"flight/detail.html",context= {'flight': Flight.objects.get(slug=slug), 'destination': Destination.objects.filter(id= Flight.objects.get(slug=slug).flight_destination_id)}) Here is the template but it which doesn't throw an error but it displays nothing <h3 class="pb-3"> {{ destination.title }} </h3> I feel … -
How do I properly use javascript axios .get() function to call get_queryset() function in Django viewset?
I followed a youtube guide to implement a React/Redux frontend that uses javascript axios to make requests to a Django REST framework backend. I've been adding a lot of my own work to it. Here is the original github repository if you think you need it to answer my question, although you shouldn't: Link To Github I have a new method I use to get what I call eventdefinitions. Sometimes I want all of the eventdefinitions that are in the database, but sometimes I only want some of them. In the original guide, the only way I was taught to get data, was to get all of the data, and so to get all eventdefinitions, I would do the following: In javascript, I use the following method which implements axios: // GET EVENT DEFINITIONS export const getEventDefinitions = () => (dispatch, getState) => { axios .get("/api/eventdefinitions/", tokenConfig(getState)) .then((res) => { dispatch({ type: GET_EVENTDEFINITIONS, payload: res.data, }); }) .catch((err) => dispatch(returnErrors(err.response.data, err.response.status)) ); }; In my urls.py file I set up the url_patterns for the /api/eventdefinitions/ url: from rest_framework import routers from .api import ... EventDefinitionViewSet, ... router = routers.DefaultRouter() ... router.register('api/eventdefinitions', EventDefinitionViewSet, 'eventdefinitions') ... urlpatterns = router.urls The EventDefinitionViewSet in … -
Django add dataframe as Excel file inside model
Django I have multiple dataframes And I want to add download links in html to down load those dataframes as Excel files -
Cannot pass variables between javascript function and ajax in django project
This is a proper noob question it would seem, so apologies, but I can't seem to solve it so I'm reaching out for some assistance. I have a function in my .js file that interacts with the Google Places library to autocomplete a field in a form. I then have an ajax function that runs when you click the submit button which creates variables in the django session. The data of interest to me is lat and long. However, for some reason, I can't seem to get the data to pass from one to the other. I know the ajax function is working because if I type in fixed values they propagate through to django, but I can't seem to get it to update dynamically. const csrf = document.getElementsByName('csrfmiddlewaretoken'); var lat; var lng; function autocomplete_location() { let defaultBounds = new google.maps.LatLngBounds( new google.maps.LatLng(49.6331, -11.7247), new google.maps.LatLng(59.4850, 1.5906)); let input = document.getElementById('id_your_location'); let options = { bounds: defaultBounds, types: ["address"], fields: ["name", "geometry"], }; let autocomplete = new google.maps.places.Autocomplete(input, options); autocomplete.addListener('place_changed', function() { // Get place info let place = autocomplete.getPlace(); // Do whatever with the value! lat = place.geometry.location.lat() lng = place.geometry.location.lng() console.log(lat) console.log(lng) }) } $(document).ready(function (){ $(".btn").click(function (){ … -
Django q update an already scheduled task
I am using Django-q to schedule a task at a specified date in an object (lets call this bell). I am successfully able to do so using schedule_obj = schedule(func_name, arg1, arg2, arg3, schedule_type=Schedule.ONCE, next_run=bell.date) when there is an update to the obj bell that holds the date, I want to modify this schedule obj with the updated date (bell.date). Is there a way to check if there is a schedule pending for this specific func_name with the args and then access it to modify it? -
How can I get userprofile randomly and add condition?
Here i am trying to get 3 random users and adding them in request user followers, But with the following code , That is getting three users useprofiles randomly including those who already following that profile, i just want to replace those users profiles with those users who don't following request.user so i can add them. #return the count of users who is not following request user all_profiles = UserProfile.objects.all() user_followers = request.user.is_following.all() pk_range = 0 for profile in all_profiles: if not profile in user_followers: pk_range +=1 print(pk_range,) if pk_range >= 3: k1, k2 ,k3 = sample(range(pk_range), 3) f1 = UserProfile.objects.all()[k1] f2 = UserProfile.objects.all()[k2] f3 = UserProfile.objects.all()[k3] userprofile = request.user.userprofile user= request.user user.is_following.add(f1, f2, f3) user.save() if more information or code is require than tell me in a comment session. I will update my question with that information. -
Why is my loop terminating before all items are looped through?
So I'm using Django and trying to dynamically add a users gists to the page using githubs embedded gists. this is the loop {% for i in snippets %} <div class="tile is-4"> <div style="height:25vh;"><script src="https://gist.github.com/{{i.owner.login}}/{{i.id}}.js"/></div> </div> {% endfor %} the list im looping through contains two items, however only the first is added. if I do something along these lines however it correctly displays the two different id's {% for i in snippets %} {{i.id}} {% endfor %} I read that the github script calls document.write(), I have a gut feeling this is where my issue lies. would document.write() break my loop? -
how can i fetch data without refresh page with javascript & django?
i am using django to make API and get data with javasctipt. first time i'm using javascript i don't have very good understanding with javasctipt. i want to get data without refreshing page i am using javacript to fetch data form API. my code is getting data from databse only when i refresh the page. is there way to get data without refreshing page? when anybody create new post then page automatically load the post in index page without refresh the page? index.html <script> async function getPosts() { const Url = 'http://localhost:8000/api/' const Story = document.getElementById('stories') await fetch(Url) .then((res) => res.json()) .then((data) => { data.map((post, index) => { document.getElementById('stories').innerHTML += ` <div class="card card-body mb-3"> <h3>${post.title}</h3> </div> `; }); }) .catch((err) => console.log(err)) } getPosts(); </script> -
AssertionError Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
I want to create a comment api but I get this error: AssertionError at /comment/add/ Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> this is my view: @api_view() def AddComent(request, parent_id=None): parent = request.data.get("parent_id") serializer = CommentSerializer(data=request.data) if serializer.is_valid(): if parent is not None: comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'], parent_id=serializer.validated_data['parent'], body=serializer.validated_data['body']) else: comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'], body=serializer.validated_data['body']) return comment and this is url: path('comment/add/', views.AddComent, name='add_comment'), -
Passing varibles from API to template in Django
I am working on building a flight price search website as part of a project and have managed to get most of the functionality I require working. Here's what the front-end looks like so far: When users enter in the details, a POST request is sent to an API. API: https://developers.amadeus.com/self-service/category/air/api-doc/flight-offers-search API Python SDK: https://github.com/amadeus4dev/amadeus-python I'm receiving a response from the API; however, am struggling to understand what I should then do with the information received. The next step is to pass the information from the API into a search results template and split out all of the received flight information, similar to how it is displayed on Sky Scanner: Below is what I have in my views.py so far (currently passing in the whole response, in what I believe is JSON format?) Views.py: def flight_search(request): kwargs = {'originLocationCode': request.POST.get('Origincity'), 'destinationLocationCode': request.POST.get('Destinationcity'), 'departureDate': request.POST.get('Departuredate'), 'returnDate': request.POST.get('Returndate'), 'adults': '1'} try: response = amadeus.shopping.flight_offers_search.get( **kwargs) print(response.data) return render(request, "flightfinder/flight_search.html", { "response": response }) except ResponseError as error: raise error Here is an example response from the API: { "meta": { "count": 2 }, "data": [ { "type": "flight-offer", "id": "1", "source": "GDS", "instantTicketingRequired": false, "nonHomogeneous": false, "oneWay": false, "lastTicketingDate": "2020-11-20", "numberOfBookableSeats": 2, … -
Got AttributeError when attempting to get a value for field `phone` on serializer `UserSerializer`
im trying to create a view to update the extended profile data in one request, using the auth_rest library, but i got this error: Got AttributeError when attempting to get a value for field phone on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'userprofile'. This is my models (UserProfile) class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE) phone = models.CharField(max_length=15, blank=True) phone_whatsapp = models.BooleanField(default=False) def __str__(self): return self.user.username This is the serializer: class UserSerializer(UserDetailsSerializer): phone = serializers.CharField(source="userprofile.phone") phone_whatsapp = serializers.BooleanField(source="userprofile.phone_whatsapp") class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('phone','phone_whatsapp',) def update(self, instance, validated_data): profile_data = validated_data.pop('userprofile', {}) phone = profile_data.get('phone') phone_whatsapp = profile_data.get('phone_whatsapp') instance = super(UserSerializer, self).update(instance, validated_data) # get and update user profile profile = instance.userprofile if profile_data and phone and phone_whatsapp: profile.phone = phone profile.phone_whatsapp = phone_whatsapp profile.save() return instance i modified some things, but i dont be able to fix it. anyone can helpme? thanks in advance -
How can I update the email address using the confirmation code in Django?
I use all the functionalities of dj-rest-auth to register, log in, confirm the email address, change the password, reset the password and many more. Unfortunately, the library does not support changing the email address. I would like the authenticated user to first enter the account password and the new email address. After the successful process of authentication, I would like to send the user a specially generated confirmation code. Only when he enters it, the old email address will be changed to the new one. As far as I know, there is no such functionality in dj-rest-auth. Unfortunately, I also have not found any current solutions or libraries for this purpose anywhere. Has anyone had a similar problem and could share solution here? Thank you in advance.