Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModelChoiceField in django admin gives 'Select a valid choice. That choice is not one of the available choices.' error
Hej! I want a field in my django admin area where the user can select from given choices in the database. For example get a list of countries and choose one. But I will always get the ' Select a valid choice. That choice is not one of the available choices.' error when you try to save the new instance. #models.py class PlaceSection(models.Model): code = models.CharField(max_length=1) def code_str(self): return self.code # admin.py class InstiForm(forms.ModelForm): place_sections = forms.ModelChoiceField( PlaceSection.objects.values(), widget=Select2Widget, ) class Meta: model = Something fields = [ "place_section"] class InstiAdmin(admin.ModelAdmin): form = InstiForm save_on_top = True def save_model(self, request, obj, form, change): fieldsets = [ ( ("General"), {"fields": [ "place_sections" ] } ) ] I do get the right choices in the admin dropdown but when I select one and save the error occurs. Does anyone has an idea how to fix this (in the admin) found only similar problems without the admin part and no solution worked for me. Help is really appreciated! :) -
Can't Submit ModelForm using CBVs
I am trying to use ModelForms and CBVs to handle them, but I am facing trouble especially while submitting my form. Here's my code. forms.py from django import forms from .models import Volunteer class NewVolunteerForm(forms.ModelForm): class Meta: model = Volunteer fields = '__all__' views.py from django.http.response import HttpResponse from django.views.generic.edit import CreateView from .forms import NewVolunteerForm class NewVolunteerView(CreateView): template_name = 'website/join.html' form_class = NewVolunteerForm def form_valid(self, form): print('Submitting') form.save() return HttpResponse('DONE') join.html {% extends 'website/_base.html' %} {% block title %}Join Us{% endblock title %} {% block content %} <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> {% endblock content %} The form is getting displayed correctly with no issues at all, but when I fill it in and press the submit button it simply re-rendered the form and doesn't submit it at all. -
APM Django - how to correlate container logs from Filebeat with data from ElasticAPM in Kibana?
Kibana version: 7.14.0 Elasticsearch version: 7.14.0 APM Server version: 7.14.0 Filebeat version: 7.14.0 APM Agent language and version: Python Django - elastic-apm 6.3.3 Description: The APM server and Python agents are working as expected just like the Filebeat. They're collecting logs and metrics, but I don't know how to correlate them in Kibana: Live streaming from Logs section is working and I can filter apm instances with container.id. 1. APM, Elasticsearch, Kibana configs docker-compose.yml: version: '3.3' services: elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:7.14.0 hostname: elasticsearch environment: - ES_JAVA_OPTS=-Xms512m -Xmx512m - ELASTIC_PASSWORD=password ports: - 192.168.100.100:9200:9200 volumes: - ./data:/usr/share/elasticsearch/data - ./elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml networks: - elk kibana: image: docker.elastic.co/kibana/kibana:7.14.0 hostname: kibana restart: always ports: - 192.168.100.100:5601:5601 volumes: - ./kibana.yml:/usr/share/kibana/config/kibana.yml:ro networks: - elk apm: image: docker.elastic.co/apm/apm-server:7.14.0 hostname: apm command: --strict.perms=false depends_on: - elasticsearch cap_add: ["CHOWN", "DAC_OVERRIDE", "SETGID", "SETUID"] cap_drop: ["ALL"] volumes: - ./apm-server.yml:/usr/share/apm-server/apm-server.yml ports: - 192.168.100.100:8200:8200 networks: - elk networks: elk: driver: bridge apm-server.yml: apm-server: host: "apm:8200" secret_token: token rum: enabled: true kibana: enabled: true host: "kibana:5601" protocol: "http" username: "elastic" password: "password" setup.template.enabled: true setup.template.name: "apm-%{[observer.version]}" setup.template.pattern: "apm-%{[observer.version]}-*" setup.template.fields: "${path.config}/fields.yml" setup.template.overwrite: false setup.template.settings: index: number_of_shards: 1 number_of_replicas: 0 codec: best_compression number_of_routing_shards: 30 mapping.total_fields.limit: 2000 output.elasticsearch: hosts: ["elasticsearch:9200"] username: elastic password: password index: "apm-%{[observer.version]}-%{+yyyy.MM.dd}" indices: - index: "apm-%{[observer.version]}-sourcemap" … -
Django / postgres - maintain a table of counters
I want to maintain a running counter per user, that will be given to the user items. User table will have a last_item_num column class Item: name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) item_num = models.IntegerField() # should be populated from the user table The question, when the user is creating an item, what is the best way to increment the counter and to copy the new counter to the newly created item, atomically? Technically I atomically need to: Increment and get the counter of the user Create a new Item with the value for item_num What is the django / postgres way to do that? -
How do i access another column from related table other than the foreign key, when creating an API view
Im using django for a web app and i am creating REST API views. Is there a way i can access two tables in one view? If not, how can can i retrieve a non-foreign key column from a related record. The below code is retrieving a vase record based on a URL parameter. I want to access the artistName which is stored in artist table (a one-to-many with Vase table), not artist_id which is stored in Vase class FilterVases(generics.ListAPIView): serializer_class = VaseSerializer def get_queryset(self): queryset = Vase.objects.all() artist_id = self.request.query_params.get('artist_id') if artist_id is not None: queryset = queryset.filter(artist_id=artist_id) vaseID = self.request.query_params.get('vaseID') if vaseID is not None: queryset = queryset.filter(vaseID=vaseID) return queryset -
Django Search fonction with all model
i created a view where i called all my models for my search function but it doesn't work ! i'm new in django ! i want to searched all my model by her Charfield field views.py def all_search_view(request): faculty = Faculty.objects.all() job = Job.objects.all() condition = Condition.objects.all() piece = Piece.objects.all() partnership = Partnership.objects.all() book = Book.objects.all() category = Category.objects.all() author = Author.objects.all() publication = Publication.objects.all() query = request.GET.get('q') if query: faculty = Faculty.objects.filter(Q(name__icontains=query)) job = Job.objects.filter(Q(name__icontains=query)) condition = Condition.objects.filter(Q(access_condition__icontains=query)) piece = Piece.objects.filter(Q(name__icontains=query)) partnership = Partnership.objects.filter(Q(name__icontains=query)) book = Book.objects.filter(Q(editor__icontains=query) | Q(title__icontains=query)) category = Category.objects.filter(Q(name__icontains=query)) author = Author.objects.filter(Q(name__icontains=query)) publication = Publication.objects.filter(Q(author__icontains=query) | Q(title__icontains=query) search_results = chain(faculty, job, condition, piece, partnership, book, category, author, publication) context = { 'author': author, 'faculty': faculty, 'job': job, 'condition': condition, 'piece': piece, 'partnership': partnership, 'category': category, 'publication': publication, 'book': book, 'search_results': search_results, } return render(request, 'all_search.html', context) -
how to add label to the select form field
# take a look at the models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') profile_pic = models.ImageField(upload_to="profile_picture/", blank=True, null=True, help_text="please upload an individual photo. Group photo is not allowed.") age = models.PositiveIntegerField(null=True) gender = models.CharField(max_length=20, choices=gender_choices) birth_date = models.DateField(null=True) phone_number = PhoneNumberField(null=True, unique=True, blank=False, ) country = CountryField(blank_label='Select country', blank=True, ) address = models.CharField(max_length=200, null=True) # Here is my forms.py class extendsUserProfile(forms.ModelForm): class Meta: model = userProfile fields = 'all' # i have shown only a widget for gender for which i need to add a label like 'Select' for user to chose either male or female depending upon the gender they belong to. widgets = { 'gender': forms.Select(attrs={ 'class': 'form-control', 'placeholder': 'gender', 'required': True, })} somebody told me to do this way to add a label for age form field in the forms.py def init(self, *args, **kwargs): super(ProfileForm, self).init(*args, **kwargs) self.fields['age'].label = "select" Anyhow that didnt worked. Thank you in advance. i believe views.py is needless for this question. -
Django Forms with different attributes linked to the same Django Model?
I'm pretty new to Django so forgive me if my code isn't too refined and the questions seems confusing. I'm attempting to make a web app where users can submit application forms for licenses. My problem is that there are different kinds of application forms. I've created a model for Licenses and included global attributes such as License ID, Licensee, and Submission Date and Expiry Date. I'm wondering how I can store the different data unique to each form (for instance, some forms have file upload fields while others don't) in a single License object. Is this possible, or should I create different models for each form? Here's some of my code: #models class License(models.Model): licensee = models.ForeignKey(User, on_delete=models.CASCADE) sub_date = models.DateTimeField(default=timezone.now()) exp_date = models.DateTimeField(blank=True, null=True) def save(self, *args, **kwargs): if not self.pk: self.exp_date = self.sub_date + datetime.timedelta(days=30) super(License, self).save() def __str__(self): return self.pk #forms class OP100Form(ModelForm): financial_statements = forms.FileField() annual_report = forms.FileField() shareholding_docs = forms.FileField() stock_exchange_docs = forms.FileField() other_docs = forms.FileField() tel_experience = forms.CharField() tech_facilities_desc = forms.CharField() tech_personnel_desc = forms.CharField() system_maintenance_desc = forms.CharField() telcoms_desc = forms.FileField() serv_desc = forms.CharField() fac_desc = forms.CharField() net_gate_det = forms.CharField() class Meta: model = License exclude = ['licensee', 'sub_date', 'exp_date',] -
Inline_Formset for a particular queryset instead of all the Models?
I'm currently working on a project and am looking to figure out the best way to easily render a list of forms. I've watched a few YouTube videos on inline_formsets (as well as reading the documentation) and I feel like that would be 'the way' to go, but I'm not totally sure how to implement them (or if it's even possible for me) given my model structure. Project Explanation: I have a number of models: Summative, Rubric, Domain, Subdomain, SummativeScore, and ProficiencyLevel The models look like this: class Domain(CreateUpdateMixin): """ Model definition for Domain. """ name = models.CharField(max_length=50) description = models.CharField(max_length=250) class Rubric(CreateUpdateMixin): """ Model definition for Rubric. """ short_description = models.CharField(max_length=100) long_description = models.CharField(max_length=250) growthplan_count = models.IntegerField() report_url = models.CharField(max_length=350) domains = models.ManyToManyField(Domain) active = models.BooleanField(default=False) class Summative(CreateUpdateMixin, CreateUpdateUserMixin): """ Model definition for Summative. """ end_year = models.ForeignKey(Year, on_delete=models.PROTECT) rubric = models.ForeignKey(Rubric, on_delete=models.PROTECT) locked = models.BooleanField(default=False) employee = models.ForeignKey( User, on_delete=models.PROTECT, related_name="%(class)s_employee" ) admin_locked_on = models.DateTimeField( auto_now=False, auto_now_add=False, blank=True, null=True ) report_url = models.CharField(max_length=350, blank=True) class Subdomain(CreateUpdateMixin): """ Model definition for Subdomain. """ domain = models.ForeignKey(Domain, on_delete=models.PROTECT) short_description = models.CharField(max_length=100) long_description = models.CharField(max_length=250) character_code = models.CharField(max_length=5) proficiency_levels = models.ManyToManyField(ProficiencyLevel) class ProficiencyLevel(CreateUpdateMixin): """ Model definition for SubdomainProficienyLevel. """ name = … -
How to send the image uploaded in frontend in javascript to AWS S3 in Django?
I have a web app, frontend using HTML5, backend using Django. In the frontend, there's an upload button, which is supposed to upload the image to AWS S3. Now I could only upload the image using that button, but I do not know how to save it to AWS S3 via Django. How could I do that? <script> function renderCover(value, row) { return '<input accept="image/*" type="file" id="files" />\n' + '<img id="image" />' } function handleFileSelect (evt) { // Loop through the FileList and render image files as thumbnails. for (const file of evt.target.files) { // Render thumbnail. const span = document.createElement('span'); const src = URL.createObjectURL(file); span.innerHTML = `<img style="height: 75px; border: 1px solid #000; margin: 5px"` + `src="${src}" title="${escape(file.name)}">`; document.getElementById('list').insertBefore(span, null) } } </script> -
How to Import data from an App class field to another app class field Django
I have been having this one problem, i need to make a ERP app, that requires a few data from the client at first, and eventually, more data has to be included to this same client form Client models.py class Cliente(models.Model): genero_choices = ( ("M","Masculino"), ("F","Feminino"), ("O","Prefiro não dizer"), ) client_id = models.AutoField(primary_key=True, editable=False) nome_cliente = models.CharField(max_length=500, null=False, blank=False) cpf = models.CharField(_('CPF'),max_length=15,null=True,blank=True) rg = models.CharField(_('RG'),max_length=15,null=True,blank=True) endereco = models.CharField(_('Endereço'),max_length=100,null=True,blank=True) procedencia = models.ForeignKey("Entrada", on_delete=models.RESTRICT, null=False,blank=False) telefone = models.CharField(_('Telefone'),max_length=18, null=False, blank=False) telefone2 = models.CharField(_('Telefone 2'),max_length=18, null=True, blank=True) email_cliente = models.EmailField(max_length=255) genero_cliente = models.CharField(max_length=1,choices=genero_choices) dt_cadastro = models.DateField(auto_now=True, null=False, blank=False) cliente_is_active = models.BooleanField(null=False, blank=False) anexos_cliente = models.FileField(blank=True,null=True) loja = models.ForeignKey(Loja,on_delete=models.RESTRICT, null=True,blank=True) vendedor_resp = models.ForeignKey(Funcionario,on_delete=models.RESTRICT, null=True,blank=True,limit_choices_to=Q(cargo=2)) observacoes = models.CharField(_('Observações'),max_length=500,null=True,blank=True) def __str__(self): return f"{self.nome_cliente}" Client admin.py from clientes.models import Cliente,Entrada # Clientes Admin class ClienteAdmin(admin.ModelAdmin): list_display = ('nome_cliente', 'telefone','genero_cliente','procedencia', 'vendedor_resp','loja','observacoes') I need to Import most of the models.py Cliente class to another appm that follows: Comercial models.py class Simulacao (models.Model): contrato_choices = ( ("Normal","Normal"), ("Futura","Futura"), ("Mostruario","Produto de Mostruário"), ) forma_pag_choices = ( ("Cartão de Crédito","Cartão de Crédito"), ("Cartão de Débito","Cartão de Débito"), ("Cheque","Cheque"), ("Dinheiro","Dinheiro"), ("Boleto Financeira","Boleto Financeira"), ("Boleto Loja","Boleto Loja"), ("Boleto ElevenCred","Boleto ElevenCred"), ("Transferência PIX","Transferência PIX"), ("Transferência DOC","Transferência DOC"), ("Transferência TED","Transferência TED") ) parcelamento_lista = [] for … -
Django accepts special characters on url
Im trying to reach a path but not working as i want. What i want is to go a specific section of the page, which i can reach using bootstrap with an address like: <a href="#formt"> but as you may know, django turns # into %23 and what i get in the Browser's url is www.misite.com/chg-profil/%23formt and with this address, i can´t reach my target. In my urls.py: path('chg-profil/', Formt.as_view(),name='chg-profil'), In my template.html: <a class="nav-link" href="{%url 'chg-profil/#formt'%}"> -
replacing values in SQL Queries
I created an app to print a Trial Balance from some database items as per the below code. It currently prints out like the following example: how would I be able to replace the '0' in the table with blank spaces so that its would display like: Views.py def Kyletrb(request): all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] '\ 'Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = PostGL.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType' cursor = cnxn.cursor(); cursor.execute(all); xAll = cursor.fetchall() cursor.close() xAll_l = [] for row in xAll: rdict = {} rdict["Description"] = row[0] rdict["Account"] = row[1] rdict["Credit"] = row[2] rdict["Debit"] = row[3] xAll_l.append(rdict) creditTotal = ' Select ROUND(SUM(Credit) , 2) FROM [Kyle].[dbo].[PostGL] WHERE Credit <> 0.0' cursor = cnxn.cursor(); cursor.execute(creditTotal); xCreditTotal = cursor.fetchone() debitTotal = ' Select ROUND(SUM(Debit) , 2) FROM [Kyle].[dbo].[PostGL] WHERE Debit <> 0.0' cursor = cnxn.cursor(); cursor.execute(debitTotal); xDebitTotal = cursor.fetchone() return render(request , 'main/Kyletrb.html' , {"xAlls":xAll_l , 'xCreditTotal':xCreditTotal , 'xDebitTotal':xDebitTotal}) HTML: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous"> {% extends "main/base.html"%} {% block content%} <h1 class = 'center'>Kyle Database Trial Balance</h1> <br> <style> .img-container { width: 150px; height: 100px; } </style> <style> .center{ text-align: center; } </style> <style> .table-container{ … -
Field 'id' expected a number but got '8c744bf0-1f7e-4ed9-a2b5-9a8155adb4b5'
I have a little problem with my 'id'. I don't know how to do to get the correct id.I have tried to do this in many ways but stil dont have idea. MODELS class Projekt(models.Model): nazwa_projektu = models.CharField(max_length=200, unique=True) opis_projektu = models.TextField() zdjecie_projektu = models.ImageField(default='project_photo/default.jpg', upload_to="project_photo",blank= True, null=True,validators=[FileExtensionValidator(['png', 'jpg', 'jpeg','gif'])]) wlasciciel = models.ForeignKey(Profil, on_delete=models.CASCADE) opcja_nr1 = models.CharField(max_length=100, default="111-222-333", blank= True, null=True) opcja_nr2 = models.CharField(max_length=100, default="TwojaNazwa@gmail.com", blank= True, null=True) opcja_nr3 = models.CharField(max_length=100, default="www.TwojaNazwa.com", blank= True, null=True) social_facebook_p = models.CharField(max_length=300, blank= True, null=True) social_www_p = models.CharField(max_length=300, blank= True, null=True) social_instagram_p = models.CharField(max_length=300, blank= True, null=True) social_twitter_p = models.CharField(max_length=300, blank= True, null=True) social_other_p = models.CharField(max_length=300, blank= True, null=True) social_likedin_p = models.CharField(max_length=300, blank= True, null=True) wybor_projekt = models.CharField(max_length=100, choices=wybor_t_f, default="FALSZ") id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.nazwa_projektu) class Srodek(models.Model): wlasciciel = models.ForeignKey(Profil, on_delete=models.CASCADE) tytul_informacje = models.CharField(max_length=200) dodatkowe_informacje = models.TextField() slider = models.ImageField(default='project_photo/default.jpg', upload_to="inside_photo",blank= True, null=True,validators=[FileExtensionValidator(['png', 'jpg', 'jpeg','gif'])]) baner = models.ImageField(default='project_photo/default.jpg', upload_to="baner",blank= True, null=True,validators=[FileExtensionValidator(['png', 'jpg', 'jpeg','gif'])]) reklama_1 = models.ImageField(default='project_photo/default.jpg', upload_to="ad_1",blank= True, null=True,validators=[FileExtensionValidator(['png', 'jpg', 'jpeg','gif'])]) reklama_2 = models.ImageField(default='project_photo/default.jpg', upload_to="ad_2",blank= True, null=True,validators=[FileExtensionValidator(['png', 'jpg', 'jpeg','gif'])]) reklama_3 = models.ImageField(default='project_photo/default.jpg', upload_to="ad_3",blank= True, null=True,validators=[FileExtensionValidator(['png', 'jpg', 'jpeg','gif'])]) reklama_4 = models.ImageField(default='project_photo/default.jpg', upload_to="ad_4",blank= True, null=True,validators=[FileExtensionValidator(['png', 'jpg', 'jpeg','gif'])]) reklama_5 = models.ImageField(default='project_photo/default.jpg', upload_to="ad_5",blank= True, null=True,validators=[FileExtensionValidator(['png', 'jpg', 'jpeg','gif'])]) … -
ERROR: Could not find a version that satisfies the requirement pkg-resources (from versions: none)
Try to run this command from the system terminal. Make sure that you use the correct version of 'pip' installed for your Python interpreter located at 'C:\Users\bbuug\PycharmProjects\core-group-api-dev\venv\Scripts\python.exe'. ERROR: Could not find a version that satisfies the requirement pkg-resources (from versions: none) ERROR: No matching distribution found for pkg-resources -
How to write data from a dict via Django ORM in SQLite?
How the models should look like in Django 1.11 so that I can write this data in them? And how to write this data? { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" } ] [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } ] -
Django DRF serializer with many=true missuses the respective validate()
I have run into the following problem: There are 2 serializers CreateSerializer(child) and BulkCreateSerializer(parent). They are connected via list_serializer_class. I have overridden create() and validate() methods for both serializers and expect them to trigger respectively on whether a single instance is coming via POST or a list of instances. However, when I am sending a post request with a list of instances serializer does switch to many=true but uses validate() that belongs to child CreateSerializer instead of dedicated BulkCreateSerializer, which runs me into errors of course. So my question is, what could be the logic under the hood, that prevents my serializers to distribute the items for validation respectively? serializers.py class RecipeStepDraftBulkCreateSerializer(serializers.ListSerializer): def validate(self, data): print("bulk validate") new_step_numbers = [s.get('step_number') for s in data] if None in new_step_numbers: raise serializers.ValidationError("step_number filed is required") if new_step_numbers != list(set(new_step_numbers)): raise serializers.ValidationError("Wrong order of step_number(s) supplied") try: recipe = Recipe.objects.get(pk=self.context.get('recipe_id')) existing_steps = recipe.recipe_steps.get_queryset().all() if existing_steps: ex_step_numbers = [s.step_number for s in existing_steps] if new_step_numbers[0] != ex_step_numbers[-1] + 1: raise serializers.ValidationError( f"The next first supplied step_number must be: {ex_step_numbers[-1] + 1}") steps_combined = ex_step_numbers + new_step_numbers if steps_combined != list(set(steps_combined)): raise serializers.ValidationError(f"Wrong order of step_number(s) supplied") return data except ObjectDoesNotExist: raise serializers.ValidationError("Recipe under provided … -
Django executing shell script from views and not to wait until the executed script finishes
Currently I am working on a django project where I would like to kick off a python shell script to execute some tasks from one of my views in the Django application. What I am trying to achive is from my Django application when I call a view function it executes the shell script but not to wait until the shell script finishes. So the Django app finishes with the request but in the background the kicked off process is still progressing. So the Django app while the kicked off process is runing is able to receive new requests. Is there any way to do this or any better way to kick of separate processes from Django and monitor the status of them? What I tried: def example_view(request): os.system("my shell script") "Code does not step to the next instruction while os.system is running" -
what are the best practices for bulk upload of .csv file in Django using?
I have a simple CSV file upload module to bulk upload my POS data. Sample Code below.. models.py class POSData(models.Model): outlet_name = models.CharField(...) food_item = models.ForeignKey('FoodItem', ...) order_date = models.DateField(...) ... class Ingredient(models.Model): ingredient_name = models.CharField(...) ... class FoodItem(models.Model): item_name = models.CharField(...) item_key = models.IntegerField(unique=True) ... class RecipeItem(models.Model): food_item = models.ForeignKey(FoodItem, ...) ingredient = models.ForeignKey(Ingredient, ...) quantity = models.Charfield(...) ... class POSIngredientData(models.Model): outlet_name = models.CharField(...) ingredient = models.ForeignKey(Ingredient, ...) quantity = models.Charfield(...) order_date = models.DateField(...) ... views.py #Code sample for handling .csv file upload file = request.FILES['order_file'] decoded_file = file.read().decode('utf-8').splitlines() # creating a csv dictionary reader object csvDictReader = csv.DictReader(decoded_file, delimiter=',') for obj in csvDictReader: try: food_item = FoodItem.objects.get(item_key=obj['item_key']) except FoodItem.DoesNotExist: # Do Something Here pass POSData.objects.create(food_item=food_item, ...) recipesItemQS = RecipeItem.objects.filter(food_item=food_item) # uploading POS data of ingredients in separate model to help in qs # Average 10 ingredients in a foodItem recipe for recipeItem in recipesItemQS: POSIngredientData.objects.create(ingredient=recipeItem.ingredient, ...) My question is that, it takes too long to upload all the data to database(5-10 seconds to upload one row of .csv file). Is there any more efficient way to upload bulk data from .csv file? Also, I read somewhere that the Model.save() method should be used instead of Model.create() for bulk … -
How to Fix "django channels", Failed to build cryptography?
i try to install django channels and i get this error how to fix it ? =============================DEBUG ASSISTANCE============================= If you are seeing a compilation error please try the following steps to successfully install cryptography: 1) Upgrade to the latest pip and try again. This will fix errors for most users. See: https://pip.pypa.io/en/stable/installing/#upgrading-pip 2) Read https://cryptography.io/en/latest/installation.html for specific instructions for your platform. 3) Check our frequently asked questions for more information: https://cryptography.io/en/latest/faq.html 4) Ensure you have a recent Rust toolchain installed: https://cryptography.io/en/latest/installation.html#rust 5) If you are experiencing issues with Rust for this release only you may set the environment variable CRYPTOGRAPHY_DONT_BUILD_RUST=1. =============================DEBUG ASSISTANCE============================= error: command 'i686-linux-gnu-gcc' failed with exit status 1 ERROR: Failed building wheel for cryptography Failed to build cryptography ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly -
Embed Tiktok or Instagram videos with URL
I have a blog where the user can enter a video-url to his/her post and after publishing the link should display the related video. Let's pretend the user add a tiktok video (https://www.tiktok.com/@jenniferivanareina/video/7002323620630449413?sender_device=pc&sender_web_id=6924717302906996229&is_from_webapp=v1&is_copy_url=0). Now the video couldn't be display with a video or iframe tag. <video src="video_link_here"></video> It results in an error: Refused to display 'https://www.tiktok.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'. Same happend with Instagram videos. I'm trying to not let the user enter the embed code because I don't want to execute unknown html code from the user (security aspects). Is there a solution for my problem? I use Django v3.2 to store the video URLs and frontend is html,css,js. -
Unable to get data as same in AGGRID table when exporting in xlsx or csv using Reactjs
Unable to get data as same in AGGRID table when exporting in xlsx or csv. If we have number column has 20 characters last 5 digits are becoming zero while exporting as xlsx or csv. -
how do you calculate number of visits for all pages in the database
Assuming you have a Page model with a '''visits_count (IntegerField)''' field, how do you calculate the arithmetic mean of the number of visits for all pages in the database? -
A good way to detect alpha channel in a video using ffmpeg/ffprobe
In my Django application, uploaded video files are transcoded into some particular format using ffmpeg. I now need a way to reliably detect whether uploaded videos have alpha channel or not. I normally use ffprobe for getting video metadata. Could you point me in the right direction? -
I tried Datatable adding to a form not working as POST method django
I want show my table as Datatable and also want to accept values from there, So I tried my form in a table but when I am trying to access the values the post method isn;t working. What can be cahnged here ? it works when I remove the script below but dosen't work when I add the script. HTML code <form class="form form-control" method="POST"> {% csrf_token %} <thead> <tr align="center"> <th> Item Code </th> <th> Name </th> <th> Check Number </th> <th> Submit </th> </tr> </thead> {% if bomlist %} <tbody> {% for bom in bomlist %} <tr align="center"> <td> {{ bom.code }} </td> <td> <input value="{{bom.code}}" name="bom" hidden/> {{bom.name}} </td> <td> <input class="text text-center form-sm" type="number" name="number" min="1"/> </td> <td> <button type="submit" class="btn btn-primary"> Submit </button></td> </tr> {% endfor %} </tbody> {% endif %} </form> </table> Jquery <script type="text/javascript"> $(document).ready(function () { $('#bomtable').DataTable(); }); </script>