Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to send flutter firebase notification using dcm-django
I am trying to send notification to flutter app from firebase. It sends notification well while sending from: https://console.firebase.google.com/project/nadir-d4ec4/notification/compose but I want to connect/control firebase with django. so, django will call firebase api asking it to send notification to flutter app. django package used: fcm-django settings.py is only file i have edited for that and settings.py contains: INSTALLED_APPS = [ # other apps "fcm_django" ] FIREBASE_APP = initialize_app() FCM_DJANGO_SETTINGS = { "FCM_SERVER_KEY": "87-digit string copied from:`project settings/cloud messenging` of firebase app", "APP_VERBOSE_NAME": "[string for AppConfig's verbose_name]", "ONE_DEVICE_PER_USER": False, "DELETE_INACTIVE_DEVICES": False, # True/False } I could not find what APP_VERBOSE_NAME is supposed to be so left as it is. and I want to send notification using: python3 manage.py runserver from fcm_django.models import FCMDevice device = FCMDevice.objects.all().first() device.send_message("Title", "Message") device.send_message(data={"test": "test"}) device.send_message(title="Title", body="Message", icon=..., data={"test": "test"}) but # FCMDevice.objects.all() is giving empty list instead of users so no user to send notifications. I want list of user to send notifications to. code: django: https://github.com/Aananda-giri/uzme_backend/ flutter: https://github.com/Yogeshpanta/nadir -
How to update nested serializer field with many=True
I'm having trouble in updating the serializer data that have nested serializer field, please if someone have any idea to it with best practice i will appreciate your answer! class SerializerA(serializers.ModelSerializer): anyfielda = serializers.CharField() class SerializerB(serializers.ModelSerializer): anyfieldb = serializers.CharField() nested_field = SerializerA(required=True, many=True) How to implement the update method please guide! I'm able to do create but update does not allowed as it is asking for ListSerializer must, I want to know if there is any other way! -
Apache2 does not find python3.8 based virtual env and load python3.6 based env
i have an issue with a django based application deployment with apache2 on ubuntu18.04 with python3.8. I installed the mod_wsgi and apache2 as: sudo apt-get install apache2 sudo apt-get install libapache2-mod-wsgi-py3 I setup venv folder in the project folder. I get error logs as: Error Log 1 [Tue Jun 21 08:34:13.966782 2022] [mpm_event:notice] [pid 660:tid 140673610189760] AH00491: caught SIGTERM, shutting down [Tue Jun 21 20:11:41.285936 2022] [mpm_event:notice] [pid 32599:tid 139678582156224] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Tue Jun 21 20:11:41.287426 2022] [core:notice] [pid 32599:tid 139678582156224] AH00094: Command line: '/usr/sbin/apache2' Error Log 2 [Tue Jun 21 20:11:44.374973 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] mod_wsgi (pid=32600): Target WSGI script '/home/$USER/{{project_name}}/{{project_name}}/wsgi.py' cannot be loaded as Python module. [Tue Jun 21 20:11:44.375046 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] mod_wsgi (pid=32600): Exception occurred processing WSGI script '/home/$USER/{{project_name}}/{{project_name}}/wsgi.py'. [Tue Jun 21 20:11:44.375175 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] Traceback (most recent call last): [Tue Jun 21 20:11:44.375230 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] File "/home/$USER/{{project_name}}/{{project_name}}/wsgi.py", line 12, in <module> [Tue Jun 21 20:11:44.375244 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] from django.core.wsgi import get_wsgi_application [Tue Jun 21 20:11:44.375272 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] ModuleNotFoundError: No module … -
How to render non-model objects in django admin?
I have the following model listed in Django admin already with the following view: class BookTabularInline(admin.TabularInline): model = Book @register(Bookcase) class BookcaseAdmin(admin.ModelAdmin): inlines = [BookTabularInline] The changes I want to make is: Instead of returning all the Books associated with Bookcase, I only want to return specific ones via queryset for example: Books.objects.filter(isAvailable=True, bookcase=bookcase).order_by("name"). How can I accomplish this? Instead of returning the model (Book) from this queryset, I want to return a BookPublicObject with different attributes inline, but BookPublicObject is a dataclass and not a Django model. Is this possible? -
Getting 500 error with Django via Ajax request, even though Django receives the request and is returning data
I have a click function that calls the Ajax request as shown to a url defined in urls.py. I can see that django is getting the data because I have print statements in views.py which print the data that will be passed back to frontend, but I end up getting this error: "GET /comment-data/?asset=total&timestamp=1654957681 HTTP/1.1" 500 145. If anyone's run into this before, much help is appreciated! Ajax call urls.py views.py (yes I know I have a bunch of unused variables) -
Unable to log in with provided credentials in DRF
I get the error { "non_field_errors": [ "Unable to log in with provided credentials." ] } whenever I do http://127.0.0.1:8000/api-token-auth/ and pass in my username and password. what's confusing is that when i run the post with my superuser account it works (i get my account token) though i noticed that my superuser's password is hashed but my normal account password isn't models.py def create_user(self, email, password, **other_fields ): if not email: raise ValueError("you must add an email") email = self.normalize_email(email) user = self.model(email =email, password = password, **other_fields) user.set_password(password) user.save(using=self._db) return user.email def create_candidate(self, email, password, **other_fields ): user = self.create_user(email, password, **other_fields) user.is_candidate = True user.save(using=self._db) return user.email def create_superuser(self, email, password, **other_fields ): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_candidate', False) if other_fields.get('is_staff') is not True: raise ValueError('superuser must be assigned is_staff=True') if other_fields.get('is_superuser') is not True: raise ValueError('superuser must be assigned is_superuser=True') return self.create_user(email, password, **other_fields) -
Bootstrap 5 - Navbar - Logo/Brand Text Left - Menu Center - Search Right
I am trying to make a Navbar in Bootstrap 5. I would like to have the Logo (In my case this is just some fancy text) on the left. I would then like the menu centered and my search field on the right. The issue I seem to be having is when I have managed to get them lined up like this, the menu is going in the center of the search and logo divs, which due to logo size etc hasn't necessarily been the middle of my screen like I want. I have been at it for days trying different things on her but just can't seem to get it right. I also want the mobile menu to collapse and include the search. The mobile menu should then have the logo aligned in the center and the collapse button just below it also centered. The latest code I have tried is this: index.html: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{% block title %}{% endblock %}Life With Vicky</title> <meta name="description" content="{% block meta_description %}{%endblock %}"> {% block canonical %}{%endblock %} {% block opengraph %}{%endblock %} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> <link … -
How to manage session with 3rd party API in Django?
Context: I have a Django based application. This application has various REST API endpoints where users can gather data. Some of this data needs to be pulled from a third-party API. This external API uses basic authentication. In order to fetch this data, I have the following code implemented in my endpoint logic. def metadata(jira_key: str, format=None): username = "example" password = "example" try: print(f"fetching {jira_key} with '{username}' credentials") url = f"https://external.api.com/issue/{jira_key}" session = requests.Session() session.auth = username, password headers = {'Content-Type': 'application/json'} response = session.get( url, headers=headers) print(f"response: {response.status_code}") return response except Exception as e: message = {"error": "Uncaught error", "message": str(e)} return message Long story short; it works! This endpoint is essentially just a proxy for another API. This is done for security purposes. However, I have been experiencing lock-outs where permission for the service account needs to be reinstated periodically... I suspect the session is being generated every time the endpoint is hit. So my question is this: How can I implement a persisted request.Session() with basic auth that is established at build time, and reused for each requests? Thanks for your help in advance! :) -
Timeout error in django send_mail program
I am doing a send_mail function in django and connected mysql database with it to store the name and subject values. I am using the smtp backend server to connect the mail and django. The port used is 587. This is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mail_test', 'USER': 'root', 'PASSWORD': '', 'HOST':'localhost', 'PORT':'3306', 'OPTIONS':{ 'init_command':"SET sql_mode='STRICT_TRANS_TABLES'" } } } ---- DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'swarai.bot@gmail.com' EMAIL_HOST_PASSWORD = 'pfxbswfjgligavgb' ** This is my views.py** from django.views.generic import FormView, TemplateView from .forms import EmailForm from django.urls import reverse_lazy from mailapp.models import Email from django.shortcuts import render class MailView(FormView): template_name = 'index.html' form_class = EmailForm success_url = reverse_lazy('mailapp:success') def form_valid(self, form): # Calls the custom send method form.send() return super().form_valid(form) def registered(request): name = request.POST['name'] email = request.POST['email'] inquiry = request.POST['inquiry'] message = request.POST['message'] person = Email(name=name, email=email, inquiry=inquiry, message=message) person.save() return render(request, 'success.html') class MailSuccessView(TemplateView): template_name = 'success.html' I am getting timeout error whenever I submit the page. I tried to add the port 587 using control panel. But then also, I am getting the same error. I don't know whether this error is … -
django post request: Forbidden (CSRF token missing.): /categories
In my file view.py I want to write a class based on View with get and post methods for API. Get is already written, it works. There was a problem with the post: Code of this class: class CategoryListView(View): def get(self, request): if not check_correct_api_secret(request): return HttpResponseForbidden('Unknown API key') query_set = Category.objects.all() query_params = request.GET query_set = paginate(query_params, query_set) items_data = serialize_category_list(request, query_set) return JsonResponse(items_data, safe=False) # Method code is written for example, just to see some kind of reaction to the post request def post(self, request): query_params = request.POST name = query_params.get('name') Category.objects.create(name=name) return HttpResponse(201) I try send post request: /categories?name=Category6 (For example) And I get error: Forbidden (CSRF token missing.): /categories [21/Jun/2022 16:21:26] "POST /categories?name=Category777 HTTP/1.1" 403 2506 My urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('categories', CategoryListView.as_view()), ] -
“non_field_errors”: [ “Invalid data. Expected a dictionary, but got QuerySet.” ] problem with serializer or model from djongo
I've recently started to learn django. And at this time i'm working on integrating mongoDB with Django using djongo driver. I've created a model for saving and mapping my data objects to mongoDB but i'm lacking knowledge about implementing serializers and at this stage i'm encountering one situation which i've been unable to resolve since 2 days so please throw some light and help me implement it. the error message from django REST framework api models.py from djongo import models # Create your models here. class OrderItem(models.Model): itemDescription = models.TextField(name = "itemDescription") itemQuantity = models.FloatField(name = "itemQuantity") itemPrice = models.FloatField(name = "itemPrice") class Meta: abstract = True class Order(models.Model): email = models.EmailField(primary_key = True, name = "email") customerName = models.CharField(max_length=30, help_text="Enter Customer Name", name = "customerName") customerAddress = models.TextField(help_text="Enter customer's Address", name = "customerAddress") orderItems = models.ArrayField( model_container = OrderItem, ) objects = models.DjongoManager() serializers.py from .models import Order, OrderItem from rest_framework.serializers import ModelSerializer class OrderItemsSerializer(ModelSerializer): class Meta: model = OrderItem fields = '__all__' class OrderSerializer(ModelSerializer): orderItems = OrderItemsSerializer(many=True) class Meta: model = Order fields = "__all__" views.py @api_view(['GET']) def getOrders(request): orders = Order.objects.values() serializer = OrderSerializer(data = orders) if serializer.is_valid(): print("Valid") return Response(data = serializer.data) else: print("invalid") print(serializer.errors) return … -
Nested Serializers with different queryset
How to create a nested serializer with it's own queryset? In the following example I would like to replace an '@api_view' function with a class based view with serializers. Simplified, I have the following code: models.py class Klass(models.Model): name = models.TextField() class Pupils(models.Model): name = models.TextField() klass = models.ForeignKey(Klass) class Chapter(models.Model): """A Chapter in a school book.""" name = models.TextField() class TestResult(models.Model): """TestResults for a Chapter.""" pupil = models.ForeignKey(Pupil) chapter = models.ForeignKey(Chapter) score = models.IntegerField() view.py @api_view def testresults(request, klass_id, chapter_id): pupils = Pupils.objects.filter(klas__id=klass_id) tests = Tests.objects.filter(chapter__id=chapter_id) ret_val = [] for pupil in pupils: pu = { "name": pupil.name, "tests": [{"score": test.score, "chapter": test.chapter.name} for test in tests.filter(pupil=pupil)] } ret_val.append(pu) return Response({"pupils": ret_val}) url /api/testresult/<klass_id>/<chapter_id>/ -
IIS can not access newly added files in a django project
In a django project that is served by IIS (windows), i added a local file, test.py. The project ran perfectly before and still runs perfect on localhost, however IIS appears to not recognize the new test.py file. It appears IIS access to this file fails, even if the users IUSR and IIS_USRS have full access (same as for all other files in the folder). I get below error message, and somethimes also the same but "No module named 'app.test'. Removing the "import app.test as test" in views.py solves the issue. Suprisingly the "import app.oldFile as oldFile" works without issue. In my views.py, i import the python scripts like this import app.oldFile as oldFile import app.test as test My django project has the structure: djangoRest -app --__init__.py --views.py --oldFile.py --test.py -djangoRest --__init__.py --settings.py --urls.py --wsgi.py -
How to know if which selected in django template select?
In my django templates how can I know which select option is selected? <select id="platformid" name="platform"> {% for x in list %} <option value="{{x.company}}">{{x.company}}</option> {% endfor %} </select> -
Django POST request returns NONE
so ive been serching for a solution for about a week now I just need the data from a hidden label within a form witch should be no problem but instead of the data from the label i just get 'NONE' Template (form): {% for Gerecht in Gerechten %} <form method="POST"> {% csrf_token %} </section> <section class="u-clearfix u-custom-color-2 u-valign-middle u-section-2" id="sec-a9e5"> <div class="u-clearfix u-gutter-0 u-layout-wrap u-layout-wrap-1"> <div class="u-layout" style=""> <div class="u-layout-row" style=""> <div class="u-align-left u-container-style u-image u-layout-cell u-left-cell u-shading u-size-30 u-size-xs-60 u-image-1" src="" data-image-width="4880" data-image-height="3253" style=" background-image: linear-gradient(0deg, rgba(0,0,0,0.25), rgba(0,0,0,0.25)), url('{% static '/img/{{ Gerecht.afbeelding }}' %}')"> <div class="u-container-layout u-container-layout-1" src=""></div> </div> <div class="u-align-left u-container-style u-custom-color-1 u-layout-cell u-right-cell u-size-30 u-size-xs-60 u-layout-cell-2"> <div class="u-container-layout u-container-layout-2"> <h2 class="u-text u-text-default u-text-white u-text-1"> {{ Gerecht.naam }}</h2> <p class="u-text u-text-default u-text-white u-text-2">Duur: {{ Gerecht.duur }} u </p> <input type="submit" value="ga naar gerecht" class="u-active-custom-color-3 u-align-left u-border-1 u-border-active-custom-color-3 u-border-hover-custom-color-3 u-border-white u-btn u-btn-round u-button-style u-hover-custom-color-3 u-none u-radius-12 u-text-active-white u-text-hover-white u-btn-2" name="btnZieRecept"> <label name="id" style="display: none;" value="{{ Gerecht.id }}">{{ Gerecht.id }}</label> </div> </div> </div> </div> </div> </section> </form> {% endfor %} My views.py: if request.POST.get('btnZieRecept'): PK = request.POST.get('id') logging.basicConfig(level=logging.NOTSET) logging.debug(request.POST.get('id')) return redirect('GerechtPreview', PK=PK) So here PK=None and i dont know why def GerechtPreview(request, PK): obj = Gerecht.objects.get(pk=PK) ingList=[] for f … -
Django: How to change the value on a model's field within a property on the model
I would like to change the value of a model field within a property set on the model. Let's say we have the model and the following properties: class Rider(models.Model): booking = models.BooleanField(default=True) cancel = models.BooleanField(default_True) _disabled_notifications = JSONField() @property def disabled_notification(self): return json.loads(self._disabled_notifications @disabled_notifications.setter def disabled_notifications(self, value) try: field = self._meta.get_field(value) except FieldDoesNotExist as e: raise e In this case, field would return an Options object. How do I use this to change the value on the field? -
How to test Stripe `SignatureVerificationError` in Python
For python, the standard stripe webhook code example includes: event = None try: event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret) except ValueError as e: logger.error(f"*** Stripe invalid payload: {e = }") return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: logger.error(f"*** Stripe invalid signature: {e = }") return HttpResponse(status=400) I've tried to test this with the following test that inherits from Django testcase: class TestStripeWebhookView(TestCase): @mock.patch("logging.Logger.error") @mock.patch("lettergun.apps.payments.views.create_order") @mock.patch("lettergun.apps.payments.views.stripe") def test_signature_verification_error(self, stripe, create_order, error): stripe.Webhook.construct_event.side_effect = SignatureVerificationError data = { "type": "placeholder", } response = self.client.get( reverse("payments:stripe_webhook"), data, HTTP_ACCEPT="application/json", HTTP_STRIPE_SIGNATURE='placeholder_signature"}', ) error.assert_called_with(f"*** Stripe invalid signature: e = an error message") assert not create_order.called assert response.status_code == 400 This produces the following error which I dont understand: > except stripe.error.SignatureVerificationError as e: E TypeError: catching classes that do not inherit from BaseException is not allowed How can I test that the signature verification error will have the expected effects? -
Change model rendered form select/option element into multi-select checkboxes with Django
I need to change two form fields (now select/option) into multi-choice checkboxes in a form that is rendered from the model. Despite carefully reading the Django docs I don't get it displayed, i.e nothing happens. What do I need to do in models.py to render the checkboxes? (For simplicity, I only display the code for one field) So far in form.py: class CreateVariantForm(ModelForm): class Meta: model = VariantView fields = '__all__' suitable_for = forms.MultipleChoiceField(choices=VariantView.SuitableForProduct.choices, widget=forms.CheckboxSelectMultiple) In models.py: class VariantView(models.Model): class SuitableForProduct(models.TextChoices): JEWELLERY = "Jewellery", _("Jewellery") ACCESSORIES = "Accessories", _("Accessories") COSMETICSHYGIENE = "Cosmetics & Hygiene", _("Cosmetics & Hygiene") ELECTRONICSGADGETS = "Electronics & Gadgets", _("Electronics & Gadgets") suitable_for_product = models.CharField(max_length=255, choices=SuitableForProduct.choices, null=True, blank=True ) class Meta: managed = False db_table = "variant_view" In views.py: class ProductUpdate(LoginRequiredMixin, UpdateView): login_url = "/" model = VariantView template_name = "searchapp/product_update_form.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["suitable_for_product"] = SuitableForProduct.objects.values_list( "suitable_for", flat=True ) return context def get_success_url(self): return reverse_lazy("listvariants", args=[self.object.product_group_id])`` ``` -
csrf_token verification failed?
I am a beginner and searched a lot about it but do not got any thing please explain why this error is coming. I have used this code from here: JavaScript post request like a form submit Error is coming from the following code in my html template in under script tag: This code is from Davidson Lima comment: post("{% url 'savep' %}", {name: user_name, pass: user_pass, csrfmiddlewaretoken: $("csrf_token").val()}); Here is the code of views.py def save_login(request): x = request.POST['user'] y = request.POST['pass'] member = credentials(user_name=x, user_pass=y) member.save() Error: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token from POST has incorrect length. -
Django foreignkey between two databases
I'm looking to connect two SQLite tables together (oh dear). I found this solution : How to use django models with foreign keys in different DBs? , I adapted it to my models and my code (I think). I have no bad answers from django. However, I would like to modify the entry with the admin view of django, and when I try to add the entry with the foreign key of another database, I get this answer: Exception Type: OperationalError at /admin/users/character/add/ Exception Value: no such table: books How to adapt to fix it? models database default from django.db import models from users.related import SpanningForeignKey from books.models import Books class Character(models.Model): last_name = models.fields.CharField(max_length=100) first_name = models.fields.CharField(max_length=100) book = SpanningForeignKey('books.Books', null=True, on_delete=models.SET_NULL) def __str__(self): return f'{self.first_name} {self.last_name}' models external database from django.db import models # Create your models here. class Books(models.Model): title = models.TextField() sort = models.TextField(blank=True, null=True) timestamp = models.TextField(blank=True, null=True) # This field type is a guess. pubdate = models.TextField(blank=True, null=True) # This field type is a guess. series_index = models.FloatField() author_sort = models.TextField(blank=True, null=True) isbn = models.TextField(blank=True, null=True) lccn = models.TextField(blank=True, null=True) path = models.TextField() flags = models.IntegerField() uuid = models.TextField(blank=True, null=True) has_cover = models.BooleanField(blank=True, null=True) … -
Django REST API: Invalid data. Expected a dictionary, but got User
I want to design a REST API where user can submit a new car record using POST request. The user is automatically should be set as creator. Under my models.py I have: class CarRecord(models.Model): type = models.CharField(max_length=50) license = models.CharField(max_length=50) creator = models.ForeignKey(User,on_delete=models.DO_NOTHING) Under my serializers.py I have: class UserSerializer(serializers.ModelSerializer): username = serializers.CharField(max_length=50) class Meta: model = User fields = ['username'] class CarRecordSerializer(serializers.ModelSerializer): type = serializers.CharField(max_length=50) license = serializers.CharField(max_length=50) creator = UserSerializer() class Meta: model = CarRecord fields = ('__all__') And In the post method I have: class CarRecordViews(APIView): def post(self, request): user = request.user if not user.is_authenticated: user = authenticate(username=request.data['username'], password=request.data['password']) if user is None: return Response(data={"error": "bad username/password"}, status=status.HTTP_401_UNAUTHORIZED) data = { 'type': request.data['type'], 'license': request.data['license'], 'creator': user } serializer = CarRecordSerializer(data=data) serializer.is_valid(raise_exception=True) return Response({"message": "success"}, status=status.HTTP_201_CREATED) But I get: { "creator": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got User." ] } } I want to keep the user as the creator. I'm not sure I fully understand how serializers work but I believe the problem is in that file. Have can I make it work? -
Get Dn from an AD, using LDAP protocol on python without connection
I try ot make a Django app using connection by ldap. To test the connection you need to use <ldapInstance>.simple_bind_s(User, Password) where User is a DN : CN=me,OU=other,DC=com (for exemple) So i try to get this DN by a function using : <ldapInstance>.search_s(paramers...) and return this error : info: 0002020: Operation unavailable without authentification The problem is, if i want DN, i need connection using DN for connection. Someone have an idea ? -
Django Upload File, Analyise Conents and write to DB or update form
I'm pretty new to Django, Trying to get my grips with it, and expand what I think its capable of doing, and maybe one of you more intelligent people here can point me in the right direction. I'm basically trying to build a system similar to a so called "Asset Management" system, to track software version of a product, so when an engineer updates the software version, they run a script which gathers all the information (Version, Install date, Hardware etc), which is stored in a .txt file, The engineer then comes back to the website and upload this .txt file for that customer, and it automatically updates the fields in the form, or directly to the database. While, I've search a bit on here for concepts, I haven't been able to find something similar (Maybe my search terms aren't correct?), and wanted to ask if anyone knows, what I'm doing is even feasible, or am I lost down the rabbit hole of limitations :) Maybe its not do-able within Django, Any suggestions on how I should approach such a problem would be greatly appreciated. -
how can I count data from foreign key field in Django template?
models.py: class Region(models.Model): city = models.CharField(max_length=64) class Properties(models.Model): title = models.CharField(max_length=200) Region = models.ForeignKey(Region, related_name='Region', on_delete=models.Cascade) how can i count all properties which have the same region ? -
Django import-export library ForeignKey error (IntegrityError: FOREIGN KEY constraint failed in django)
First of all please sorry for my English. )) So I have a problem with Django import-export library when I try to import data from csv/xls/xlsx files to the Django application DB. How it looks like. Here is my models.py: class Department(models.Model): department_name = models.CharField(max_length = 50, default = '', verbose_name = 'Подразделение') def __str__(self): return f'{self.department_name}' class ITHardware(models.Model): it_hardware_model = models.CharField(max_length = 100) it_hardware_serial_number = models.CharField(max_length = 100, blank = True, default = '') it_hardware_department = models.ForeignKey(Department, related_name = 'department', on_delete = models.SET_NULL, default = '', null = True, blank = True, db_constraint=False) admin.py: @admin.register(Department) class DepartmentAdmin(admin.ModelAdmin): list_display = ('department_name', ) actions = [dublicate_object] @admin.register(ITHardwareManufacturer) class ITHardwareManufacturerAdmin(admin.ModelAdmin): list_display = ('manufacturer', ) actions = [dublicate_object] class ITHardwareImportExportAdmin(ImportExportModelAdmin): resource_class = ITHardwareResource list_display = ['id', 'it_hardware_manufacturer', 'it_hardware_model', 'it_hardware_serial_number', 'it_hardware_department'] actions = [dublicate_object] resource.py: class ITHardwareResource(resources.ModelResource): it_hardware_department = fields.Field( column_name = 'it_hardware_department', attribute = 'ITHardware.it_hardware_department', widget = widgets.ForeignKeyWidget(Department, field = 'department_name')) class Meta(): model = ITHardware fields = ( 'id', 'it_hardware_model', 'it_hardware_serial_number', 'it_hardware_department', ) export_order = ( 'id', 'it_hardware_model', 'it_hardware_serial_number', 'it_hardware_department', ) import file: import file If I try to import data from file, I get such error: String number: 1 - ITHardwareManufacturer matching query does not exist. None, Canon, BX500CI, 5B1837T00976, Office_1, …