Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Schedule Function Call for User 9 Days After Last Run Django/Celery
This is in the context of refreshing an access token for a user. Say we have the function refresh_user_token that takes in a CustomUser object as user. def refresh_user_token(user): ... ... return result I'd like for each execution of this function for a specific CustomUser to schedule a repeat in 9 days. def refresh_user_token(user): ... ... next_refresh = datetime.now() + timedelta(days=9) schedule_refresh(user, scheduled_time=next_refresh) return result Most use cases I see for Celery are in regards to performing batch operations, but for this use I need to be able to execute the function with arguments which doesn't seem to be feasible with Celery. -
how to find out if instagram accept the username and password of the bot?
I'm a beginner at Django and Python and now plan to make a simple bot site for Instagram with instabot: https://github.com/instabot-py/instabot.py My problem is how can I find out if Instagram accept the username and password of the user or the username and password is wrong. How can I warn the user? -
How to get multiple objects form the following code which includes get_object_or_404 and get_list_or_404
urls.py urls are working properly from django.urls import path from . import views urlpatterns = [ path('', views.index, name= 'index' ), path('about', views.about, name='about'), path('contact', views.contact, name='contact'), path('<int:id>/', views.course, name="course") ] models.py This is the model I created for my app class Course(models.Model): name = models.CharField(max_length=200,blank=False) description = models.TextField(blank=True) createdby = models.CharField(max_length=200,blank=False) ratings = models.DecimalField(max_digits=2, decimal_places=1) image = models.CharField(max_length=244,blank=True) is_bestseller = models.BooleanField(default=False) is_highestrated = models.BooleanField(default=False) department = models.ForeignKey('Department', on_delete = models.DO_NOTHING) def __str__(self): return self.name class TableContent(models.Model): c = models.ForeignKey('Course', on_delete = models.CASCADE) title = models.CharField(max_length=200,blank=False) lecture = models.CharField(max_length=200,blank=False) lecturelink = models.TextField(blank=False) def __str__(self): return str(self.c) views.py Want to correct my views.py in function course from django.shortcuts import render, get_object_or_404, get_list_or_404 from .models import * def index(request): courses = Course.objects.all() context= { 'courses': courses } return render(request, 'pixma/index.html', context) def course(request, id): course = get_object_or_404(Course, pk= id) tablecontent= TableContent.objects.filter(c__id=id) #tablecontent= get_list_or_404(TableContent, c__id=id) not helping context = { 'course': course, 'tablecontent' : tablecontent } return render(request, 'pixma/course.html', context) In return I want all the table content with the particular course id from TableContent -
Django " Static files are not found "
Static files are not shown up also it gives me error idk why is this error comes up please help me March 29, 2019 - 16:06:30 Django version 2.1.7, using settings 'aurora.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Not Found: / [29/Mar/2019 16:06:38] "GET / HTTP/1.1" 404 2026 Not Found: /favicon.ico [29/Mar/2019 16:06:39] "GET /favicon.ico HTTP/1.1" 404 2077 [29/Mar/2019 16:06:42] "GET /sign HTTP/1.1" 301 0 [29/Mar/2019 16:06:42] "GET /sign/ HTTP/1.1" 200 3448 Not Found: /sign/img/index.png [29/Mar/2019 16:06:42] "GET /sign/img/index.png HTTP/1.1" 404 2340 Not Found: /sign/static/css/bootstrap.min.css [29/Mar/2019 16:06:42] "GET /sign/static/css/bootstrap.min.css HTTP/1.1" 404 1833 Not Found: /sign/static/css/all.min.css Not Found: /sign/static/css/style.css [29/Mar/2019 16:06:42] "GET /sign/static/css/all.min.css HTTP/1.1" 404 1815 [29/Mar/2019 16:06:42] "GET /sign/static/css/style.css HTTP/1.1" 404 1809 html file <html> {% csrf_token %} <head> {% load staticfiles %} <link rel="stylesheet" href="{% static "css/all.min.css" %}"> <link rel="stylesheet" href="{% static "css/bootstrap.min.css" %}"> <link rel="stylesheet" href="{% static "css/style.css" %}"> </head> <body> ================== directories sign \ templates \ file.html static \ style.css otherfiles.css ha /?????????????????? what to do ? -
Default user in django (sentinel value)
I have a model: class NotificationSettings(models.Model): android_device = models.ForeignKey( 'users.AndroidDevice', default=None, null=True, blank=True, on_delete=models.SET_NULL ) user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True) ... class Meta: unique_together = ("user", "android_device") My problem is that I have unique_together on fields that are nullable. I learned that in PostgreSQL (and generally in the SQL standard) NULL != NULL, so I can end up with, for example, two NotificationSettings objects that have the same device_id and user is NULL in both cases. I thought that using NotificationSettings.objects.get_or_create() everywhere I create these objects would suffice but I guess there is a race condition when two request are hitting the endpoint in almost the same time, and I end up with duplicates anyway. This is why I wanted to make this constraint on the PostgreSQL level and was thinking about changing the user field to not being nullable and having default user instead. But I feel like creating default user might have some kind of security consequences. So my question is: Is this a good practice (or practice at all) to create such a sentinel/default user object? Are there any caveats/security risks? -
Correct way to test if a User model has a password
I have this models from django.db import models from django.contrib.auth.models import AbstractUser class Account(AbstractUser): last_updated = models.DateTimeField(default=datetime.now, blank=False, null=False) class User(Account): security_question = models.TextField(blank=True) security_answer = models.CharField(max_length=50, blank=True) and this simple test case: from django import test from myapp import models class UserTestCase(test.TestCase): def test_user_password_cannot_be_empty(self): def create_user_without_password(): models.User.objects.create( username='usr2', first_name='Name', last_name='Name2', email='me@email.com' ) # should throw an error self.assertRaises( Exception, create_user_without_password ) The test should pass as password is a mandatory field, yet by running python manage.py test --pattern="tests_*.py" I get ====================================================================== FAIL: test_user_password_cannot_be_empty (myapp.tests_user_testcase.UserTestCase) AssertionError: Exception not raised by create_user_without_password I guess I'm testing it wrongly. What is the correct way? Specs: Python 3.6.1 Django 2.1.1 Windows 10 -
Why are form widgets hidden for ForeignKey, ManyToManyField, BooleanField, and CharField with Choices?
I'm using a generic.edit.Updateview to dynamically generate a form for my model instances. Most of the fields are loaded correctly, however ForeignKeys, Many to Many fields, BooleanFields, and CharFields using choices are not visible. The labels are properly displayed, and inspecting the page html shows select elements with the proper values but the widget itself is not present. models.py from django.db import models from django.urls import reverse from django.conf import settings class Staff(models.Model): is_lead = models.BooleanField(default=False) first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) phone_number = models.CharField(max_length=11, blank=True, null=True) email = models.EmailField(max_length=128, blank=True, null=True) def __str__(self): return self.first_name + ' ' + self.last_name def get_absolute_url(self): return reverse("momentum:Staff-update", kwargs={'pk':self.pk}) class Client(models.Model): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) phone_number = models.CharField(max_length=11, blank=True) email = models.EmailField(max_length=128, blank=True) def __str__(self): return self.first_name + ' ' + self.last_name def get_absolute_url(self): return reverse('momentum:Client-update', kwargs={'pk':self.pk}) class Event(models.Model): inquiry = 'INQ' confirmed = 'CNF' completed = 'COM' STATUS_CHOICES = ( (inquiry, 'INQ'), (confirmed, 'CNF'), (completed, 'COM'), ) client = models.ForeignKey( 'Client', on_delete=models.SET_NULL, null=True, ) status = models.CharField( max_length=3, choices=STATUS_CHOICES, default=inquiry, ) guest_count = models.IntegerField(blank=True, null=True) name = models.CharField(max_length=128) start = models.DateTimeField(blank=True, null=True) location = models.CharField(max_length=128, blank=True) lead = models.ForeignKey( 'Staff', on_delete=models.SET_NULL, limit_choices_to={'is_lead':True}, null=True, related_name='Lead', ) staff = models.ManyToManyField( 'Staff', related_name='EventStaff' … -
Detecting whether multiple browsers/tabs are opened with django
I am developing web pages that I need that won't be opened in more then one browser/browser tab. Only one tab in one browser for one client. I know that it is possible in the modern web, because I see that websites like Netflix does that. What is the required setup for this? Can this be done with bare django? -
Generic way to add field to 'readonly_fields' and and 'fields' Djnago admin with decorator or Mixin
I want to have some generic way to append str to fields ('fields', 'readonlu_fileds') to the django admin the ideal way is Mixin or the decorator. Can I do that? When I tried some ways I had recussion or errors. def distributed_admin(wrapped): class WrappedClass(wrapped): def get_fields(self, request, obj=None): fields = WrappedClass.get_fields(request, obj) fields.append('id_to_str') return fields return WrappedClass -
Encrypting database fields with user's password
I run a server with multiple users, Each user has its own username and password, and other personal data. I would like to encrypt each user's data with his own password (Yes, it means that if he had forgotten his password all the data is lost forever). After googling around I have not found such solution which satisfies this requirement. I'd be grateful if someone can point me to a solution. -
django get distinct object from many to many
I have following models : class Account(AbstractBaseUser): username = models.CharField(max_length=40, unique=True) name = models.CharField(max_length=200, null=True) is_admin = models.BooleanField(default=False) is_hiren = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) USERNAME_FIELD = 'username' objects = AccountManager() class Company(models.Model): admin = models.ForeignKey(Account, on_delete=models.PROTECT, null=True) name = models.CharField(max_length=100) class CompanyDetails(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) employee = models.ManyToManyField(Account, related_name='employee') admin = models.ForeignKey(Account, on_delete=models.PROTECT, null=True) Suppose I have 7 account objects , one admin and six manager (or employee) . Admin has multiple company and five manager are assigned in those companies. Single manager account can assigned to multiple company. Now my problem is, how can I get all 5 unique employee account objects ? here is what I tried : @login_required def employee_list(request): employees = get_list_or_404(CompanyDetails, admin=request.user) print(CompanyDetails.objects.filter(employee__in=Account.objects.all()).distinct()) -
How to: prefetchable related name with implicit filter
It is understood that foreign keys can have related_names, like this: class Foo(Model): ... class Bar(Model): foo = ForeignKey(Foo, related_name='bars') hidden = BooleanField() The effect is foo = Foo.objects.first(); foo.bars.all() yields any Bars attached to that Foo. However, I want to add a default filter to all .bars.all(), such that Bars that are marked as "hidden" are never part of the resulting queryset. It is tempting to do: class Foo(Model): ... @property def shown_bars(self): return self.bars.filter(hidden=False) and just use foo.shown_bars instead of foo.bars, but my objective is to make such a related_name nested-prefetchable as well, i.e. class Baz(Model): foo = ForeignKey(Foo) # The bars in this queryset *also* automatically excludes bars that are hidden Baz.objects.prefetch_related('foo__bars') So nested_bars cannot be used directly in such expressions. Is there a way to achieve this in Django 1.11 or 2.x? -
How to handle in django user going back after payment confirmation?
After payment confirmation, I can go back to payment page and view the details on what user entered. This should not happen Tried using java script to disable back button but read few recommendations saying its not a good practice to stop user going back. Not sure if there are any decorators like @login_required in django. How can I force user to see home page even if back button is click on browser after payment confirmation? Does django provide any decorator for the same? -
Errors after recreating venv outside of Django project
I recently deleted my venv from within a django project root folder, to recreate it outside of the root folder. Since then I observed some inconsistencies when running python manage.py commands, which I assume might be connected to this venv "reset". For example, I have no issues running: python manage.py runserver python manage.py makemigrations my_app But when I run e.g. python manage.py migrate my_app --database my_db I get: Migrations for 'my_app': my_app/migrations/0007_auto_20190329_1417.py - Alter field description on subtask (my-venv) [myname@myname-VirtualBox myproject](develop)$ python manage.py migrate my_app --database my_db /home/myname/dj-workspace/my-venv/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Operations to perform: Apply all migrations: my_app Running migrations: Applying my_app.0007_auto_20190329_1417... OK Traceback (most recent call last): File "/home/myname/dj-workspace/my-venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column django_content_type.name does not exist LINE 1: SELECT "django_content_type"."id", "django_content_type"."na... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "/home/myname/dj-workspace/my-venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/myname/dj-workspace/my-venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/myname/dj-workspace/my-venv/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) … -
How We use prefetch_related in 2 level of many to many fields
I am using many to many filed and i used a prefech_related to optimize query I want a users mail id of all child company. how can achieve this code: class AuthUser(AbstractBaseUser, PermissionsMixin): user_code = models.CharField(max_length=10, unique=True) user_type = models.ForeignKey(UserTypes, on_delete=models.SET_NULL, null=True) address = models.CharField(max_length=100, null=True) email = models.EmailField(max_length=100, null=False) class Company(models.Model): company_name = models.CharField(max_length=100, null=False, unique=True) company_short_name = models.CharField(max_length=100, null=True, blank=True) company_type = models.CharField(max_length=1, choices=company_type, default="T") child_company = models.ManyToManyField('self', blank=True) users = models.ManyToManyField(AuthUser, blank=True) I tried user_data = Company.objects.filter(id=1).prefetch_related('child_company', 'child_company__users') -
View does not seem to be saving all the information in my model
I have a model and a view for saving books. However when i access the information it does not appear to be complete. All queries seem to be running properly. Am at a loss what could be going wrong my model class Book(models.Model): title = models.CharField(max_length=50) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE,) cover_pic = models.FileField(null=True, blank=True) author = models.CharField(max_length=100, blank=True) description = models.TextField(max_length=1000) uploaded_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("books:addBook") class Meta: ordering = ["-uploaded_on"] My views.py class addBook(FormUserNeededMixin, CreateView): form_class = BookForm success_url = reverse_lazy('addbook') template_name = 'books/addbook.html' forms.py class BookForm(forms.ModelForm): class Meta: model = Book exclude = ['user', 'uploaded_on'] am trying to access the details using this view class BookListView(ListView): model = Book template_name = 'books/viewbooks.html' and this template {% for books in object_list %} <img src="{{ book.cover_pic }}"> <h5>{{ book.title }}</h5> <p>{{ book.author }}</p> {% endfor %} everytime i add an item i can see another list item added in view books but has none of the details that i requested. -
Using forms with django-translated-fields
Please take a look at this issue: How do I use ModelForm with django-translated-fields? Do you have any solution? In short, I'm trying to convert Speedy Net from using django-modeltranslation to django-translated-fields. I defined the models and forms and everything works in English, but in another language (Hebrew) I have a problem that the form fields are defined in English instead of Hebrew (the current language). What did I do wrong and how do I define the form to work in the current language? (the fields defined by TranslatedField in the model should be visible only with the current language in the form SpeedyMatchProfileActivationForm). I want to clarify that the desired definition is not as above. The desired definition is to use the current language in the form and not always English. Using English when the current language is not English is a bug. You can see the code here: tree forms.py models.py The problem right now is with the class SpeedyMatchProfileActivationForm (defined in forms.py). I think it is mainly because the class is defined before get_language() returns anything. But when the class was defined with django-modeltranslation (for example in branch staging), it worked. By the way, one of the … -
I am trying to implement a code from codepen but it is not happening
The following is the code for html, javascript, css,urls.py,views.py please help me out because, the animation i want from code pen is not working. Ive copy pasted the exact same code,still it wont work. base.html <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="{% static 'clubapp/css/master.css'%}"> </head> <body class="text-center"> <div id="page"> <div class="cover-container d-flex h-100 p-3 mx-auto flex-column"> <header class="masthead mb-auto"> <div class="inner"> <h3 class="masthead-brand">Reveal #1</h3> <nav class="nav nav-masthead justify-content-center"> <a class="nav-link active" href="#">Home</a> <a class="nav-link" href="https://codepen.io/soju22/" target="_blank">Codepen Profile</a> <a class="nav-link" href="https://codepen.io/collection/AGZywR" target="_blank">ThreeJS Collection</a> </nav> </div> </header> <main role="main" class="inner cover"> <h1 class="cover-heading">Simple 3D Reveal Effect</h1> <p class="lead">This simple effect is made with ThreeJS and TweenMax.</p> <p class="lead"> <a href="#" id="trigger" class="btn btn-lg btn-secondary">Trigger</a> </p> </main> <footer class="mastfoot mt-auto"> <div class="inner"> <p></p> </div> </footer> </div> </div> <canvas id="reveal-effect"></canvas> <script src="{% static "clubapp/js/master.js"%}" type="text/javascript"></script> </body> </html> views.py from django.shortcuts import render from django.urls import reverse from django.http import HttpResponseRedirect from django.views.generic import TemplateView def index(request): return render(request,'clubapp/base.html') urls.py from django.contrib import admin from django.urls import path from clubapp import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index,name='index') ] css a, a:focus, a:hover { color: #fff; } .btn-secondary, .btn-secondary:hover, .btn-secondary:focus { color: #333; text-shadow: none; background-color: … -
How to pass context data from 2 models in a template?
I have 2 models tied by a ForeignKey Model1:(secondary) fk= ForeignKey(model2) image = imagefield() Model2:(primary) ….some fields here I need to pass context of the Model1 into the template. I have written some code: def someview(request, id): # id from “path("AAA/BBB/<int:id>/” a = Model2.objects.get(pk=id) # primary model context data b = a.modelel1_set.all() # secondary model context data context = {"a": a, "b": b} return render(request, "some.html", context) in template context data “a” is accessible but context data “b” is not, although "b" is accessible as a query-set but empty. What’s wrong with this code or am I just stupid or both? If you have an answer please also specify where I can read about it cos I have been trying to fix it for a 3 days already. tried to add context processser. Does not work def some_context_processor(request): context = {} context["bi"] = Model1.objects.all() return context Pass context data "b" in the template -
Why does Django upvote increases the vote of latest added item only?
There is an upvote button in every item. but when I click it, it increases the upvote of the latest added item only. <a href="javascript:{document.getElementById('upvote').submit() }"> <button class="btn btn-success d-block w-100 mt-4"><span class="pull-left">UPVOTE <i class="fa fa-thumbs-o-up"></i> </span> <span class="pull-right"> {{product.upvote}} </span> </button> </a> <form action="{% url 'upvote' product.id %}" method="POST" id="upvote"> {% csrf_token %} <input type="hidden" name="upvote"> </form> from django.urls import path from myApp import views urlpatterns = [ path('', views.HomePageView.as_view(),name='home'), path('<int:product_id>/upvote',views.Upvote,name='upvote'), ] def Upvote(request, product_id): if request.method == 'POST': product = get_object_or_404(Product, pk=product_id) product.upvote += 1 product.save() return redirect('home') -
How do I write a view.py for my model.py file
I'm working on an incoming webhook using Djangorestframework. I have to write a view for my model. I just want to check if I'm going right or not? Refer this for more information class WebhookTransaction(models.Model): UNPROCESSED = 1 PROCESSED = 2 ERROR = 3 STATUSES = ( (UNPROCESSED, 'Unprocessed'), (PROCESSED, 'Processed'), (ERROR, 'Error'), ) date_generated = models.DateTimeField() date_received = models.DateTimeField(default=timezone.now) body = hstore.SerializedDictionaryField() request_meta = hstore.SerializedDictionaryField() status = models.CharField(max_length=250, choices=STATUSES, default=UNPROCESSED) objects = hstore.HStoreManager() def __unicode__(self): return u'{0}'.format(self.date_event_generated) class Message(models.Model): date_processed = models.DateTimeField(default=timezone.now) webhook_transaction = models.OneToOneField(WebhookTransaction) team_id = models.CharField(max_length=250) team_domain = models.CharField(max_length=250) channel_id = models.CharField(max_length=250) channel_name = models.CharField(max_length=250) user_id = models.CharField(max_length=250) user_name = models.CharField(max_length=250) text = models.TextField() trigger_word = models.CharField(max_length=250) def __unicode__(self): return u'{}'.format(self.user_name) This is my model for the problem. After this I have tried to write view for this Here is my code def DRSWebhookTransactionView(request): if request.method == 'GET': webhooktransaction = WebhookTransaction.objects.all() serializer = WebhookTransactionSerializer(webhooktransaction, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = WebhookTransactionSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) def DRSMessageView(request): if request.method == 'GET': message = Message.objects.all() serializer = MessageSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = MessageSerializer(data=data) if serializer.is_valid(): serializer.save() return … -
I am getting invalid keyword argument while posting product array in customer order. What should i do?
First i was getting an error like to create an explicit create method while serializing an array of product. So i added it but stiil im getting thhis error : TypeError: 'customerorder' is an invalid keyword argument for this function This is my serializers.py class ProductSerializer(serializers.ModelSerializer): product_id = serializers.IntegerField(required=False) class Meta: model = Product fields = '__all__' class CustOrderSerializer(serializers.ModelSerializer): price = serializers.SlugRelatedField(slug_field='price', queryset=Price.objects.all()) # product = serializers.SlugRelatedField(slug_field='product', queryset=Product.objects.all()) area = serializers.SlugRelatedField(slug_field='address', queryset=Area.objects.all()) city = serializers.SlugRelatedField(slug_field='city', queryset=City.objects.all()) product = ProductSerializer(many=True) class Meta: model = CustOrder fields = '__all__' def create(self, validated_data): product = validated_data.pop('product') customerorder = CustOrder.objects.create(**validated_data) for product in product: Product.objects.create(**product, customerorder= customerorder) return customerorder This is models.py class Product(models.Model): product_id = models.AutoField(primary_key=True) product = ArrayField(models.CharField(max_length=200, blank=True)) def str(self): return str(self.product) class CustOrder(models.Model): Customer_id = models.AutoField(primary_key=True) CustomerName = models.CharField(max_length=200) email = models.EmailField(max_length=70,blank=True, null= True, unique= True) gender = models.CharField(max_length=6, choices=GENDER_CHOICES) phone = PhoneField(null=False, blank=True, unique=True) landmark = models.PointField() #landmark = models.TextField(max_length=400, help_text="Enter the landmark", default='Enter landmark') houseno = models.IntegerField(default=0) #product_name = models.CharField(max_length=200, choices=PRODUCT_CHOICES,default='Boneless chicken') # product_id = models.ForeignKey(Product, on_delete=models.CASCADE,related_name='custorder_productid') product = models.ManyToManyField(Product, blank=True,related_name='pricetag') quantity = models.IntegerField(default=0) # price_id = models.ForeignKey(Price) price = models.ForeignKey(Price, on_delete=models.SET_NULL, null=True,related_name='pricetag') #price = models.DecimalField(max_digits=50, decimal_places=5, default=48.9) pay_method = models.CharField(max_length=200,choices=PAYMENT_CHOICES, default='RAZOR PAY') city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) … -
Fat Model Skinny View: where should I put the related code
I'm still new to Django and am trying to understand and implement the "fat model, skinny view" pattern. It makes sense to me that a model should be self contained for re-usability though I don't currently see the use case for this particular model. The model is a virtual machine for one of many cloud vendors. I have a polymorphic base model, VirtualMachine which defines all the fields. I also have a specific model, VirtualMachineVendor which implements the vendor specific control function for VirtualMachine. Examples would be vm_create() or vm_delete that handle the model creation or deletion as well as the management of the cloud resource. The view mainly processes the request and sends that to the correct model method and preparing data for the template. I want to add functionality for creating a domain record. Question: Should the VirtualMachine model call this domain creation method or should this be something the View calls? In general, should a model be calling other model methods within the same or different app, or should the model return control back to the view after a call? -
Sync Postgress sql with elasticsearch- djnago python
I am trying to sync my local database with elasticsearch. I am following this tuturials, https://www.codementor.io/samueljames/using-django-with-elasticsearch-logstash-and-kibana-elk-stack-9l4fwx138 and https://github.com/barseghyanartur/django-elasticsearch-dsl-drf/blob/master/docs/quick_start.rst My setting.py goes like this, INSTALLED_APPS = [ # .... 'django_elasticsearch_dsl', ] LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'null': { 'level': LogLevel, 'class': 'logging.NullHandler', }, 'console': { 'level': LogLevel, 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'log_file': { }, }, 'loggers': { 'django': { 'handlers': ['log_file'], 'level': LogLevel, 'propagate': True, }, }, 'root': { 'handlers': ['console', 'log_file'], 'level': LogLevel } } ELASTICSEARCH_DSL = { 'default': { 'hosts': 'localhost:9200' }, } ELASTICSEARCH_INDEX_NAMES = { 'search_indexes.documents.books': 'books', } I am using, ./manage.py search_index --rebuild to create index and ./manage.py search_index --populate -f to sync data. However this fails to sync my elasticsearch with postgress sql. -
Cannot assign : must be a instance Django foreign Key error
I have created a model and connected a foreign key with it, but when I save them I get an error Cannot assign "1": "SupplierBidModel.Load_ID" must be a "ShipperBoardModel" instance. I am fairly new to Django, and even newer to Django interconnected models concept. Any idea why this is happening ?? I have no idea where to go from here as there are not many questions such as this on Google either. My models.py class ShipperBoardModel(models.Model): # Manufaturer_ID Rahul1 = models.AutoField(primary_key=True) From = models.CharField(max_length=100,null=True) To = models.CharField(max_length=100,null=True) Type = models.CharField(max_length=100,null=True) Length = models.CharField(max_length=100,null=True) Weight = models.CharField(max_length=100,null=True) Numberoftrucks = models.IntegerField(null=True) MaterialType = models.CharField(null=True,max_length=100) Loadingtime = models.DateTimeField(null=True) # Loadkey = models.ForeignKey() def _str_(self): return self.Origin # class SupplierBidModel(models.Model): BidID = models.AutoField(primary_key=True) Load_ID = models.ForeignKey(ShipperBoardModel,on_delete=models.CASCADE,default=3) Supplier_ID = models.ForeignKey(SupplierBoardModel,on_delete=models.CASCADE,default=3) Bid_amount = models.IntegerField(null=True) class Meta: unique_together = ('Load_ID', 'Supplier_ID') Views.py def suppliertablefun (request): # function to display shipperboardmodel data = ShipperBoardModel.objects.all() if request.method == 'POST': forminput = BiddingForm(request.POST) if forminput.is_valid(): forminput.save() forminput = BiddingForm(request.POST) return render(request, 'supplierboard/board.html', locals(), {'forminput': forminput})