Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get Django to send error emails on status codes above 500?
I have migrated an old codebase to a new server and am now running Django 4.0.5. I can send emails from the shell as follows: from django.core.mail import mail_admins mail_admins(subject='test', message='test') But I don't receive any emails on 500 or higher errors. My settings are: DEBUG = env('DEBUG') ADMINS = [('My Name', 'me@provider.com'),] MANAGERS = ADMINS ADMIN_EMAIL = ['me@provider.com',] DEFAULT_FROM_EMAIL = 'admin@provider.com' SERVER_EMAIL = 'admin@provider.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'admin@provider.com' EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') EMAIL_USE_TLS = True And i have tried adding: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' But they are still not sent. I am using django-environ, but debug is set to false. Any ideas what the problem could be? -
Django celery error while adding tasks to RabbitMQ message queue : AttributeError: 'ChannelPromise' object has no attribute '__value__'
I have setup celery, rabbitmq and django web server on digitalocean. RabbitMQ runs on another server where my Django app is not running. When I am trying to add the tasks to the queue using delay I am getting an error AttributeError: 'ChannelPromise' object has no attribute 'value' From django shell I am adding the task to my message queue. python3 manage.py shell Python 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from app1.tasks import add >>> add.delay(5, 6) But getting error Traceback (most recent call last): File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/utils/functional.py", line 30, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/connection.py", line 446, in _reraise_as_library_errors yield File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/connection.py", line 433, in _ensure_connection return retry_over_time( File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/utils/functional.py", line 312, in retry_over_time return fun(*args, **kwargs) File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/connection.py", line 877, in _connection_factory self._connection = self._establish_connection() File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/connection.py", line 812, in _establish_connection conn = self.transport.establish_connection() File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection conn.connect() File "/etc/myprojectenv/lib/python3.8/site-packages/amqp/connection.py", line 323, in connect self.transport.connect() File "/etc/myprojectenv/lib/python3.8/site-packages/amqp/transport.py", line 129, in connect self._connect(self.host, self.port, self.connect_timeout) File "/etc/myprojectenv/lib/python3.8/site-packages/amqp/transport.py", line 184, in _connect … -
Django: create many-to-Many relationship without creating intermediary table
I have a set of tables that Ive turned into django models. The tables weren't architected very well and i can't change them, and it is causing problems for this one many to many relationship I'm trying to set up in my code. Models class Owner(models.Model): owner_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True) # Field name made lowercase. email = models.TextField(max_length=200, unique=True) is_active = models.BooleanField( blank=True, null=True) # Field name made lowercase. owned_apps_whistic = models.ManyToManyField("Applications", through="ApplicationOwnerXRef", related_name="owners_whistic") #owned_apps_group = models.ManyToManyField("Applications", through="BusinessUnitOwnerXref", related_name="owners_group") class Applications(models.Model): application_id = models.UUIDField(primary_key=True) url = models.TextField(blank=True, null=True) name = models.TextField(blank=True, null=True) service = models.TextField(blank=True, null=True) status = models.TextField(blank=True, null=True) created_date = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) business_unit_name = models.TextField(blank=True, null=True) class BusinessUnitOwnerXref(models.Model): id = models.AutoField(primary_key=True) owner_uuid = models.ForeignKey(ApplicationOwner, models.DO_NOTHING, to_field="owner_uuid", db_column = "owner_uuid") business_unit_name = models.TextField(max_length=100, null=True) Owners can own applications by owning the group that owns the application, indicated in the BusinessUnitOwnerXref table. The Application table and the BusinessUnitOwnerXref both have the business_unit_name column , and can be directly joined I cant use a foreign key because the BusinessUnitOwnerXref.business_unit_name column isn't unique. TLDR, Is there a way to create the many-to-many relationship between Applications and Owners, through BusinessUnitOwnerXref, without altering the existing tables or letting django … -
How to install python packages on shared host
When I upload my Django app, I have problem when I setup the python app configuration files. After adding requirements.txt gives me an error these libraries are not accepted: matplotlib==3.5.1 pandas==1.3.5 Pillow==9.0.0 psycopg2==2.9.1 scipy==1.7.3 seaborn==0.11.2 Is there a solution? -
"Bot domain invalid" error in web telegram login. Django
When integrating the login via telegram for Django, I received the following error (despite the fact that all actions were done correctly) Bot domain invalid error I've been tinkering with this for a couple of days and just want to share a solution. The solution is simple and pretty funny. Just remove "django.middleware.security.SecurityMiddleware" from MIDDLEWARE -
getting dynamic data from views to javascript
Just like we can set a context variable for the default users in a django template, var user = "{{request.user}}" How do I do the same thing for a custom Model? views def test(request): news = News.objects.all() context = {"news ": news} template <script> var text = "{{request.news}}"; </script> -
Is it possible to take in input from django, and output that to a word document using python docx
I want to take in user input through text boxes on websites created with Django. After gathering the user input I want to automatically generate a word document with the inputs, and output a word document. Is this possible? -
django error : 'the current database router prevents this relation.'
I have 2 models(customer, order) in 2 different sqlite3 databases(custdb and orddb) apart from the default database. Settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'custdb': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'custdb.sqlite3', }, 'orddb': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'orddb.sqlite3', } } DATABASE_ROUTERS = ['customer.router.custrouter', 'order.router.ordrouter'] Under 'customer' App, in the models.py, below customer model class is defined(only class definition shown here) class customer(models.Model): name = models.CharField(max_length=50) phone = models.IntegerField() Under order App, in the models.py, below order model is defined(only class definition shown here) class order(models.Model): ordername = models.CharField(max_length=50) customer = models.ForeignKey(cust, default=None, null=True, on_delete = models.SET_NULL) Under 'customer' App, in the router.py, I have defined one router class class custrouter: route_app_labels = {'customer'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'custdb' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'custdb' return None def allow_relations(self, obj1, obj2, **hints): if ( obj1.meta.app_label in self.route_app_labels or obj2.meta.app_label in self.route_app_labels ): return True return True def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'custdb' return None Under 'order' App, in the router.py, I have defined another router class class ordrouter: route_app_labels = {'order', 'customer'} def … -
Django service only works when the image is deleted and pulled again (in Swarm)
I have a swarm cluster with 2 workers and one manager. I built a Django image, pushed it to Docker Hub. I make migrations before pushing the image so it contains them. I pull the image for it to be used for the Swarm services, using docker-compose, I deploy the stack, everything works. But if I remove the stack and try to start it again from the old image (which should be immutable) i get psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known. If I delete the image and just run the stack again (so basically I get the same image from Docker Hub) the service is deployed without any errors. So i cant delete the stack and use the same image to deploy it again.. My compose is: version: "3.3" services: web: image: x command: > bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" env_file: - .env.dev volumes: - migrations-volume:/stack_name/api/migrations/ deploy: replicas: 3 restart_policy: condition: on-failure networks: - web_network - data_network secrets: - firebase_secret - google_cloud_secret healthcheck: test: wget --tries=1 --spider http://localhost:8000/app/ || exit 1 interval: 180s retries: 5 timeout: 10s db: image: postgres:11 command: "-c logging_collector=on" volumes: - database:/var/lib/postgresql/database/ env_file: … -
Django How to make a chat app without django-channrls
Hello how can I make a chat app without django-channels. I want to do it with something like socketio. I found in Google a module named django-socketio. Should I do it with this? Please write me the code to do this or write a link of a tutorial. -
Django REST Framework: Strange behaviour in unit tests
Good evening, at the moment I'm creating the unit tests for a pretty basic model in combination with the authentification of a json web token. Also I'm using a custom user model. Notice: a few lines of code will be cut off for a better overview - there unimportant for my question. models.py: USER = get_user_model() class MainTask(models.Model): id = models.BigAutoField(primary_key=True, unique=True) title = models.CharField(max_length=50, null=False, blank=False, unique=True) active = models.BooleanField(default=True) slug = models.SlugField(null=False, blank=False, unique=True) created_by = models.ForeignKey(USER, null=False, blank=False, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py: class MainTaskListCreateView(ListCreateAPIView): queryset = MainTask.objects.all() serializer_class = MainTaskSerializer pagination_class = PageNumberPagination urls.py: urlpatterns = [ path('maintask/', MainTaskListCreateView.as_view(), name='maintask-list'), path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), ] settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser', 'rest_framework.permissions.IsAuthenticated', ], } test_views.py: USER = get_user_model() class MainTaskTest(APITestCase): url_verification = reverse('token_obtain_pair') url_maintasks = reverse('maintask-list') def setUp(self): self.email = 'johndoe@email.com' self.password = 'johndoepassword' self.data = { 'email': self.email, 'password': self.password } USER.objects.create_user(email=self.email, password=self.password) def test_auth_user(self): response = self.client.post(self.url_verification, self.data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue('access' in response.data) self.assertTrue('refresh' in response.data) def test_get_obj(self): response_verification = self.client.post(self.url_verification, self.data, format='json') token = response_verification.data['access'] self.client.credentials(HTTP_AUTHORIZATION=f"JWT {token}") response = self.client.get(self.url_maintasks, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertNotEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) self.assertNotEqual(response.status_code, status.HTTP_403_FORBIDDEN) Problem: When running the test above, I get an error 403, the … -
TwilloRestfullException on inbound call in django_two_factor_auth
I am using django_two_factor_auth version 1.13.1 with python 3.6, and when I try to get OTP via phone call it returns TwilloRestfullExeption on URL. HTTP 400 error: Unable to create a record: Url is not a valid URL: http://localhost:8000/twilio/inbound/two_factor/206039/?locale=en in my URLS.py I have added the URLs paths url('', include(tf_urls)), url('', include(tf_twilio_urls)), one more thing when I try to hit that URL via postman or web browser I got 200 success response <?xml version="1.0" encoding="UTF-8" ?> <Response> <Say language="en">Your token is 1. 7. 3. 8. 4. 7. Repeat: 1. 7. 3. 8. 4. 7. Good bye.</Say> </Response> -
wagtail api : my pages dont appear in /api/cms/pages/
I ve configured my wagtail to use the api and to serve the pages on /api/cms/pages/ endpoint. But I only have the default page being served on this endpoint : "meta": { "total_count": 1 }, "items": [ { "id": 2, "meta": { "type": "wagtailcore.Page", "detail_url": "http://localhost/api/cms/pages/2/", "html_url": "http://localhost/", "slug": "home", "first_published_at": null }, "title": "Welcome to your new Wagtail site!" } ] } I have created a few BlogPages and PostPages but they dont appear there. How can i configure my django/wagtail files so they appear? The documentation here : https://docs.wagtail.org/en/stable/advanced_topics/api/v2/usage.html is not very detailed... Here is my models.py : import urllib.parse from django.http.response import JsonResponse, HttpResponseRedirect from django.conf import settings from django.db import models from django.utils.module_loading import import_string from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from modelcluster.fields import ParentalKey from modelcluster.tags import ClusterTaggableManager from taggit.models import Tag as TaggitTag from taggit.models import TaggedItemBase from wagtail.admin.edit_handlers import ( FieldPanel, FieldRowPanel, InlinePanel, MultiFieldPanel, PageChooserPanel, StreamFieldPanel, ) from wagtail.core.models import Page from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.snippets.edit_handlers import SnippetChooserPanel from wagtail.snippets.models import register_snippet from wagtail.core.fields import StreamField from wagtail.contrib.routable_page.models import RoutablePageMixin, route from wagtail.search import index from wagtail_headless_preview.models import HeadlessPreviewMixin from .blocks import BodyBlock from wagtail.api import APIField from .fields import TagField, CategoryField, … -
{detail: Unsupported media type "text/plain; charset=utf-8" in request.}
I am using Flutter and Django and have this error when try to call the backend Back end error : {detail: Unsupported media type "text/plain; charset=utf-8" in request.} Flutter code : Future<void> addAlbum(Album album) async { print('5'); final url = Uri.parse('http://127.0.0.1:8000/list-create/'); try { print('6'); final response = await http.post(url, headers: { 'Authorization': 'Token dc7e96ed776bc44d013b44fdfe560a616c64646f', }, body: json.encode({ 'title': album.title, 'cover': album.cover, // => this is an int 'photos_number': album.photos_number, // => this is an int })); print('6 ed'); final responseData = json.decode(response.body); print(responseData.toString()); final newAlbum = Album( title: album.title, cover: album.cover, photos_number: album.photos_number, ); print('6 edddgg'); _items.add(newAlbum); print('6 f'); notifyListeners(); } catch (error) { print('7'); print(error); throw error; } } } -
Django API call from extern Website via AJAX Javascript
i am working for the first time with Django Framework. A service provider is using django i can see the data only with an active Cookie on their API Docs. We received now an API Token to call for the data on the framework. I am trying to call the data with the Token via AJAX but i receive everytime the same console log "401 (Unauthorized)". $.ajax({ type: 'POST', headers: { 'X-CSRFTOKEN': "XXXXXXXXXXXXXXX", 'Content-Type': 'application/json' }, url: 'www.service-provider.url/api/...', success: function () { console.log("ok"); }, error: function () { console.log("error"); } }); Sorry i'm a beginner at this point and have no idea where to begin with. I've searched for solution on the inet but couldn't find anything that would work. -
Have Integerated the ckeditor in django model but when saving the data from ckeditor django admin panel it is not saving to database , showing blank
I am using RichText Field from ckeditor.fields import RichTextField class Section(BaseContent): image = ImageWithThumbsField(upload_to='static/%Y/%m/%d', sizes=((90,120),(180,240),(360,480)),blank=True, null=True ) # image = ImageWithThumbsField(upload_to='static/%Y/%m/%d',blank=True, null=True ) description = RichTextField("Section description. Appears in section home page", blank=True, null=True) url4SEO = models.SlugField("SEO friendly url, use only aplhabets and hyphen", max_length=60) summary = models.CharField("Byline/ Summary", max_length=300, blank=True, null=True) css = models.CharField("Section specific CSS", max_length=300, blank=True, null=True) allowContent = models.BooleanField("Should this section allow any content(such as News and Event)?", default=True) parent = models.ForeignKey('self', blank=True, null=True,on_delete=models.DO_NOTHING) home_disp = models.BooleanField(default = False) sub_description=RichTextField("Section sub description. Appears in section portfolio page", blank=True, null=True) sub_image=ImageWithThumbsField(upload_to='static/%Y/%m/%d', sizes=((90,120),(180,240),(360,480)),blank=True, null=True ) # sub_image=ImageWithThumbsField(upload_to='static/%Y/%m/%d',blank=True, null=True ) is_active = models.BooleanField() -
Django Template request.GET.value don't work
I need to set selected="selected" for a select field. <form action="{% url 'books:book_detail' book.pk %}" method="get"> {% csrf_token %} <select name="country"> {% for shop_country in shop_countries_list %} {% if request.GET.country == shop_country.pk %} <option value="{{ shop_country.pk }}" selected="selected">{{ shop_country.name }}</option> {% else %} <option value="{{ shop_country.pk }}">{{ shop_country.name }}</option> {% endif %} {% endfor %} </select> <button class="button" type="submit">Search</button> </form> But it's not working. I think that request.GET.country inside the if statement is null or empty. But if I to put request.GET.country in some other place of my code like this: {{ request.GET.country }} - it give the correct value. So the question is why it doesn't give any value inside the if statement? -
Registering Django objects with child objects
I have two tables named product and variant. I am building an offer creation module. While creating the offer, I want to pull the products from the product and variant table and save them to the offer product table, but I am having problems with the checkboxes. model.py from django.db import models from firma.models import company class variant(models.Model): name = models.CharField('Varyant Adı',max_length=200) price = models.IntegerField('Varyant Fiyat') stok = models.IntegerField('Varyant Stok') company = models.ForeignKey(company,on_delete=models.CASCADE) image = models.FileField(upload_to="variant",default="") def __str__(self): return f"{self.name}" class product(models.Model): name = models.CharField('Ürün Adı',max_length=200) price = models.IntegerField('Ürün Fiyat') stok = models.IntegerField('Ürün Stok') variant = models.ManyToManyField(variant,blank=True) company = models.ForeignKey(company,on_delete=models.CASCADE) image = models.FileField(upload_to="product",default="") def __str__(self): return f"{self.name}" model.py class offerProductInfo(models.Model): offerProductName = models.CharField('Ürün Adı',max_length=200) offerProductPrice = models.IntegerField('Ürün Fiyat') offerProductStok = models.IntegerField('Ürün Stok') offerProductVariant = models.ManyToManyField(offerVariantInfo,blank=True) offerProductCompany = models.ForeignKey(company,on_delete=models.CASCADE) offerProductImage = models.ImageField(upload_to="product") def __str__(self): return f"{self.offerProductName}" view.py def teklifsave(request): if not request.user.is_authenticated: return redirect('login') if request.method == 'POST': offerVariantId = request.POST.getlist('offerVariantId') offerProduct = request.POST.getlist("offerProducts") count = -1 for fproduct in offerProduct: print(fproduct) count += 1 h = variant.objects.get(id=offerVariantId[count]) c = h.product_set.all() print(c) s = offerVariantInfo( offerVariantName = h.name, offerVariantPrice = h.price, offerVariantStok = h.stok, offerVariantCompany = h.company ) s.save() z = product.objects.get(id=fproduct) c = offerProductInfo( offerProductName = z.name, offerProductPrice = z.price, … -
Django ValueError: field admin.LogEntry.user was declared with a lazy reference to 'app.user', but app 'app' doesn't provide model 'user'
I have a similar problem to this post but its only answer didn't help: ❯ python manage.py makemigrations No changes detected Because when I execute python manage.py migrate I get the following traceback: ❯ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, portfolio, sessions Traceback (most recent call last): File "C:\Users\user\Projects\personal_website\src\packages\pweb_django\manage.py", line 23, in <module> main() File "C:\Users\user\Projects\personal_website\src\packages\pweb_django\manage.py", line 19, in main execute_from_command_line(sys.argv) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\core\management\commands\migrate.py", line 236, in handle pre_migrate_apps = pre_migrate_state.apps File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\db\migrations\state.py", line 544, in apps return StateApps(self.real_apps, self.models) File "C:\Users\user\Projects\personal_website\pweb-venv\lib\site-packages\django\db\migrations\state.py", line 615, in __init__ raise ValueError("\n".join(error.msg for error in errors)) ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'portfolio.user', but app 'portfolio' doesn't provide model 'user'. Yet, when I check the file portfolio\models.py it clearly provides the 'user'-model: class User(AbstractUser): """Dummy class in order to mimic a standard Auth-user. Docs: https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project """ pass In the related … -
On Raw HTML, website looks as I intend it. But on Django, there is some blank space created during the for loop
<div id="Project" class="bg-white fnt-white brdr project-div "> <div class="float-left image-for-project-container brdr"> <img src="{% static './Images/manworking.webp' %}" alt="manworking" height="630px"> </div> {% for project in project_details %} <div class=" project-container inline-block "> <h2 class="text-center fnt-black head-portfolio"> {{project.project_name}} </h2> <br> <br> <p class="margin-auto txt-portfolio roboto hover-orange fnt-black"> {{project.project_details}} </p> <br> <a href="#" class="buttons read-more fnt-black">Read More</a> </div> </div> Issue: The project container when receiving dynamic entries from Django model, creates multiple project containers as executed by the forloop. However, as evident from the image attached, as each project container is created, it is creating an unwanted upward indentation or margin successively. What am I doing wrong? This is the HTML code. I do not think there is any requirement for my CSS stylesheet as when I view the HTML file without Django, it's absolutely alright. I have also attached an image to show the space that is being created. In case the Imgur is not being shown here is the link (https://i.stack.imgur.com/EnUUG.png). -
How do I update data in a linked django rest model?
How do I update data in a linked django rest model Here is my json { "doc_type": 1, "warehouse": 4, "date": "2022-06-09", "number": 980, "contragent": 2, "comment": "testcom;mgment", "items": [ { "product": 7, "buy_price": "168.00", "sell_price": "500.00", "quantity": 17 }, { "product": 8, "buy_price": "168.00", "sell_price": "500.00", "quantity": 17 } ] } I can't change the data in the "items" dictionary If I submit only one "product" element, will the other one be deleted? And if, for example, three, will it be added? this is what I have at the moment, records are created without problems, but I can only update the "ConsignmentNote" model #serialisers.py class ConsignmentNoteSerializer(serializers.ModelSerializer): creator = serializers.HiddenField(default=serializers.CurrentUserDefault()) doc_type = serializers.IntegerField(read_only=True) # contragent_detail = ContragentSerializer(source='contragent', read_only=True) items = ConsignmentItemSerializer(many=True) class Meta: model = ConsignmentNote fields = ['doc_type', "warehouse", 'date', 'number', 'contragent', 'comment', 'creator', 'items'] read_only_fields = ['id' ] def create(self, validated_data): items = validated_data.pop('items') note = ConsignmentNote.objects.create(**validated_data, doc_type = 1) for item in items: product = item.pop('product') item = ConsignmentItem.objects.create(consignmentnote=note, product=product ,**item) return note def update(self, instance, validated_data): instance.date = validated_data.pop('date', instance.date) instance.comment = validated_data.pop('comment', instance.comment) return instance -
Compare entirely two different models in Django
I have been working in Django template. I have been stuck here since quite some time now. {% for i in LOOP %} {% if i == {{SECOND VARIABLE}} %} //Do Something {% endif %} {% endfor %} LOOP and second variable are entirely different. Is there something we can do? Is there some alternate solution -
Django,MSSQL server query and pagination
This is a sample of my MSSQL server table Employeetable emp_id name status EMP001 A STATUS-A EMP001 A STATUS-B EMP002 B STATUS-C EMP001 A STATUS-D EMP002 B STATUS-D EMP003 C STATUS-C Now in my app front end page there is a table in which each employee is listed once in the table and expanding each employee will show their every available status For Example: EMPID NAME EMP001 A ---STATUS-A #After expanding the EMP001 row it shows all the status of EMP001 ---STATUS-B ---STATUS-D EMP002 B EMP003 C So how can we use pagination in this consider there are about 200K records and about 100K distinct employees -
How do I test if my django is connecting to my cloud proxy auth mysql site?
I am receiving this error: django.db.utils.ProgrammingError: (1146, "Table 'xpotoolsdb.xpotoolshome_site' doesn't exist") in pycharm on mac os and windows 10. My coworkers are not and they are able to run a local development environment. How would I go about troubleshooting this error? It seems as if my local dev env is not finding a table in the mysql database but I don't think it's actually connecting at all since my coworkers aren't receiving the same error. -
Forms django -> is_valid
i'm currently developping an application on django and when i send a post request from a form, is_valid method return false. my forms.py : from django import forms class formadduser(forms.Form): mail = forms.CharField(label='Mail', max_length=40) # imput_username = forms.CharField(input='input_username', max_length=100) prenom = forms.CharField(label='Prénom', max_length=25) # input_password = forms.CharField(input='input_pathword', max_length=100) nom = forms.CharField(label = 'Nom', max_length=25)