Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3.0 ValueError
hello guys am having issues with django 3.0. am trying to create a user register page but i keep getting erros. these are my codes users/views.py from .form import UserRegisterForm from django.shortcuts import render, redirect # Create your views here. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = UserRegisterForm() return render(request, 'register.html', {'form': form}) form.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] register.html {% extends 'website/base.html' %} {% block body %} {% include 'website/nav_bar.html' %} <div> <form method="post"> {% csrf_token %} <fieldset> <legend>join now</legend> {{ form.as_p }} </fieldset> <button type="submit">submit</button> </form> </div> {% endblock body %} ERROR MESSAGE -
How to take url param and use it as filter for data
I'm just getting into Python/Django and I've managed to build an API to return all items in a DB table but I want to be able to filter the data through a parameter used in the GET request. I want to be able to return data based on the 'Author' id that is a number I've built this based on the documentation: View.py class AllTweets(APIView): permission_classes = [IsOwnerOrReadOnly] def get(self, request): tweets = Tweet.objects.all() data = TweetSerializer(tweets, many=True).data return Response(data) URLs.py urlpatterns = [ path('', include('djoser.urls')), path('', include('djoser.urls.authtoken')), path('restricted/', restricted), path('create/', TweetAPIView.as_view(), name="tweet-create"), path('list/', AllTweets.as_view(), name="tweet-list") ] Models.py class Tweet(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="tweets") tweet_text = models.CharField(max_length=200) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweet_text -
Django how to query with condition in a string
I have the following query: list = catalog['model'].objects.all().values(*catalog['id_label']).order_by('name') and I have the following variable: filter='state=1' How can I change all() for filter(), and make django to use the content of variable filter as input for filter()? -
How to post data to database from HTML form having manytomany Field in django?
I am having form consisting of two input fields having some values, Now I want these values to post in the database having manytomanyfield. My form is <div class="card-body"> <form action="{% url 'car:user_register' %}" method="POST" > {% csrf_token %} <div class="form-group" > <input type="text" name="goal" id="goal" value=""> </div> <div class="form-group" > <input type="text" name="goale" id="goal2" value=""> </div> <input type="submit" value="Register" class="btn btn-secondary btn-block"> </form> </div> My models.py is class users(models.Model): email=models.CharField(max_length=50,default='0000000') password=models.CharField(max_length=50,default='0000000') room = models.ForeignKey(rooms,on_delete=models.CASCADE) goal = models.ManyToManyField(goals) The email password and room values are saving but I want to store the two values in the goal field which is manytomanyfield My views.py def user_register(request): if request.method == 'POST': username=request.POST["username"] email = request.POST['email'] password = request.POST['password'] room = request.POST['room'] g = goal=request.POST['goal'] g1 = goal=request.POST['goale'] user = users(password=password,email=email) user.room=rooms.objects.get(pk=room) user.goal=goals.objects.get(pk=g) user.goal =goals.objects.get(pk=g1) user.save() user.goal.add(g,g1) user.save() Is there any wrong in my views.py it is not storing and please how to store data from form to manytomanyfield -
Asyncio NotImplementedError for events
python 3.8 windows OS 10 Django 3.0 I have upgraded to python 3.8 from 3.6.8 but when I started my django project I get following error. By quickly looking at the trace it appears that there is some issue with the asyncioreactor file in twisted package. Any solution to this or is it known bug. > C:\Users\user\Desktop\WorkingPy38\Current> python manage.py > runserver 127.0.0.1:8080 Exception in thread django-main-thread: > Traceback (most recent call last): File > "C:\Users\user\AppData\Local\Programs\Python\Python38\Lib\threading.py", > line 932, in _bootstrap_inner > self.run() File "C:\Users\user\AppData\Local\Programs\Python\Python38\Lib\threading.py", > line 870, in run > self._target(*self._args, **self._kwargs) File "C:\Users\user\.virtualenvs\Current-lgPmbAD0\lib\site-packages\django\utils\autoreload.py", > line 53, in wrapper > fn(*args, **kwargs) File "C:\Users\user\.virtualenvs\Current-lgPmbAD0\lib\site-packages\django\core\management\commands\runserver.py", > line 109, in inner_run > autoreload.raise_last_exception() File "C:\Users\user\.virtualenvs\Current-lgPmbAD0\lib\site-packages\django\utils\autoreload.py", > line 76, in raise_last_exception > raise _exception[1] File "C:\Users\user\.virtualenvs\Current-lgPmbAD0\lib\site-packages\django\core\management\__init__.py", > line 357, in execute > autoreload.check_errors(django.setup)() File "C:\Users\user\.virtualenvs\Current-lgPmbAD0\lib\site-packages\django\utils\autoreload.py", > line 53, in wrapper > fn(*args, **kwargs) File "C:\Users\user\.virtualenvs\Current-lgPmbAD0\lib\site-packages\django\__init__.py", > line 24, in setup > apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\.virtualenvs\Current-lgPmbAD0\lib\site-packages\django\apps\registry.py", > line 91, in populate > app_config = AppConfig.create(entry) File "C:\Users\user\.virtualenvs\Current-lgPmbAD0\lib\site-packages\django\apps\config.py", > line 116, in create > mod = import_module(mod_path) File "C:\Users\user\.virtualenvs\Current-lgPmbAD0\lib\importlib\__init__.py", > line 127, in import_module > return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File > "<frozen importlib._bootstrap>", line 991, in _find_and_load File > … -
Have a Django project that uses Pinax and templates say "load bootstrap." But where is it?
I have a legacy Django project that I know uses "Pinax," and I see templates that say {%load bootstrap%} but ... where is that to be found? (That is to say, "today?") bootstrap3? If so, exactly what am I up against to keep this thing working? -
About wagtail BaseSetting, How can I get setting value in models?
At wagtail Docs, settings can use in view and templates. def view(request): social_media_settings = SocialMediaSettings.for_site(request.site) ... {{ settings.app_label.SocialMediaSettings.instagram }} But how can I use settings in models? I have different style templates in different folders, each template has many head styles. I need to set up the template first, and then select the head template based on this template. -
django - ValueError: <model> needs to have a value for field "id" before this many-to-many relationship can be used
Say, I have a model Post which has many to many relation to built-in User for liked_post class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') like = models.ManyToManyField(User, related_name='liked_posts') All is going nice for the logic, I can add/remove the like relation nicely. But when I introduce additional attribute save for saved_post, like this: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') like = models.ManyToManyField(User, related_name='liked_posts') save = models.ManyToManyField(User, related_name='saved_posts') It always throw an error below when I'm trying to even instantiate the Post model. ValueError: "<Post: Post object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. Note that I did not even modify/add any custom save() method. The error just pops up even when I'm trying to call p = Post.object.create(). From what I have known, I need to save Post first before adding any like or save relation. But I got error even from saving a Post instance. -
Is http stream actually implemented by http chunk?
I did a test to learn http stream and http chunk. Here is a django view func def test_stream(request): def func(): for i in range(0, 100): yield i return StreamingHttpResponse(func) Then I use curl to access the code. There is no chunk headers. Also a tcpdump analysis shows it is not a http chunk either. So questions are: if http stream is not chunk. then what it is implemented? how do i return chunk reponse in Django -
Datatables server side rendering with Django taking long time to respond
Good day guys. I am using datatables with almost 2000 rows. My problem is, it is taking 7-9 seconds to load the page. I tried to implement server side rendering using django_datatables_view: https://pypi.org/project/django-datatables-view/. It seems working because i am receiving the right response with its data but still it was taking 7-9 seconds to load the page. I am missing something? See screenshots below: ]2 -
Run remote Linux Django project on Visual studio code
I have a Linux system with a Django python project created on that. I want to make this system as the center of a distributed development environment. One or many windows Visual Studio Code should be able to open this Django environment and work on it, compile execute on the central Linux system. How can I achieve this? -
calling event to display image in django
when calling image from js event im html for perticuler classes in django this {% load static %} is not working sample.js prth_box_actions = { init: function() { $('.box_actions').each(function(){ $(this).append('<span class="bAct_hide"><img src="img/blank.gif" class="bAct_x" alt="" /></span>'); //$(this).append('<span class="bAct_hide"><img src="{% static 'img/blank.gif' %}" class="bAct_x" alt="" /></span>'); above line is not working when i calling image $(this).append('<span class="bAct_toggle"><img src="img/blank.gif" class="bAct_minus" alt="" /></span>'); $(this).find('.bAct_hide').on('click', function(){ $(this).closest('.box_c').fadeOut('slow',function(){ $(this).remove(); }); }); $(this).find('.bAct_toggle').on('click', function(){ if( $(this).closest('.box_c_heading').next('.box_c_content').is(':visible') ) { $(this).closest('.box_c_heading').next('.box_c_content').slideUp('slow'); $(this).html('<img src="img/blank.gif" class="bAct_plus" alt="" />'); } else { $(this).closest('.box_c_heading').next('.box_c_content').slideDown('slow'); $(this).html('<img src="img/blank.gif" class="bAct_minus" alt="" />'); } }); }); } }; below is my html code <div class="box_c_heading cf box_actions"> <div class="box_c_ico"><img src="/static/img/ico/icSw2/16-Abacus.png" alt=""></div> <p>Statistics</p> <span class="bAct_hide"><img src="img/blank.gif" class="bAct_x" alt=""></span><span class="bAct_toggle"><img src="img/blank.gif" class="bAct_minus" alt=""></span></div> can someone please review this code and help me with this django load static image event call, is this cassing me fustration. and i search for lots of forms for this issue but it is not clear too much too me please please HELP. -
Django resolve() doesn't resolve with i18n urls
Django: 2.2.7 Python 3.6.8 I have initiated a project using cookiecutter-django template. After that I translated to 4 languages and I included i18n for urls so that depending on accessing each one, I get it translated in a different language. For example: http://localhost:8000/en/home => Gets the home page in english http://localhost:8000/es/home => Gets the home page in spanish The thing is that I started to apply TDD and made a test first: myapp/tests.py: from django.test import TestCase from django.urls import resolve from django_sftpbrowser.views import browse_page # Create your tests here. class BrowsePageTest(TestCase): def test_browse_url_resolves_to_browse_page(self): found = resolve('browse/') # Tried also en/browse/ self.assertEqual(found.func, browse_page) But, although the URLs seem to work in the browser, when running this test I find this error: ====================================================================== ERROR: test_browse_url_resolves_to_browse_page (django_sftpbrowser.tests.BrowsePageTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/madtyn/PycharmProjects/corelli/django_sftpbrowser/tests.py", line 9, in test_browse_url_resolves_to_browse_page found = resolve('browse/') File "/home/madtyn/venvs/corelli/lib/python3.6/site-packages/django/urls/base.py", line 24, in resolve return get_resolver(urlconf).resolve(path) File "/home/madtyn/venvs/corelli/lib/python3.6/site-packages/django/urls/resolvers.py", line 568, in resolve raise Resolver404({'path': path}) django.urls.exceptions.Resolver404: {'path': 'browse/'} My urls are these below. You will notice the i18n url pattern which I believe in some way provoke the described error: config/urls.py: from django.conf import settings from django.urls import include, path from django.conf.urls.static import static from django.contrib import admin … -
Implementing follower system using a many to many field through a model
I am adding a following/follower system and I made it a foreign field in my profile model. The thing is, I want to be able to save multiple information to it like the time when a particular user started following and other future info, so I made the many to many field pass through a model, as shown here: https://docs.djangoproject.com/en/3.0/topics/db/models/#extra-fields-on-many-to-many-relationships Please, I will like to know what I am missing as I am getting AttributeError at /api/opeyemi-odedeyi-ikx5yh/follow/ 'User' object has no attribute 'following' I have tried this: models.py class Profile(models.Model): SEX= ( ('M', 'Male'), ('F', 'Female'), ) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profiles') date_of_birth = models.DateField(blank=True, verbose_name="DOB", null=True) bio = models.TextField(max_length=500, blank=True, null=True) sex = models.CharField(max_length=1, choices=SEX, blank=True, null=True) following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, through='Follow', related_name='followed_by') updated_on = models.DateTimeField(auto_now=True) def __str__(self): return self.user.fullname class Follow(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user_following') profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='profile') date_followed = models.DateField(auto_now_add=True) serializers.py class ProfileDetailedSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField(read_only=True, slug_field='slug') age = serializers.SerializerMethodField(read_only=True) following = serializers.SlugRelatedField(read_only=True, slug_field='slug', many=True) following_count = serializers.SerializerMethodField(read_only=True) user_has_followed = serializers.SerializerMethodField(read_only=True) class Meta: model = Profile fields = "__all__" read_only_fields = ('pk', 'user') def get_age(self, instance): today = date.today() dob = instance.date_of_birth if dob==None: return None return today.year - dob.year - ((today.month, today.day) < … -
Cannot Open Text File To Read Into Django Html
I have followed many of the answers provided here but I still cannot open the file. I have an text file that I would like to render on my home.html. I rewrote my views.py as suggested: def homepage_view(request): module_dir = os.path.dirname(__file__) file_path = os.path.join(module_dir, 'my_text.txt') data_file = open(file_path, 'r') data = data_file.read() context = {'intro' : data} return render(request, 'home.html', context) Here is my home.html. The html includes: from . import forms, from . import views <div class="intro"> {% block intro %} {{block.super }} {{intro}} {% endblock %} </div> My app/urls.py is: from page import views app_name = 'page' urlpatterns = [ path('home/', views.homepage_view, name='homepage_view'), path('upload/', views.csvUpload, name='csv_upload'), path('zip/', views.zipUser_view, name = 'zipUser_view'), path('results/', views.results_view, name='results_view'), path('ky_outline/', views.display_ky_image, name = 'ky_image'), ] My structure is: myproject/ __pycache__ __init__.py settings.py urls.py wsgi.py my/app ('page') __pycache__ migrations static page css style.css images media my_text.txt Static and media files are: STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = [], MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' What am I missing or have I looked at this too long? -
How to pass a value from an onChange event to a Django url template?
It seems like what I would like to do should be a simple thing, but I haven't been able to figure it out. I'm using Django 2.06 with Geodjango. I have a simple UI with a dropdown menu. In order to respond to changes in dropdown selections, I have an event listener for onChange events. The idea is to get the e.target.value from the event and make it the value of a query parameter in a URL. So in index.html I have: const property_name = document.getElementsByName('properties')[0]; property_name.addEventListener('change', (e) => { zones = new L.GeoJSON.AJAX("{% url 'zones' property=e.target.value %}", { ... In urls.py I have: url(r'^zones_data/$', zone_datasets2, name='zones'), and in views.py I have: def zone_datasets2(request): property = request.GET.get('property', '') When I try to load my webpage, the error I get is: NoReverseMatch at / Reverse for 'zones' with keyword arguments '{'property': ''}' not found. 1 pattern(s) tried: ['zones_data/$'] Can someone tell me what I'm doing wrong? How can I pass the dropdown menu selection to the URL and how can I define a url pattern that works with this? Thank you. -
Condition to check uploaded files before displaying them
I've got a simple Django model as described below: class UploadedFile(models.Model): module = models.ForeignKey(Module, on_delete=models.CASCADE, null=False) uploaded_file = models.FileField(upload_to=file_upload_directory, validators=[ValidateUploadFileSize]) and I handle upload of files via a class based view which works fine. When users upload files it successfully gets uploaded to the server directory. When the user accesses the file via an anchor tag, the URL looks something like this http://127.0.0.1:8000/media/444131/module/24.pdf. What I want to know is how do I do some validation before opening the file based on some condition that decides whether to display or not display the file? Let me expand on this. In the URL http://127.0.0.1:8000/media/444131/, 444131 is an ID for an object in the database. I want to be able to check if the current user belongs to that object. If the user exists in that object, then I want to display the file, otherwise, I'd like to do some kind of redirect or not show the file. This is to prevent any random person from being able to brute force the urls or prevent accidental file discovery. I've been thinking of using middlewares but I'm not entirely sure if that is the right way to do it? I've also tried to match … -
Why my testing function in the Django returns status code 404 while in chrome browser the page shows correctly?
I am a Django novice and I am trying to proceed with a simple application testing. One of my tests fails but I cannot find the reason why. I added several prints to clear what was going on. The test function that fails is: def test_board_topics_view_contains_navigation_links(self): board_topics_url = reverse('board_topics', kwargs={'pk': 1}) print("49: board_topic = " + board_topics_url) homepage_url = reverse('home') print("51: homepage_url = " + homepage_url) new_topic_url = reverse('new_topic', kwargs={'pk': 1}) print("53: new_topic_url = " + new_topic_url) response = self.client.get(board_topics_url) print("*****************\n") print(response) print('********************\n') self.assertContains(response, 'href="{0}"'.format(homepage_url)) self.assertContains(response, 'href="{0}"'.format(new_topic_url)) Then I can see the output: Creating test database for alias 'default'... System check identified no issues (0 silenced). .49: board_topic = /boards/1/ 51: homepage_url = / 53: new_topic_url = /boards/1/new/ ***************** <HttpResponseNotFound status_code=404, "text/html"> ******************** It looks like board_topics_url is not working. But in my chrome explorer it works very good and returns a page with both links homepage_url = '/' and new_topic_url = '/boards/1/new/': ... <li class="breadcrumb-item"><a href="/">Boards</a></li> <li class="breadcrumb-item active">Django</li> </ol> <div class="mb-4"> <a href="/boards/1/new/" class="btn btn-primary">New topic</a> </div> ... Both links are working correctly. Please, any idea what could be wrong? Thank you very much for any help. -
Dropdownlist not displayed in Django
I am trying to implement a dropdownlist from my models into an html using Django. The form is working perfectly, but the dropdownlist is not displayed, it only displays "languages:" but not a dropdownlist or any options. Any ideas? add_page.html {% extends 'main/header.html' %} {% block content %} <br> <form method="POST"> {% csrf_token %} {{form.as_p}} <button style="background-color:#F4EB16; color:blue" class="btn btn-outline-info" type="submit">Add Page</button> </form> {% endblock %} forms.py: from django import forms from django.forms import ModelForm from main.models import Pages from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.db import models class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() return user class PagesForm(ModelForm): class Meta: model = Pages fields = ["title","language","content"] models.py from django.db import models from datetime import datetime #from django.forms import ModelForm # Create your models here. LANGUAGE_CHOICES = ( ('english','ENGLISH'), ('spanish', 'SPANISH'), ('german','GERMAN'), ('french','FRENCH'), ('chinese','CHINESE'), ) #Pages son entradas del diario class Pages(models.Model): title = models.CharField(max_length=300) content = models.TextField() author = models.CharField(max_length=50) published_date = models.DateTimeField("Published: ", default=datetime.now()) language = models.CharField(max_length=7, choices=LANGUAGE_CHOICES, default='english') def __str__(self): return self.title Thank you very much in advance and have a good … -
Unresolved function or method carousel()
i have been searching for hours, also tried to get help from here, but couldn't find a solution earlier. Can you please explain to me, why when i implement the js code in django project it raises a problem like Unresolved function or method carousel(). And in the context action it tells: introduce local variable. What should i do?! Please help! $(document).ready(function() { $(".carousel").carousel(); }); .carousel { position: absolute; height: 250px; left:400px; perspective:175px; } .carousel .carousel-item { width: 150px; } .carousel .carousel-item img { width: 100%; border-radius: 10px 10px 0 0; } .carousel .carousel-item h2 { margin: -5px 0 0; background: white; color: red; box-sizing: border-box; padding: 10px 5px; font-weight: bold; font-size: 1em; text-align: center; } {% load static %} <html lang=""> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"/> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <script src="/Main/static/functionality/imageslider.js"></script> <link rel="stylesheet" href="/Main/static/blog/imageslider.css" /> <title></title> </head> <body> <div class="carousel"> <a class="carousel-item" href="#" ><img src="/media/carousel-pics/photo-1454942901704-3c44c11b2ad1.jpg" alt=""> <h2>3D CAROUSEL</h2> </a> <a class="carousel-item" href="#" ><img src="/media/carousel-pics/photo-1454942901704-3c44c11b2ad1.jpg" alt="" /> <h2>3D CAROUSEL</h2> </a> <a class="carousel-item" href="#" ><img src="/media/carousel-pics/photo-1454942901704-3c44c11b2ad1.jpg" alt=""/> <h2>3D CAROUSEL</h2> </a> <a class="carousel-item" href="#" ><img src="/media/carousel-pics/photo-1454942901704-3c44c11b2ad1.jpg" alt=""/> <h2>3D CAROUSEL</h2> </a> </div> </body> </html> -
Effecient way to add default user to model object which is created by other users
My User has 2 objects. 1. admin - super admin 2. tom - user MyModel with class MyModel: project_user = models.ManyToManyField(User) Let's suppose tom is creating a MyModel object: MyModel(project_user=request.user).save() Here I would like to add admin user automatically to the project_user object when someone creates an object. What will the more efficient way to implement it,How about using signals or def save(self)? -
Django registration Type error at /accounts/register/ get_success_url() missing 1 required positional argument: 'user'
Using the Django registration redux plugin to create a form page after a user has successfully registered for my app. However I keep receiving this error TypeError at /accounts/register/ get_success_url() missing 1 required positional argument: 'user' after completing the registration. It should redirect to a page with a form shown in the method below from registration.backends.simple.views import RegistrationView # my new reg view, subclassing RegistrationView from our plugin class MyRegistrationView(RegistrationView): def get_success_url(self, request, user): # the named URL that we want to redirect to after # successful registration return ('registration_create_word') Here is the url path path('accounts/create_word/', views.create_word, name='registration_create_word'), I have attempted changing the parameters to just user however i received the same error except it is missing self. Not sure what I am missing, any help would be greatly appreciated. -
Django Custom Stocks Market Model
i am writing custom models to handle all stocks market transactions from few particular companies. i would be thankful for any idea or help from stack overflow developers. account deposit of a particular user class Portfolio(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) balance = models.IntegerField(default=0) custom companies class Companies(models.Model): name = models.CharField(max_length=120) symbol = models.CharField(max_length=7) total_shares = models.IntegerField() price_earning = models.IntegerField() open = models.IntegerField() last = models.IntegerField() volume = models.IntegerField() date_published = models.DateTimeField() date_term = models.DateTimeField() bulls - buyers class Holdings(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) bought_at = models.IntegerField() num_shares = models.IntegerField() date_published = models.DateTimeField() date_term = models.DateField() bears - sellers, they must have a holding before class Trades(models.Model): holder = models.ForeignKey(Holdings, on_delete=models.CASCADE) trade_at = models.IntegerField() num_shares = models.IntegerField() date_published = models.DateTimeField() i was wondering if you guys can help me complete these models. any idea on how to write on 'open', 'last', and 'volume' columns of a particular company with information of bulls and bears flow in our database diagram. thanks for your time. -
Which are the valid values and directories for django's translation.activate?
To the dreaded stackoverflow community: I'm struggling with this issue for month now: I try to pass a valid language code to translation.activate(language_code) for the following languages: en-us, en-gb, pt-pt, pt-br and zh-hans. I have two configurations: my macbook with gettext 0.20.1 and a debian 10 server with gettext 0.19.8.1-9. For the locale directory I have tried locale/en_gb-style (d_) and locale/en-gb-style paths (d-). For the language_code I tried both en_gb (l_) and en-gb (l-) and en-GB (l-caps) style. The results so far: on my mac: works: d_l-, d_l_, d_l-caps, d-l-caps on my mac: fails: d-l_, d-l- on debian 10: works for zh-hans only: d_l_ on debian 10: fails: d_l-, d-l- Using br instead of pt_br works but it gets picked up as "breton" by rosetta and using gb instead of en_gb does not get picked up at all. What is the solution to this pickle? I use django 2.2. -
Object Detection Django Rest API Deployment on Google Cloud Platform or Google ML Engine
I have developed Django API which accepts images from livefeed camera using in the form of base64 as request. Then, In API this image is converted into numpy arrays to pass to machine learning model i.e object detection using tensorflow object API. Response is simple text of detected objects. I need GPU based cloud instance where i can deploy this application for fast processing to achieve real time results. I have searched a lot but such resource found. I believe google cloud console (instances) can be connected to live API but I am not sure how exactly. Thanks