Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM Prefetch and filter results
I want to filter GeneralItem by manytomany items without null (filtered by Prefetch): class GeneralItem(models.Model): title = models.CharField(max_length=250) items = models.ManyToManyField('MediaItem') qs = GeneralItem.objects.prefetch_related( Prefetch( 'items', queryset=MediaItem.objects.filter(**item_params), to_attr='custom_items' ) ).filter(custom_items__isnull=False) But I get error: Cannot resolve keyword 'custom_items' into field. Choices are: items, title Is there a way to filter this? -
Conditional unique_together in Django
I have following unique constraint in my model. class Meta: unique_together = (('crop', 'order', 'sku'),) But sku may be null in some cases and in that case this unique_together is not working as null is not equal to null.i am thinking to make a conditional unique_together like if sku is not null then (('crop', 'order', 'sku'),) else (('crop', 'order'),). -
How can I edit many to many relations in Django (admin sites)
I need to add tags to my blog posts. Each tag should be available on many posts and also posts can have multiple tags. How can I change the admin sites so that I can add multiple (existing) tags to a post? The standard view only lets me add by creating new ones. model.py # blog post tags class Tag(models.Model): name = models.CharField(max_length=20) slug = models.SlugField(max_length=40, unique=True) date_created = models.DateTimeField(default=timezone.now) class Meta: ordering = ['name'] def __str__(self): return self.name # blog posts class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) last_modified = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) # 1 author per post tags = models.ManyToManyField(Tag, related_name='tags') # n tags per m posts class Meta: ordering = ['title'] def __str__(self): return self.title Current Admin Site I know I need to edit my admin.py file in my blog application but everything i tried so far did not work. Is there a recipe for these admin views? I want to achieve something like this (1st answer - filtered view). -
Changing default "migrations" directory
What I want to do: To use a different name for the "migrations" folder. What I tried: It seems like the default approach is to set the 'MIGRATION_MODULES' in settings.py (as documented here): MIGRATIONS_MODULE = {'app_name':'app_name.migrations_folder_name'} But for some reason caused the migrations of the default apps to fail: You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, authtoken, contenttypes, sessions. How can I make sure that the default apps migrations works as intended? -
How to fix Reverse for '' not found. '' is not a valid view function or pattern name
I have a custom form created in my template with two datefields and one custom autocomplete field. My aim is to take the values of those datefields in my view and afterwards to create and call a url with ajax. After submiting the button I face with the error: Reverse for '' not found. '' is not a valid view function or pattern name. How can i fix this? template <script> $(document).ready(function() { $('#offers').DataTable( { "pagingType": "full_numbers" } ); } ); $('#offers').dataTable( { "serverSide": true, // "ajax": "https://www.example.com/api/v2/offers?dateFrom={{from_date}}T00%3A00%3A00&dateTo={{to_date}}T00%3A00%3A00&{{companyId}}" "ajax": '{{url}}' } ); </script> <form action="" method="get"> {% csrf_token %} <label for="from_date">From date</label> <input type="date" id="from_date" name="from_date"> <label for="to_date">To date</label> <input type="date" id="to_date" name="to_date"> <label for="company">Company</label> <select name="companyId" class="company" id = "company"></select> <button class="btn btn-primary" id ="submit" type="submit" > Submit </button> </form> <script> $('.company').select2({ ajax: { url: '{% url "mmkcompany-autocomplete" %}', dataType: 'json' } }); </script> view from_date = self.request.GET.get('from_date','') #string from_= "dateFrom="+from_date+"T00%3A00%3A00" to_date = self.request.GET.get('to_date','') #string to_= "dateTo="+to_date+"T00%3A00%3A00" company = self.request.GET.get('companyId','') #string companyId = "companyId="+company if self.request.method == 'GET' and from_date !="" and to_date!="": headers = { 'accept': 'application/json', 'Authorization': '', } url = 'https://www.example.com/api/v2/offers?'+from_+"&"+to_ existence = 1 try: offer_request = requests.get(url, headers=headers) existence = 2 except: print("nothing") if existence … -
Django test failing due to AssertionError:201 !=400
Got the following view class MyUserCreate(APIView): ''' Creates the user. ''' def post(self, request, format='json'): serializer = MyUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And wanted to create a test to ensure I'm not able to create a user with the same username. In serializers.py, the username in MyUserSerializer loks like this username = serializers.CharField( validators=[UniqueValidator(queryset=User.objects.all())], max_length=32 ) and in models.py, the username in MyUser username = models.CharField(db_column='username', unique=True, max_length=20) In tests.py class MyUserTest(APITestCase): ... def test_create_user_with_preexisting_username(self): data = { 'username': 'testing', 'password': 'test' } response = self.client.post(self.create_url, data, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(MyUser.objects.count(), 1) self.assertEqual(len(response.data['username']), 1) Up to this point the tests for user creation, user without username, user with a too long username, ... all worked out fine. The problem only happens in this specific test. The user testing exists in the DB If I run python manage.py tests then FAIL: test_create_user_with_preexisting_username (codeLabsApp.tests.MyUserTest) Ensure we can't create a user with preexisting username. ---------------------------------------------------------------------- Traceback (most recent call last): ... AssertionError: 201 != 400 So I'm getting a 201 Created instead of a 400 Bad Request. -
How authenticate with username, password and token in Django?
I'm trying to authenticate users in Django with username, password and token. All of them are stored in a database. #accounts/views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from account.forms import RegistrationForm, AccountAuthenticationForm def login_view(request): if request.POST: form = AccountAuthenticationForm(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] token = request.POST['token'] user = authenticate(username = username, password = password, token = token) if user: login(request, user) return redirect("home") else: form = AccountAuthenticationForm() context['login_form'] = form return render(request, 'account/login.html', context) #account/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, username, token, password=None): if not username: raise ValueError('Users must have an username') if not token: raise ValueError('Users must have a token') user = self.model( username = username, token = token, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, token, password=None): user = self.create_user( username = username, password = password, token = token, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user Login is possible with the right username/password combination, but with the wrong token. What am I doing wrong? -
How to have list of strings in Django REST framework model using MongoDB
I am using Django version 2.2.11 with MongoDB as database I a Simple Array Field to store a list of strings in a Django REST framework Model. I want the serialized JSON output to be like this. { name : "John" roles : [ "string1", "string2" ] } I searched the internet and could only find implementation of this for PostgreSQL. I just need to store the data of roles as string/list in database and need to display in proper format in api view. -
Django Redirect to different URL base on forms choice
Hello I stack with redirect to different pages base on Form Choice in Django. I have 4 different choices to pick, but everyone has different next page. I do something like this : forms.py class DodajForm(forms.ModelForm): class Meta: model = Atrakcje exclude = ['user'] fields = ['tytul', 'opis', 'kategoriaa', 'adres', 'wojewodztwo', 'miasto', 'telefon', 'zdjecie', 'wideo', 'email', 'strona', 'facebook', 'kodpocztowy', 'zaswiadczenia', 'pakiet', 'cena', 'dla'] widgets = { 'kategoriaa': forms.Select( attrs={ 'class': 'form-control' } ), 'pakiet': forms.Select( attrs={ 'class': 'form-control' } ), 'tytul': forms.TextInput( attrs={ 'class': 'form-label' } ), 'opis': forms.Textarea( attrs={ 'class': 'form-control' } ), 'zdjecie': forms.FileInput( attrs={ 'class': 'dropzone dz-clickable', } ), 'zaswiadczenia': forms.FileInput( attrs={ 'class': 'dropzone dz-clickable', } ), } views.py def formularz(request): form = DodajForm(request.POST) if form.is_valid(): ogloszenie = form.save(commit=False) ogloszenie.user = request.user ogloszenie.save() if form.pakiet == "free": return redirect('atrakcje:after') elif form.pakiet == "pakiet1": return redirect('atrakcje:after1') elif form.pakiet == "pakiet2": return redirect('atrakcje:after2') else: return redirect('atrakcje:after3') else: ogloszenie = DodajForm() context = { 'form': form,} return render(request, 'formularz.html', context) and I have error on every choice like this : "AttributeError at /atrakcje/formularz/ 'DodajForm' object has no attribute 'pakiet' There is a error on this line : if form.pakiet == "free": Any recommendations how to resolve this please? -
django - mark_safe is not working as it is supposed to?
I don't know why but my mark_safe is not working properly,It's still loading html as a normal text. I had to use mark_safe on one of my serializer field and then get them through my api on the frontend by using jquery but I tried to use safe filter in my seriliazer,the format_html,mark_safe but it's still loading my html as a text,this field which I am trying to pass as safe is an HTMLField by tinymice! Here's my serializer class FooterSerializer(serializers.ModelSerializer): disclaimer = serializers.SerializerMethodField(read_only=True) class Meta: model = Footer fields = ["disclaimer"] def get_disclaimer(self,obj): disclaimer = mark_safe(obj.disclaimer) return disclaimer And here's my ajax call // FOOTER Disclaimer $.ajax({ url:'/api/footer/', method:"GET", headers: { 'Accept-Language':language, } , success:(data)=>{ $(".footer-disclaimer").text(data.footer.disclaimer) }, error:(data)=>{ $(".footer-disclaimer").text("Err! Disclaimer not loading....") } }) -
Problem django objects function "SUM AGGREGATE RETURN AND SAVE"
im trying to save as object by using this code, but it's give me just a "function return", and not the real value. when i did the same in admin it works fine, but i did'n save that in my db. here my code in admin: def get_total_carregado(self, obj): filt = obj.contrato tot = Carga.objects.filter(pedido__contrato=filt).values('pedido').aggregate(pesot=Sum('peso'))['pesot'] return tot get_total_carregado.short_description = "Carregado" and now in models: def get_carregado(): filt = Pedido.contrato return Carga.objects.filter(pedido__contrato=filt).values('pedido').aggregate(pesot=Sum('peso'))['pesot'] this is what i got : it's not what i want :( -
Pytest-Django on code that gets its own database connection
I have some classes that get their own database connections: from django.db import connections from psycopg2 import extensions class Foo: def __init__(self, *args, **kwargs): conn_wrapper = connections["name"] if not conn_wrapper.connection: conn_wrapper.connect() conn = conn_wrapper.connection conn.set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT) self.conn = conn The code works, but in tests, pytest-django complains that it requires the @pytest.mark.django_db decorator. The problem is that when I add this to the test class, it still complains that it requires this decorator. -
customized backend alert service for users
I was making a price comparison web app for multiple online websites. I have already made the crawler how can I make a custom alert service for multiple users so that it crawls web at regular intervals and send an alert when the price is below user specified price . how can I passively make it work even when the user in not connected ? suggesting some videos would be enough. thanks.. -
Intersection of Filter Results in Django RestFrameWork
I have created and endpoint to filter Users based on their KYC (Know Your Customer) PAN (An Identity Proof Used in India) Status. my url is as below: user-management/users/kyc/?kyc_document__document_type__verification_type=PAN&kyc_document__verification_status=VERIFIED The Models and Relations are as Below: User: The User Model Storing User Data VerificationDocuments: VERIFICATION_PENDING = "VERIFICATION_PENDING" VERIFIED = "VERIFIED" REJECTED = "REJECTED" VERIFICATION_STATUS = ( (VERIFICATION_PENDING, "Verification Pending"), (VERIFIED, "Verified"), (REJECTED, "Rejected"), ) user = models.ForeignKey( "User", related_name="kyc_document", on_delete=models.CASCADE ) document_type = models.ForeignKey( "DocumentType", related_name="document_verification", on_delete=models.CASCADE ) verification_status = models.CharField( max_length=24, choices=VERIFICATION_STATUS, default=VERIFICATION_PENDING ) DocumentType: PAN = "PAN" ADDRESS = "ADDRESS" BANK = "BANK" DEMAT = "DEMAT" VERIFICATION_TYPE = ( (PAN, "PAN Verification"), (ADDRESS, "Address Proof"), (BANK, "Bank Account Verification"), (DEMAT, "Demat Account Verification"), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=64) verification_type = models.CharField(max_length=10, choices=VERIFICATION_TYPE) details = models.TextField(null=True, blank=True) def __str__(self): return self.name The View: class KYCList(generics.ListAPIView): permission_classes = () serializer_class = KYCListSerializer queryset = User.objects.all() filter_backends = [ DjangoFilterBackend, filters.SearchFilter, ] # filter_backends = (rest_framework_filters.backends.ComplexFilterBackend,) # filterset_class = UserKYCFilter filterset_fields = ( "kyc_document__document_type__verification_type", "kyc_document__document_number", "kyc_document__verification_status" ) # filter_backends = (CustomizedBackend,) search_fields = ["$first_name", "$last_name", "$mobile", "$email"] When i get the results, the output contains the details of Users , if any of the filter criteria is … -
Django Managemengt Command Logging Buffers Messages
When I issue log statements from a Django management command, they always get joined into one big log statement for the whole command execution. Instead, I want them to be issued individually line by line like usual application logs. That way log aggregation can pick them up properly and not as one extremely large message. LOGGING_ROOT_HANDLERS = ['prometheus', 'console'] LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'json': { '()': 'pythonjsonlogger.jsonlogger.JsonFormatter', 'fmt': '%(levelname)s %(levelno)s %(pathname)s %(funcName)s %(asctime)s %(message)s', }, }, 'filters': { 'require_debug_true': {'()': 'django.utils.log.RequireDebugTrue'}, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'json', }, 'prometheus': { 'level': 'WARNING', 'class': 'app.logging_handlers.PrometheusHandler', }, }, 'loggers': { '': {'level': 'INFO', 'handlers': LOGGING_ROOT_HANDLERS}, 'myapp.management.commands': { 'handlers': LOGGING_ROOT_HANDLERS.copy(), 'level': 'INFO', 'propagate': True, }, 'django': { 'handlers': LOGGING_ROOT_HANDLERS.copy(), 'level': 'WARNING', 'propagate': False, }, 'django.request': { 'handlers': LOGGING_ROOT_HANDLERS.copy(), 'level': 'INFO', 'propagate': False, }, }, } import logging from django.core.management.base import BaseCommand logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): logger.info("Message %s", "1") logger.info("Message %s", "2") Current output: {"levelname": "INFO", "levelno": 20, "pathname": "runcommand.py", "funcName": "<module>", "asctime": "2020-06-03 09:32:19,497", "message": ""} {"levelname": "WARNING", "levelno": 30, "pathname": "runcommand.py", "funcName": "<module>", "asctime": "2020-06-03 09:32:19,498", "message": "{\"levelname\": \"INFO\", \"levelno\": 20, \"pathname\": \"/www/app/myapp/management/commands/mycommand.py\", \"funcName\": \"handle\", \"asctime\": \"2020-06-03 … -
How to compile single python scripts (not to exe)?
I know there is a lot of debate within this topic. I made some research, I looked into some of the questions here, but none was exactly it. I'm developing my app in Django, using Python 3.7 and I'm not looking to convert my app into a single .exe file, actually it wouldn't be reasonable to do so, if even possible. However, I have seen some apps developed in javascript that use bytenode to compile code to .jsc Is there such a thing for python? I know there is .pyc, but for all I know those are just runtime compiled files, not actually a bytecode precompiled script. I wanted to protect the source code on some files that can compromise the security of the app. After all, deploying my app means deploying a fully fledged python installation with a web port open and an app that works on it. What do you think, is there a way to do it, does it even make sense to you? Thank you -
Django urlpatterns when a category is included into URL
Django 3.0.6 urlpatterns = [ path('', HomeView.as_view(), name='home'), path('{}'.format("admin/" if DEBUG else "dhjfsljdasdhje32/"), admin.site.urls), # Change admin url for security reasons. path('image/', include(('image.urls', 'image'), namespace="image")), path('polls/', include(('polls.urls', 'polls'), namespace="polls")), path('applications/', include(('applications.urls', 'applications'), namespace="applications")), ] def _get_categories_url_pattern(): """ Organize urls with posts categories. URL format: <category>/<post_slug> Example: linux/how_to_install_ubuntu/ """ categories = Category.objects.all().values_list("slug", flat=True) for category in categories: urlpatterns.append(path('{}/'.format(category), include('post.urls'))) urlpatterns.append(path('draft/{}/'.format(category), include('post.urls'))) _get_categories_url_pattern() Please, concentrate your attention on how categories in urls are handled. Problems with this code: When a new category is added in the admin site, Django project has to be relaunched (at least with the built in dev server). When last time I did python manage.py makemigrations it blew up. I had to comment out anything having anything to do with _get_categories_url_pattern. Then it made migrations. Now I can't reproduce this error anymore. But there seems to be some danger in this code. Could you help me understand how to refactor this code for it to work at least without restarting the dev server when a new category is added. -
function in views not called while sending POST request to django
I am beginner to Django and I am working to store input form data to database with using HTML forms.But whenever the request generated, the register function isn't called. My login form and registration form are in a single web page.My webpage consists a scroll down animation effect on opening of registration form. Here is my code : Login.html (with Javascript(jQuery)) <strike> <!DOCTYPE html> <html lang="en"> <head> <link href="https://cdnjs.cloudflare.com/ajax/libs/holder/2.9.7/holder.min.js" rel = "stylesheet" type="text/css"> <link rel="stylesheet" href="jQuery/slick-1.8.1/slick/slick.css" type="text/css"> <link rel="stylesheet" href="jQuery/slick-1.8.1/slick/slick-theme.css" type="text/css"> <link type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">--> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <!--<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>--> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <meta charset="UTF-8"> <title>Login | Register</title> </head> <body> <script> $(document).ready(function(){ $('#lgcollapse').collapse('show'); $('#reg-uncollapse').hide(); $('#register-form-opener').click(function(){ $('#lgcollapse').slideUp(500); setTimeout(function(){ $('#reg-uncollapse').fadeIn(1000); $('#lgcollapse').hide(); },800); }); $('#login-opener').click(function(){ $('#lgcollapse').slideDown(500,function(){ $('#reg-uncollapse').hide(); }); /*setTimeout(function(){ $('#lgcollapse').fadeIn(1000); },800);*/ }); }); </script> <style> .nmp{ background: #ffffff; transition: 1s ease; box-shadow: 5px 5px 10px #bfc2c4, -5px -5px 10px #ffffff; } .nmp:hover{ box-shadow: none; } </style> <body style="background-color: #e9ecef!important;"> <div class = "row my-5" id="lgcollapse" style="background-color: #ffffff!important;box-shadow: inset 5px 5px 18px -2px #000000;margin-right: 0px!important;"> <div class = "container"> <div class = "row"> <div class = "col-md-12"> <div class = "card my-5" style="background-color: #e9ecef!important;"> … -
Translation fails in django-simple-menu
I'm using django-simple-menu in my header navigation and the application has multiple languages. When switching language, the language is stored within the user preferences and everything is translated correctly except the django-simple-menu. When I stop the application and restart, the translation is also applied to simple-menu. I don't know which part of my code to publish here in order to solve the problem, but any help will be appreciated. -
Create directory as service account not the computer
I am struggling with an issue that I do not know how to solve. I am trying to make a directory with python as a different user/under the different credentials. I will explain why. Since I am not able to use internal storage on server/virtual machine but I can use a mapped drive which is on a different machine and make directory there. This will not be an issue if I will make the directory but since I am using the Django and web view the command which is started will be executed with permissions of computer which is not allowed due to the security access the mapped drive and make directory/folder. Is there any option on how to access the mapped drive with different credentials and create the directory/folder? Keep in mind that I am executing the scrip through the website so everything executed is as computer/VM. Thanks -
How to fix the " has no attribute 'objects' " error in django?
I have an attribute error with the line block = Block.objects.filter(chain=chain) in my views.py. I have two models, Chain and Block, as shown here, in my models.py. class Chain(models.Model): """ This model class enables us to save each blockchain separately per user in the database. """ name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) year = models.CharField(max_length=10, default="20XX") sem = models.CharField(max_length=30, default="Default Semester") code = models.CharField(max_length=10, default="SUB-CODE") slot = models.CharField(max_length=10, default="EX+EX") last_updated = models.DateTimeField(auto_now=True) objects = models.Manager() class Block(models.Model): """ This model class enables us to save each block in the database. """ index = models.IntegerField() chain = models.ForeignKey(Chain, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) data = models.TextField() prev_hash = models.CharField(max_length=500) block_hash = models.CharField(max_length=500) objects = models.Manager() This is the function in my views.py. @login_required(login_url='/') def course_view(request, chain_id): try: chain = Chain.objects.get(pk=chain_id) block = Block.objects.filter(chain=chain) except ObjectDoesNotExist: return render(request, 'create_block.html', {'announcements':"You have no attendances marked in this course. Mark attendance for a class to view it."}) return render(request, 'course_view.html', {'blocks':blocks}) What I'm trying to do basically is have two models, where each "Chain" object has multiple "Block" objects and list them in one page. I'm unable to do so because the view function consistently shows AttributeError at /create_block/1 type object 'Block' has no … -
class import : ImproperlyConfigured: The SECRET_KEY setting must not be empty
I have this error whenever I try to import model class from another app. in a helper file helper.py. Project structure: project_dir - main_project_dir - helpers - helper.py - malakar_app - models.py <- contains RunDate model class Now in helper.py: from django.conf import settings from project.models import RunDate def get_run_date_id_from_rundate_field(ac_id, run_date): try: run_date = RunDate.object.get(file_run_date=run_date, client_id=ac_id) return run_date.id except RunDate.DoesNotExist: return None I read something similar about circular dependency but have no idea how to proceed. How can I import the model class in the helper file? -
int() argument must be a string, a bytes-like object or a number, not 'Xray'
I'm trying to create a db entry from two nested serialisers: Here are the Serializers: class BboxSerializer(serializers.ModelSerializer): xray = serializers.IntegerField(required=False) class Meta: model = Bbox fields = ('id', 'xmin', 'ymin', 'xmax', 'ymax', 'xray') class XrayBboxSerializer(serializers.ModelSerializer): bboxes = BboxSerializer(many=True) class Meta: model = Xray fields = ('id', 'bboxes', 'picture', 'pic_name') def create(self, validated_data): bboxes = validated_data.pop('bboxes') xray = Xray.objects.create(**validated_data) for bbox in bboxes: Bbox.objects.create( xray=xray) return xray Here are the models: class Xray(models.Model): picture = models.ImageField(upload_to='xray', blank=True) pic_name = models.CharField(max_length=50, unique=True) expert_check = models.BooleanField(default=0) def __str__(self): return self.pic_name class Bbox(models.Model): xray = models.ForeignKey(Xray, related_name = "bboxes", on_delete=models.CASCADE) xmin = models.FloatField(default=0) ymin = models.FloatField(default=0) xmax = models.FloatField(default=100) ymax = models.FloatField(default=100) def __str__(self): return self.xray.pic_name now when I send this json as request I get this error: int() argument must be a string, a bytes-like object or a number, not 'Xray' My Xray obj gets created but not the Bbox obj for some reason. -
Django: Sort given results of method on model
In Django, how can I sort the results of a method on my model? class Flashcard(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) deck = models.ForeignKey(Deck, on_delete=models.CASCADE) question = models.TextField() answer = models.TextField() difficulty = models.FloatField(default=2.5) objects = FlashcardManager() def __str__(self): return self.question def number_of_questions(self): return self.question.count(deck=deck.id) def get_avg_diff_user(self): avg_diff = Flashcard.objects.filter(owner=self).aggregate(Avg('difficulty'))['difficulty__avg'] return avg_diff So with get_avg_diff_user, I get each user's average difficulty rating. Which I can then use in my leaderboard template as follows: <ol> {% for user in leaderboard_list %} <li>{{user.username}}: {{user.profile.avg_diff_user|floatformat:2}}</li> {% endfor %} </ol> But it's not sorted - how can I sort by avg_diff_user? I've read many similar questions on SO, but to no avail. I've tried a different method on my model: def avg_diff_sorted(self): avg_diff_sorted = Flashcard.objects.all().annotate(get_avg_diff_user=Avg(Flashcard('difficulty'))['difficulty__avg'].order_by(get_avg_diff_user)) return avg_diff_sorted Which I don't think is right and unsurprisingly it didn't return any results in my template. I also tried the following, as suggested in https://stackoverflow.com/a/930894/13290801, which didn't work for me: def avg_diff_sorted(self): avg_diff_sorted = sorted(Flashcard.objects.all(), key = lambda p: p.avg_diff) return avg_diff_sorted -
Unhandled rejection error from fetch in Javascript
I am trying to fetch some JSON file from one Rest API, which can be accessed via http://0.0.0.0:8888/model/?sentence=querys. The response essentially looks like {"out": "Test string"} Now I am starting a Django application, which resides on localhost:8000. I have a Javascript inside which is supposed to fetch the JSON and the relevant code snippet looks as follows: fetch("http://0.0.0.0:8888/model/?sentence=querys") .then(response => response.json()) .then(result => { let responseText = result.out; console.log(responseText); }); Now when I try to fetch the JSON the following error shows up: ERROR Got error: context: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 details: unhandledrejection, Failed to fetch, TypeError: Failed to fetch However, when I change the Url to something from the Github API, everything works as desired. Do you know how to make it work here as well?