Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework: Register pure function-based views with router so it appears under API root
This is my views.py: class ChoicesViewSet(viewsets.ModelViewSet): queryset = SingleChoice.objects.all() serializer_class = SingleChoiceSerializer ... class AssessmentTakersViewSet(viewsets.ModelViewSet): queryset = AssessmentTaker.objects.all() serializer_class = AssessmentTakersSerializer ... @api_view(['POST']) @parser_classes((JSONParser,)) def studio_create_view(request, format=None): """" A view that accept POST request with JSON content and in turn build out the questions and choices. Post with application/json type. """ ... This is my urls.py: urlpatterns = [ # http://localhost:8000/survey/api/studio-create path('api/studio-create', views.studio_create_view, name='studio-create-api'), ] # drf config router = routers.DefaultRouter() router.register('api/choices', views.ChoicesViewSet) router.register('api/assessment-takers', views.AssessmentTakersViewSet) urlpatterns += router.urls This works functionally, and is considered feature-complete, but but because studio-create_view is not registered with the router, the path doesn't show up under the API Root which isn't great documentation wise. In other words, the API root from Django Rest Framework isn't aware of the path, and a GET request to the root would list only: http://localhost:8000/survey/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "api/choices": "http://localhost:8000/survey/api/choices/", "api/assessment-takers": "http://localhost:8000/survey/api/assessment-takers/", ... } My question is, outside of viewsets that inherit from ModelViewSet, how do we get the custom views like studio_create_view to be registered with the router that Django Rest Framework provide so it's listed under the API root? One would be inclined to try something like: router.register('api/studio-create', views.studio_create_view, … -
i want to do something on value of a ModelForm before saving in database-django
hiiii,, im trying to do something on value of a ModelForm in django before saving that on database. that "something" is changing the value of datetime field... i want to take jalali datetime from user in form and in template and do something on that(its about changing jalali datetime to gregourian datetime) and save gregourian datetime on database... where should i doing that? in the view or forms? and how?? this is my forms.py (i want do something on datetime field): class NewEvent(ModelForm): class Meta: model = Event fields = ['user','datetime','work'] and this is my view: class CreateEventView(CreateView): form_class = NewEvent template_name = 'app1/new_event.html' i know how to convert jalali to gregourian but i dontknow where should doing that -
Is there any way to clear the session on a browser or tab close in Django as SESSION_EXPIRE_AT_BROWSER_CLOSE = True is not working at all?
When I close a tab or browser and then I run the application again opening the browser again, the previous session remains active. I tried SESSION_EXPIRE_AT_BROWSER_CLOSE = True in settings.py file in the project directory as per the Django documentation. Nothing works. Even the existing solutions in stackoverflow does not work. Is there any way to clear the session on a browser or tab close in Django? -
Bidirectional one-to-may django
I would like to create a bidirectional one-to-many and many-to-one relationship in django like: class User(models.Model): device = dont_know_what_to_write() class Device(models.Model): user = models.ForeignKey( User, on_delete = models.CASCADE ) What should I do? -
Django makemigrations does not create admin databases
I have a django project, this is the installed apps entry in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crawler', ] when I run python manage.py migrate everything seems to be fine. But when I try to login into django admin page, It says (1146, "Table 'stock_db.django_session' doesn't exist") It seems to me that migrate is not creating django admin databases, but why? -
in Visual Studio Code, how can i trigger intellisense in an html django template file to get parameters from a .py file under same app?
I'm learning Django and I would like to know if there's a way to trigger intellisense within an html django template file to get a parameter declared in a python class from another under the same app, I'm trying to get the question__text declared in a class in the models.py file. this is by the way the tutorial from the django docs here -
jango filter by latest date in python
I have the following model class CoinsQuotes(models.Model): coinQuotesID = models.AutoField(primary_key=True) coinID = models.ForeignKey(Coins, on_delete=models.CASCADE) coinCurrency= models.CharField(max_length=10) coinPrice = models.DecimalField(decimal_places=8, max_digits=40) coinVolume24h = models.DecimalField(decimal_places=2, max_digits=30) coinPercentageChange1h = models.DecimalField(decimal_places=2, max_digits=20) coinPercentageChange24h = models.DecimalField(decimal_places=2, max_digits=20) coinPercentageChange7D = models.DecimalField(decimal_places=2, max_digits=20) coinPercentageChange30D = models.DecimalField(decimal_places=2, max_digits=20) coinPercentageChange60D = models.DecimalField(decimal_places=2, max_digits=20) coinPercentageChange90D = models.DecimalField(decimal_places=2, max_digits=20) coinPercentageChange180D = models.DecimalField(decimal_places=2, max_digits=20) coinMarketCap = models.DecimalField(decimal_places=2, max_digits=20) coinQuoteLastUpdated = models.DateTimeField('quoteLastUpdated') coinQuotesSnapDate = models.DateTimeField(auto_now_add =True) class CoinsPortfolio(models.Model): coinPortfolioID = models.AutoField(primary_key=True) coinID = models.ForeignKey(Coins, on_delete=models.CASCADE) coinName= models.CharField(max_length=10) coinUSDNotional= models.DecimalField(decimal_places=2, max_digits=30) coinAmount = models.DecimalField(decimal_places=10, max_digits=30) coinBookPrice = models.DecimalField(decimal_places=10, max_digits=40) coinMarketPrice = models.DecimalField(decimal_places=10, max_digits=40) coinBookFees = models.DecimalField(decimal_places=2, max_digits=20) coinBookDate = models.DateTimeField('coinBookDate') coinQuoteLastUpdated = models.DateTimeField('quoteLastUpdated') coinQuotesSnapDate = models.DateTimeField(auto_now_add =True) and I am using the current view to extract the latest quotes for all coins. latest_date = CoinsQuotes.objects.aggregate(latest1 = Max('coinQuotesSnapDate')).['latest1'] pct_chg = CoinsQuotes.objects.all().filter(coinQuotesSnapDate = latest_date) for a reason its returning only one item, while in fact there are 10 coins with the latest time ? additionally is there a way to filter to filter wihin a template of or alternatively should i link those 2 models with many to many relationship ? Many thanks -
How to serve and download zip file stored in media folder in Django?
I am using Django to develop a small API and I want to download files stored in media folder based in id of file stored in a model. this is my API view function def download_trans(request, tran_id, ext): translation = Translation.objects.filter(translator__tran_id=tran_id).first() file_path = os.path.join(translation.file_path.path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) return response raise Http404 The download is starting but it gives me file with size of 0 and damaged file because no contents on it. what could be my problem. -
Concurrency Tests in Django
Just started Django last month. I needed help running concurrency tests in django, so what I've done is tried to write code which will prevent issues that arise due to lack of concurrency but what I don't know is how to verify and test the code to see that it meets my expectations. What I want is to send multiple requests at the same time to see if the code works as expected. The target function in views.py def buy_animal(request): context = {} if request.method == 'POST': form = buys_animal(request.POST) if form.is_valid() == True or form.is_valid() == False: #return HttpResponse('asdasd') nm = request.POST['an_name'] b = Animal.objects.filter(an_name = nm) #return HttpResponse("yo ") #nm = request.POST['an_name'] qt = int(request.POST['qty']) if b.count() <= 0: return HttpResponse(str(b.count()) + " Sorry we're out of animals") else: try: with transaction.atomic(): b.select_for_update() b = b[0] #b.an_name = 'asd' #b.save() with transaction.atomic(): Quality.objects.filter( animal = Animal.objects.filter(an_name = 'ringneck')[0] ).select_for_update() c = Quality.objects.filter( animal = Animal.objects.filter(an_name = 'ringneck')[0] )[0] c.rating = 'niece' c.save() except: return HttpResponse('lock in use') if b.qty - qt < 0: return HttpResponse("Sorry we don't have enough animals") else: b.qty = b.qty - qt b.save() a = Buy_animal( an_name = nm, qty = qt, buyer = … -
Using Arabic letters in Django urls causes a 404 error
I want to use Arabic letters in my addresses, there is no problem in local mode, but it causes an error on the server. models.py class Product(models.Model): title = models.CharField(max_length=40, verbose_name='عنوان محصول') slug = models.SlugField(max_length=100,unique=True,allow_unicode=True, verbose_name='آدرس') urls.py urlpatterns = [ path('detail/<str:slug>', ProductDetail.as_view(), name='product_detail') ] views.py class ProductDetail(DetailView): model = Product template_name = 'product_app/product_detail.html' -
how make django sleep
I have a project in which one client register a request and some other clients must answer if they want to work with him or not in real time the problem is that how can i sleep the consumer of him to wait until one of them accepted if i use time.sleep() the whole project will sleep class ConsulationConsumer(WebsocketConsumer): def connet(self): pass def diconnect(self,code_close): pass def receive(self, text_data): text_data_json = json.loads(text_data) consultation = text_data_json['message'] consulator=ConsultationOrder.objects.get(id=consultation).lawyer if(consulator==None): consulator=0 self.send(text_data=json.dumps({ 'message': consulator })) -
menu model design like uber eats menu maker with rules and pricing
I am trying to mimic uber eats menu maker. It has a concepts like modifier, modifier groups, ingredients, preparation time, rules for modifier groups and able to set conditional pricing. I am not quite confident but at least I have implemented modifier, and modifier groups but I stumbled on rules and conditional pricing. By rules I mean to say, modifier groups should be able to allow customers to customize their dishes by allowing them to set constraints for modifier groups to manage exactly what customers can select. This is what rules and conditional pricing looks like This is how I have done so far class MenuItemTag(TimestampBase, ShortUUIDBase): name = models.CharField(max_length=255, null=False) class Meta: verbose_name = "Label" verbose_name_plural = "Labels" default_related_name = "tags" def __str__(self): return self.name or "-" class MenuCategory(TimestampBase, ShortUUIDBase): name = models.CharField(max_length=255, null=False) restaurant = models.ForeignKey("restaurants.Restaurant", on_delete=models.CASCADE) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" default_related_name = "category" def __str__(self): return self.name or "-" class MenuItem(TimestampBase, ShortUUIDBase): CLASSIFICATION_CHOICES = ( ('nonveg', 'Non Veg'), ('vegan', 'Vegan'), ('vegetarian', 'Vegetarian'), ) name = models.CharField(max_length=255, null=False) details = models.TextField(null=True, blank=True) # Precision: 9-digits<decimal_place>6-digits list_price = models.DecimalField( max_digits=15, decimal_places=6, null=True, blank=True, validators=[MinValueValidator(Decimal("0.01"))], ) net_price = models.DecimalField( max_digits=15, decimal_places=6, validators=[MinValueValidator(Decimal("0.01"))] ) restaurant = models.ForeignKey( … -
ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied
Please Help me to install Django on virtual enviroment My terminal throw this error ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/home/user/lib/python3.8/site-packages/sqlparse' Consider using the --user option or check the permissions. -
serializer.is_valid returns false with an error that the field is required even though I am passing it
I am building a serializer so that if I post using the following command curl -d '{"food": "test", "portion": 12}' http://127.0.0.1:8000/food it will save to the db. However my problem is serializer.is_valid() returns false with an error that the field "food" is required even though I am passing it. I am unable to change the curl command so how can I make it work? Any help is appreciated. views.py serializer = StockSerializer(data=request.data) if serializer.is_valid(): //save else: print(serializer.errors) //{'food': [ErrorDetail(string='This field is required.', code='required')]} serializer.py class FoodSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["food", "portion"] Log FoodSerializer(data=<QueryDict: {'{"food": "test", "portion": 12}': ['']}>): food = CharField(max_length=8) portion = IntegerField(required=False) -
How to Update field of Django model based on another model with foreign key relation
I have two models Betslip and Bet,I want to update value of Betslip.settled_status to 'Lost', if Bet.settlement_status is 'half_lost' or 'lost', can anyone create a method for it ? class Betslip(models.Model): SETTLED_STATUS_CHOICE = ( ('InGame','InGame'), ('Won','Won'), ('Lost','Lost'), ('Refunded','Refunded') ) settled_status = models.CharField(choices=SETTLED_STATUS_CHOICE,max_length=30) class Bet(models.Model): SETTLEMENT_STATUS_CHOICE = ( ('','select'), ('won','won'), ('lost','lost'), ('refund','Refund'), ('half_won','half_won'), ('half_lost','half_lost'), ) settlement_status = models.CharField(choices=SETTLEMENT_STATUS_CHOICE,max_length=30,) betslip = models.ForeignKey(Betslip,on_delete=models.CASCADE,related_name='bet')``` -
Obtaining unique set of related models
I'm attempting to get a unique set of Employees that are represented within a queryset of jobs. My models are as follows: class Employee(models.Model): name = models.CharField(max_length=100) class Job(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True) start_time = models.DateTimeField(null=True, blank=False) end_time = models.DateTimeField(null=True, blank=False) My query is as follows jobs_list = Job.objects.filter( Q(start_time__lte=start) & Q(end_time__gte=end) ) I'd like to develop a query that gets me a unique queryset of Employees that are related to the jobs_list queryset. Thanks! -
Add view count if video is played more than 3 seconds
I am building a Simple Video App. What i am trying to do :- I am trying to add a user's view count if video is played more than three seconds. What i have done :- I got the video duration in miliseconds using pymediainfo. I made a view counter which is working fine(In video detail view) but. i don't know how can i get played duration of video. models.py class Video(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True) video = models.FileField(upload_to='videos',null=True) viewers = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='viewed_video',blank=True,editable=True) views.py from pymediainfo import MediaInfo def videoListView(request,pk): videos = Video.objects.all() for vid in videos: media_info = MediaInfo.parse(f.video) duration_in_ms = media_info.tracks[0].duration queryset = Video.objects.annotate( num_views=Count('viewers')).order_by('-num_views') datas = get_object_or_404(queryset, pk=pk) if request.user.is_authenticated: created = Video.viewers.through.objects.get_or_create(video=datas, user=request.user) if created: datas.num_views += 0 context = {'vid':vid,'datas':datas,'duration_in_ms':duration_in_ms} return render(request, 'videoList.html', context) I have no idea how can i get video's played duration. Once i get the video's played duration then i will use if statement that if video_played_duration == 3seconds: then add view count. Any help would be much Appreciated. Thank You in Advance. -
¿Como serializar query set con group by en django?
Soy nuevo en DJANGO, estoy tratando de serializar el siguiente query set: Product.objects.all().values('category').annotate(total= Count('category')) el resultado que estoy buscando seria el siguiente [ { category: "category1", total: 5 }, { category: "category2", total: 3 }, { category: "category3", total: 8 } ] -
Question in one of Cory Schafer's tutorials for Django
I am trying to learn Django by watching the Django course by Cory Schafer, and I'm just confused about the part where Cory used redirect after the registration process. if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('blog-home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) He used the return redirect('blog-home') and managed to show the message Account created for {username} in the template. But I'm not sure how he managed to access that message in the template without ever passing it similar with what we do with render method. Example of render method I learned is below, it's always passing the 3rd argument so that in the template we can manage to access it. But I have no idea how the message was passed via redirect method. return render(request, 'blog/home.html', context) -
Getting this error while running this python code for Google analytics API implimentation
I want to get all the feed lists From Google analytics API and while running my code I'm getting this error. Code: from oauth2client import client results = client.list_web_data_streams(parent=f"properties/65652355") results Error: AttributeError Traceback (most recent call last) <ipython-input-11-13e430ab0d4b> in <module> 3 from oauth2client import client 4 ----> 5 results = client.list_web_data_streams(parent=f"properties/65652355") 6 results AttributeError: module 'oauth2client.client' has no attribute 'list_web_data_streams' -
error is comming while sending list and fetch value on sended list data
plz explain why this is happening in detail and solution also. thanks in advance. list is coming in views but when i fetch the value against them then it prints 'none' and also when i use to send js list to same function in which i want to fetch then also it dont works plz this also image of error page: https://i.stack.imgur.com/t43Vw.png <div class="container"> <div class="tabble"> <div class="col"> <div> <label class="ac_trigger" for="ac1"> <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search For Food Names.." title="Type in a name"> &nbsp;<i class="fa fa-search"></i> </label> </div> <br> <div class="ac_container" id="div1"> <table id="myTable"> <tr class="header" id="heading" style="display: none;"> <th style="width:80%;">Name</th> <th style="width:20%;padding: 4px;">Select</th> </tr> {% for a in foodlist2 %} <tr style="display: none;"> <td>{{a|title}}</td><td style="text-align:center"><input id="btn" type="button" value="Add" name="{{a}}" onclick="add_item(this, this.parentNode.nextSibling.nextSibling)"></td> <td style="display: none;text-align: center;"><input id="btn" type="button" name="{{a}}" value="Remove" onclick="remove_item(this,this.parentNode.previousElementSibling)"></td> </tr> {% endfor %} </table> </div> <div class="ac_container"> <table id="myTable1"> <tr class="header"> <th style="width:80%;">Selected Items</th> <th style="width:20%;">Intake(gm)</th> </tr> <!-- <tr id="newRow"> <td id="showName"></td><td><input type="Number" name="FETID CASSIA (fresh)"></td> </tr> --> </table> </div> </div></div> <a href="food_output"><button id="submit">Submit</button></a> </div> <script type="text/javascript"> function myFunction() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); document.getElementById('heading').style.display = ''; for (i = 0; … -
How to process the practice answers directly on the server and the results are immediately updated on the practice data using Django
I want to process the practice answers directly on the server and the results are immediately updated on the practice data, so when the user opens the practice data, the practice data value is already available. models.py class PracticeAnswer(models.Model): practice_answer_id = models.BigAutoField(primary_key=True) practice_answer = models.CharField(max_length=255, default=None, blank=True) practice = models.ForeignKey(Practice, models.DO_NOTHING, default=None) question = models.ForeignKey('Question', models.DO_NOTHING, default=None) def __str__(self): return str(self.practice_answer_id) class Practice(models.Model): practice_id = models.BigAutoField(primary_key=True) score = models.SmallIntegerField(null=True) correct = models.SmallIntegerField(null=True) def __str__(self): return str(self.practice_id) class Question(models.Model): question_id = models.BigAutoField(primary_key=True) question = models.TextField() question_answer = models.CharField(max_length=255) multiple_choice_a = models.CharField(max_length=255) multiple_choice_b = models.CharField(max_length=255) multiple_choice_c = models.CharField(max_length=255) def __str__(self): return self.question class User(models.Model): user_id = models.BigAutoField(primary_key=True) fullname = models.CharField(max_length=50) email = models.CharField(max_length=100) password = models.TextField() def __str__(self): return self.fullname views.py @api_view(['GET']) def practiceAnswer_filter(request): if request.method == 'GET': practiceAnswers = PracticeAnswer.objects.all() practice_id = request.GET.get('practice_id', None) if practice_id is not None: practiceAnswer_filtered = practiceAnswers.filter(practice_id__practice_id__icontains=practice_id) practiceAnswer_list = list(practiceAnswer_filtered) shuffle(practiceAnswer_list) practiceAnswer_shuffled = practiceAnswer_list[:5] def sort_list(e): return e.pk practiceAnswer_shuffled.sort(key=sort_list) practiceAnswers_serializer = PracticeAnswerSerializerFilter(practiceAnswer_shuffled, many=True) return JsonResponse(practiceAnswers_serializer.data, safe=False) @api_view(['GET']) def practice_filter(request): if request.method == 'GET': exercises = Practice.objects.all() user = request.GET.get('user', None) if user is not None: practice_filtered = exercises.filter(user__user_id__icontains=user) exercises_serializer = PracticeSerializer(practice_filtered, many=True) return JsonResponse(exercises_serializer.data, safe=False) I have practice answer data based on practice with id 127. … -
Django: NOT NULL constraint failed: account_tutorvalidator.user_id
I am new to django and I created this "apply now form" exclusively for tutors that when they submit the form it will appear to the admin site, and I will manually check it if they are a valid tutor. And if they are a valid tutor, I will check the is_validated booleanfield in the admin site to the corresponding tutor that sent the form, so that he/she will have access to other things in the site. But I am having this problem that when you submit the form a "NOT NULL constraint failed: account_tutorvalidator.user_id" comes up.. I have search for some solutions and also read similar questions here but I still couldn't understand what to do.. could someone help me out with this? here is my models.py class User(AbstractUser): is_student = models.BooleanField(default=False) is_tutor = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=11, blank=False, null=True) current_address = models.CharField(max_length=100, null=True) image = models.ImageField(default='default-pic.jpg', upload_to='profile_pics') def __str__(self): return f'{self.first_name} {self.last_name} class TutorProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='tutor_profile') bio = models.CharField(max_length=255, blank=True) is_validated = models.BooleanField(default=False) def __str__(self): return f"{self.user.first_name} {self.user.last_name}'s Profile" class TutorValidator(models.Model): user = models.ForeignKey(TutorProfile, on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) dbs = models.ImageField(upload_to='dbs_pics') driving_license = models.ImageField(upload_to='drivers_license_pics', null=True, … -
FBV Delete to CBV Delete
I am new to django ,how can i convert this FBV delete to CBV delete ? def delete_hotel(request, pk): hotel = Hotel.objects.get(pk=pk) owner = MyUser.objects.get(pk=pk) hotel.delete() owner.delete() return redirect('/admin/') -
any django app that can store sessions ip,browser ..etc and not delete it after the user logout?
i want to store the session history for users in my application , any app can be used ? if not how some thing like that can be made ? i want to have complete history for IPS , browsers , location ..etc i have tried to used Django-sessions app from jassband but it the session is deleted after the user logout thanks