Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Inserting pandas dataframe into django model
I am having an issue writing a dataframe to my django models.py. The file is long, but is quite simple in its methodology: -import modules -create django database -requests.get necessary data -alter data some to fit my goals, save as df -connect to django db and insert df My models.py is the following: from django.db import models import requests import pandas as pd from datetime import timezone from datetime import datetime from datetime import date from datetime import timedelta import time from django.conf import settings from sqlalchemy.engine import create_engine class cryptoData(models.Model): coin = models.CharField(max_length=10) asset_id = models.SmallIntegerField() time = models.DateTimeField() close = models.FloatField() volume = models.BigIntegerField() market_cap = models.FloatField() reddit_posts = models.IntegerField() reddit_comments = models.IntegerField() tweets = models.IntegerField() tweet_favorites = models.IntegerField() social_volume = models.IntegerField() lunarcrush_key = 'fakekey1234' def top_coins(): lc_market = requests.get( url = 'https://api.lunarcrush.com/v2?data=market&', params = { 'key': lunarcrush_key, } ) all_coins = [] for entry in lc_market.json().get('data'): coin = [] coin.append(entry.get('s')) coin.append(entry.get('mc')) all_coins.append(coin) all_coins.sort(key = lambda x : x[1], reverse = True) top_ten_coins = all_coins[:10] return(top_ten_coins) top_coins_lst = top_coins() top_coin_names_lst = [x[0] for x in top_coins_lst] def get_coin_data(key, coin, date_diff, start_date, end_date): lc = requests.get( url = 'https://api.lunarcrush.com/v2?data=assets&', params = { 'key': lunarcrush_key, 'symbol': coin, 'interval': 'day', 'data_points': … -
How to pass a Count field to export field
I'm working on an export resource but I can't figure out how to pass this field from the view as a column in my export. issues = Student.objects.annotate(Count('issue')) def view_student(request): issues = Student.objects.annotate(Count('issue')) students = Student.objects.filter(school = request.user.school).order_by('year') return render(request, 'view_student.html', {'students': students,'issues':issues}) This is how I tried it in the resoucrces.py but it shows no result class ExportStudentsResource(resources.ModelResource): books = fields.Field(attribute = 'books',column_name='books',widget= ForeignKeyWidget(Student, 'issue_count')) class Meta: model = Student fields = ('student_id','name','year','klass','stream','books') This field is not from any model so I just thought Student model could be habouring it. How can I make it work -
Views.py ,Incrementing score by one for each correct option
I am making a quiz application, for result calculation I have written logic ..If the value of answer stored in question model is equal to the answer chosen by user then , when user submits each question , score is incrementing by one, but I've failed to build this logic as am a new user to django please help. Models.py : question along with its 4 options and the correct answer is in question model(These fields are entered by the user who creates a quiz by filling a form). Answer submitted by user is in answer model(This field is entered by user who takes quiz). score is stored in result model. from django.db import models from django.contrib.auth.models import User from django.conf import settings class quiztitle(models.Model): Quiz_id = models.AutoField(primary_key=True) Quiz_title = models.CharField(max_length=600) User = settings.AUTH_USER_MODEL User_id= models.ForeignKey(User, on_delete=models.CASCADE) class question(models.Model): Qid = models.AutoField(primary_key=True) User = settings.AUTH_USER_MODEL User_id = models.ForeignKey(User,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle,on_delete=models.CASCADE) Qques = models.TextField() Qoption1 = models.TextField() Qoption2 = models.TextField() Qoption3 = models.TextField() Qoption4 = models.TextField() QAnswer = models.TextField() class answer(models.Model): Ansid = models.AutoField(primary_key=True) Qid = models.ForeignKey(question,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle, on_delete=models.CASCADE) User = settings.AUTH_USER_MODEL User_id = models.ForeignKey(User, on_delete=models.CASCADE) Answer = models.TextField() class result(models.Model): result = models.AutoField(primary_key=True) Quiz_id = models.ForeignKey(quiztitle, on_delete=models.CASCADE) … -
How do I host paid videos on my django website
I have a django website currently hosted on pythonanywhere. It operate just like Udemy, how do I uppload my videos to a secure server? -
How to associate data sent by a user to his own account in Django
I have a model called KeyFormModel which has 2 fields "secret_key" and "primary_key", I pointed this model towards a form and called this form to a view and template. each user has exactly one primary_key and one secret_key, when I send this to model they are mixing with other keysets this is my model class KeyFormModel(models.Model): username = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) primary_key = models.CharField(max_length=200) secret_key = models.CharField(max_length=200) def __str__(self): return username+"_keys" class Meta: verbose_name_plural = 'Keys' this is my form from ..models import KeyFormModel from django import forms from django.conf import settings class KeyForm(forms.ModelForm): primary_key = forms.CharField(required=True) secret_key = forms.CharField(required=True,widget = forms.PasswordInput) class Meta: model = KeyFormModel fields = ("username","primary_key","secret_key") this is my view @cache_control(no_cache=True, must_revalidate=True) @login_required(login_url='../login') def AccountView(request): if(request.method == 'POST'): form =KeyForm(request.POST) if(form.is_valid()): form.save() else: for msg in form.error_messages: messages.error(request,f"{msg}") form = KeyForm return(render(request, 'accountView.html',context={"form":form})) as you can see I am trying to add username from AUTH_USER_MODEL after logging into that account but failing miserably. please hlp -
Is transaction atomic will cover all my queries in my function / is this a safe and correct way?
I'm working on a small project using Django and I would like to know if the way that I'm using, transaction atomic is correct and save for the queries? this is my code : def create(first_name, last_name, username): try: with transaction.atomic(): # Create Tenant / Set domain name for the tenant in question / Create User with schema_context('public'): tenant = Client( schema_name=str(username), name=first_name + '_' + last_name, paid_until='2014-12-05', on_trial=True) tenant.save() domain = Domain() domain.domain = str(userInQuestion.username) + settings.BASE_URL # tx.domain.com domain.tenant = tenant domain.is_primary = False domain.save() user = CustomUser() user.first_name = first_name user.last_name = last_name user.username = username user.password = set_password('admin') user.save() with schema_context(current_schema): addUserInTeam = Team.objects.create(user = CustomUser.objects.get(pk=userid)) except: transaction.set_rollback(True) -
How to get sum of the production_volume in a seasion of a particular fiscal_year using Django ORM
Here, I'm trying to get the sum of the production_volume different seasons in particular production_year: here is my models: class FiscalYear(BaseModel, models.Model): year = models.CharField(max_length=256) class Season(BaseModel, models.Model): name = models.CharField(max_length=256) season_month = models.ManyToManyField(Month) class Product(BaseModel, models.Model): name = models.CharField(max_length=256) category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL, related_name='product_category') description = models.CharField(max_length=1000) hs_code = models.CharField(max_length=256, unique=True) photo = models.ImageField(upload_to='media/product/%Y/%M/', null=True, blank=True) production_unit = models.ForeignKey(MeasurementUnit, related_name='product_unit', null=True, blank=True, on_delete=models.SET_NULL) class Production(BaseModel, models.Model): product = models.ForeignKey(Product, related_name='production_product', on_delete=models.CASCADE) district = models.ForeignKey(DistrictLevel, related_name='production_district', on_delete=models.CASCADE) production_volume = models.FloatField() production_year = models.ForeignKey(FiscalYear, related_name='production_year', null=True, blank=True, on_delete=models.SET_NULL) seasons = models.ManyToManyField(Season, related_name='product_season') I'm getting result by using for loop, aggregate but I think this is not appropriate. Which is below: fiscal_year = FiscalYear.objects.all().first() # for test for i in Season.objects.all(): production_year = Production.objects.filter(production_year = fiscal_year).filter(seasons=i).aggregate(total_production = Sum('production_volume')) print(production_year ,909090) How can i get result by ORM methods. I tried by using related_name with aggregate and annotate but it didn't work. Below what I want exactly: -
django-admin command not regonized
I have installed django on my computer but when i try to run any django-admin command on my terminal i get this error: django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + django-admin startproject app + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException I am using powershell and visual studio code Is there any way i can fix this? -
PyCharm Django Project: Changes in CSS stylesheet do not update
In a Django project on PyCharm changes to the main.css file do not work. Chache should not be a problem, as I deleted it and also tried it on a newly downloaded browser. Also the exact same code works on another computer. It seems like the problem is with my PyCharm somehow. Did anyone encounter the same problem? Thanks! -
In Django I cant retrieve the values for Upload cv, Status, gender in the edit.html form from the database but I can retrieve the other field values
enter image description hereThis is my edit.html code and during retrieving the values from database it shows only the text fields like value={{ i.full_name}} but when I am writing value={{ i.cv}}, value={{ i.status}}, value={{ i.gender}} it does not shows the value which needs to bed edited I have two choice fields and one file field and also when I am uploading a pdf file it is getting stored in media folder and I am showing that file in a table but if a file name which which I have uploaded name java.pdf after uploading it changes to some random name after original name like java_hjh45.pdf why this is happening I don't know this is my edit.html <section class="site-section"> <div class="container"> <div class="row"> <div class="col-lg-12 mb-5"> <h2 class="mb-4 text-center">Update Candidate Details</h2> <form method="POST" action="/update/ {{i.id}}/" enctype="multipart/form-data" class="p-4 border rounded" onsubmit="myFunction()" > {% csrf_token %} {% comment %} <input type="hidden" name="csrfmiddlewaretoken" value="UabxqpD8HGPOu1ZSFnIHAPbMtRgWBAnVHEs8bLDx0HnxN6uhG3LyYvZShvcx1ekn"> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="full_name">Full Name :</label> <input type="text" class="form-control" value ={{ i.full_name}} name="full_name" id="id_full_name" placeholder="Enter First Name"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="recruiter_name">Recruiter Name :</label> <input type="text" class="form-control" value ={{ i.recruiter_name }} name="recruiter_name" id="id_recruiter_name" placeholder="Enter … -
Why django throws an integrityError?
I have a very weird exception I have no idea how to handle it. Until now, everything worked fine, but after I did some changes(not on database per se), out of 16 objects listed on my website, 2 throw to me this error when I want to delete one from Admin Pannel: FOREIGN KEY constraint failed models.py class Products(models.Model): name = models.CharField(max_length=50, blank=True, null=True) price = models.FloatField(blank=True, null=True) description = models.TextField(max_length=300, blank=True, null=True) resealed = models.BooleanField(blank=True, null=True) category = models.ForeignKey(to=SubCategories, on_delete=models.CASCADE, blank=True, null=True) image = models.ImageField(upload_to='gallery', blank=True, null=True) quantity = models.IntegerField(default=1) class SubCategories(models.Model): name = models.CharField(max_length=50, blank=True, null=True) description = models.TextField(max_length=500, blank=True, null=True) image = models.ImageField(upload_to='gallery', blank=True, null=True) par_category = models.ForeignKey(to=Categories, on_delete=models.CASCADE, blank=True, null=True, related_name="Category") class Categories(models.Model): name = models.CharField(max_length=50, blank=True, null=True) description = models.TextField(max_length=300, blank=True, null=True) I set on_delete=models.CASCADE. 3 days ago, I did some changes in the database in the sense that I renamed the old Category table to SubCategories and I created a new table Categories. With this move, I have created par_category constraint to the newly created table. After I did some refractors, two out of 16 elements throw me that error when I am trying to delete them. Can somebody help me with this issue? … -
How to add index_together when iexact is used
I am creating a index on 2 columns index_together = [["name", "value"]] but I also want it to be case insensitive, because one of my filters will use iexact. Any idea how this can be achieved? Using Django and Python. I am open to adding raw SQL to migration as well, if someone can also help with that -
django view does not catch an exception occurred by signal
I am a newbie of Django and have a question about exception handling. In my Django view file, I have a function like below. def timeTest(request): try: result = longTimeFunction() return HttpResponse(json.dumps(result)) except: raise Exception() I want to use the signal so that if the function longTimeFunction() takes more than 3 seconds, it will raise an exception as below. from functools import wraps import errno import os import signal class TimeoutError(Exception): pass def timeout(seconds=10, error_message=os.strerror(errno.ETIME)): def decorator(func): def _handle_timeout(signum, frame): raise TimeoutError(error_message) def wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(seconds) try: result = func(*args, **kwargs) finally: signal.alarm(0) return result return wraps(func)(wrapper) return decorator and the function longTimeFunction() looks like below. @timeout(3) def longTimeFunction(): do some computations here ... So, what I want is to raise an exception when the longTimeFunction takes more than 3 seconds. and the exception will be handled in the middleware. However, instead of catching the exception in the view so that it can be handled in the middleware, the signal raise exception and shows it directly to the browser. I do not know, but an exception occurred by the signal is not caught? -
Django Reset Loop in Template
How to reset loop (e.g. if a category change, reset the counter for sub category) in Django template? Game 1.1. Cricket 1.2. Football 1.3. Base Ball Pets 2.1. Dog 2.2. Cat 2.3. Fish NB: forloop.counter can't reset. -
Django Exclude Model Objects from query using a list
Having trouble with my query excluding results from a different query. I have a table - Segment that I have already gotten entries from. It is related to another table - Program, and I want to also run the same query on it but I want to exclude any of the programs that were already found during the segment query. When I try to do it, the list isn't allowed to be used in the comparison... See below: query = "My Query String" segment_results = Segment.objects.filter( Q(title__icontains=query)| Q(author__icontains=query)| Q(voice__icontains=query)| Q(library__icontains=query)| Q(summary__icontains=query) ).distinct() # There can be multiple segments in the same program unique_programs = [] for segs in segment_results: if segs.program.pk not in unique_programs: unique_programs.append(segs.program.pk) program_results = ( (Program.objects.filter( Q(title__icontains=query) | Q(library__icontains=query) | Q(mc__icontains=query) | Q(producer__icontains=query) | Q(editor__icontains=query) | Q(remarks__icontains=query) ).distinct()) & (Program.objects.exclude(id__in=[unique_programs]))) I can run: for x in unique_programs: p = Program.objects.filter(id=x) print("p = %s" % p) And I get a list of Programs...which works Just not sure how to incorporate this type of logic into the results query...and have it exclude at the same time. I tried exclude keyword, but the main problem is it doesn't like the list being in the query - I get an error: … -
Date names localization in Pyton
I parse the site and get a date like this: 2021. május 7., péntek, 15:17 I realized that in python it has this format: %Y. %B %d., %A, %H:%M But when I specify it, an error occurs, I think it's because of the months and days of the week in Hungarian, since my locale is in English. Error: ValueError: time data '2021. május 7., péntek, 15:17' does not match format '%Y. %B %d., %A, %H:%M' Actually, the question is, can I change the locale on the fly in the datetime? -
how do I filter references to avoid getting duplicates in after each execution?
I want to say the following if product exists in product table, but if not exist order refences in order table add , but if exists skip ? however I dig in the docs to do something like the following to avoid adding duplicate references in my case I am using arrayfield for references to use it like field___in how do I improve if product_id is not None and order_id is None: ? from django.db.models import Q obj, created = Person.objects.filter( Q(first_name='Bob') | Q(first_name='Robert'), ).get_or_create(last_name='Marley', defaults={'first_name': 'Bob'}) my own implementation try: product_id = Product.objects.get(productid=product_objects.get('id')) except Product.DoesNotExist as err: product_id = None try: order_id = Order.objects.get(product=product_id) except Order.DoesNotExist as err: order_id = None source, created = Source.objects.get_or_create(name='stysta') _url = product_objects.get('html_url') demo = Order.objects.filter(product=product_id,reference=_url) print(demo) if product_id is not None and order_id is None: product, created = Order.objects.get_or_create( product=order_id, reference=_url, date=product_objects.get('updated_at') ) models class Product(models.Model): productid = models.CharField(max_length=32, unique=True) [...] date = models.DateTimeField(default=timezone.now) class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) reference = ArrayField(models.URLField()) date = models.DateTimeField() -
Django Graphene/GraphQL best design for model field-level permissions
I am using Django as back-end with graphene-django serving the front-end. I am new to both django and graphene so I am not sure what is the best approach to achieve field-level permissions with no code repetition in this set-up. For example, if my model is: class MyModel(models.Model): field1 = models.CharField() field2 = models.CharField() I want to be able to specify that user1 can read field1 but not field2; when the user1 queries GraphQL for all MyModels it would be only allow to retrieve field1 from rows (nodes) and not field2. I did a bit of research and found 2 possible alternative solutions but I fear they may not be in the spirit of Django framework and/or conflicting with each other and there may be a better way to achieve this in Django. Ultimately I don't want to be repeating the permissions code in multiple parts of the Django and Graphene back-end so want this to be centralised at the lowest possible level, ideally at the Django model. I need to be able to control full CRUD per field depending on user_id and maybe even have some additional logic. The options I found were: overriding retrieve_node in graphene-django DjangoObjectType to … -
Recommended way to do math on database to show in template in Django
I need to get some data from the database, do some calculation and show the results in the template. From my research I saw that I could use django-mathfilters. But I read that it is not recommeded to include business logic in the template. So I researched for alternatives. It seems that I could use annotate. So I have tried this: def price_supplier(request): list = request.GET.get("list") price_list = SupplierPriceList.objects.filter(id=list).annotate(margin=(F('cod_product.sale_price') - F('price')) / F('cod_product.sale_price')).all() return render(request, 'painel_fornecedor/comparacao_precos.html', {'price_list': price_list}) I have tested this and got the error "Cannot resolve keyword 'cod_product.sale_price' into field." How is the recommended way to implement this? Here is the model: class Product(models.Model): cod_product= models.IntegerField(primary_key=True) descripction = models.CharField(max_length=120, blank=True, null=True) sale_price = models.DecimalField(max_digits=20, decimal_places=10, blank=True, null=True) class SupplierPriceList(models.Model): cod_produto= models.IntegerField(primary_key=True) cod_product = models.ForeignKey(Product, on_delete=models.PROTECT, blank=True, null=True) price = models.DecimalField(max_digits=20, decimal_places=10, blank=True, null=True) Thanks in advance! -
Django AttributeError " " object has no attribute " "
I'm working on CS50w network on the followings/followers feature. I am stuck on counting the followers: This is my model: class Following(models.Model): """Tracks the following of a user""" user = models.ForeignKey(User, on_delete=models.CASCADE) followings = models.ManyToManyField(User, blank=True, related_name="followers") Using the code below, I can successfully get the followings count: user = Following.objects.get(user=user_instance) followings = user.followings.count() However, I can't get the followers, this is what I tried: user = Following.objects.get(user=user_instance) followers = user.followers.count() It is worth mentioning that if I passed the user and tried to get the `followers', I get it successfully using: {{user.followers.count}} However, I can't use this method since I need to handle corner cases in the backend. -
DRF test for APIView returns 400
I know that it's already a lot of same questions, but it wasn't helpful for me, so I need any ideas where the bug is. I have a super-simple DRF APIView(all imports are fine): class MyView(APIView): permission_classes = (AllowAny,) def post(self, request: Request) -> Response: return Response({'status': 'success'}, status=status.HTTP_200_OK) And here is my test (ignore the payload, it's just simplified for this question-post): import json from django.urls import reverse from rest_framework.test import APITestCase from web.models import User class MyViewViewTestCase(APITestCase): def setUp(self): self.username = 'test@example.com' self.pwd = '1234' self.user = User.objects.create_user(self.username, self.pwd) def request(self, data): self.client.login(username=self.username, password=self.pwd) return self.client.post(reverse('my-view-url-name'), data=data, format='json') def test_my_view(self): response = self.request(json.dumps({ 'some-data': 'some-data', })) print(response.content) self.assertEqual(response.status_code, 200) So, I got here 400 instead of 200. And response type is <HttpResponseBadRequest status_code=400, "text/html"> And response.content is: b'\n<!doctype html>\n<html lang="en">\n<head>\n <title>Bad Request (400 </title>\n</head>\n<body>\n <h1>Bad Request (400)</h1><p></p>\n</body>\n</html>\n' So, considering that api view is expected to return 200 w/o any other action, my guess that I'm doing something wrong in test, but can't get what exactly. Any ideas where I might be wrong? View itself works correctly. Thanks! -
Django API : Variable Filter (is null)
I'm working on my Django project, I have Django running as rest API and I want to filter value null based on a variable column that the user gonna choose. For filtering by equals I did something like that : field = fields[i] value = values[i] queryset = queryset.filter(**{field:value}) but if i leave value empty the query does not work . -
keep getting syntax error running manage.py
Just trying to set up my first django app on pythonanywhere eu region 13:29 ~/OP (master)$ ./manage.py makemigrations OP File "./manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax 13:29 ~/OP (master)$ -
clean() method in form not working (loading it into ListView)
I've tried searching around and reading the docs but I don't quite understand how to get the clean() method to work when dealing with ListView's, get_querysets() and get methods. I've tried adding in a breakpoint() in the clean() method and it doesn't get triggered meaning it's not called at all. My suspicion is because I'm not using post as the method in the form but I need to use get in order to build a filter query to a query set (namely, it's a date picker using from and to). This is my setup (omitting details): Form: class ReportForm(forms.Form): ... def clean(self): super().clean() ... return self.cleaned_data ListView: class ReportView(ListView): form_class = ReportForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) form = kwargs.get('form', self.form_class()) context['form'] = form return context def get_queryset(self): # Details omitted but I'm essentially taking data from the form # and using it to filter a QuerySet from_date = self.request.GET.get('from_date') to_date = self.request.GET.get('to_date') ....... return QuerySet Template: <form action="" method="get"> {% csrf_token %} {% crispy form %} </form> Does anyone know why my clean method isn't being called? -
Validated data is empty
I use Django REST Frameworke in my application. I want to create like for posts My api view: class LikePostAPIView(CreateAPIView): model = Like permission_classes = [ permissions.IsAuthenticated ] serializer_class = LikeCreateSerializer My LikeCreateSerializer: class LikeCreateSerializer(serializers.ModelSerializer): def create(self, validated_data): print(validated_data) class Meta: model = Like fields = ('post_id', ) I send JSON data: { "post_id": 1 } But i get 500 HTTP status because my validated_data is empty in serializer