Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework doesn't commit data to sqlite3 via POST untill server restarted
I just started to study django rest framework and encountered with problem. Here is my code (views.py, urls.py, models.py, serializers.py): #view.py: class AllData(viewsets.ModelViewSet): queryset = Run.objects.all() serializer_class = RunSerializer def get_queryset(self): queryset = self.queryset start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') if start_date is not None and end_date is not None: queryset = queryset.filter(Q(date__gte=start_date) & Q(date__lte=end_date)) return queryset #serializers.py: class RunSerializer(serializers.ModelSerializer): class Meta: model = Run fields = '__all__' #models.py: class Run(models.Model): date = models.DateField() distance = models.DecimalField(max_digits=5, decimal_places=3) time = models.SmallIntegerField() def __str__(self): return str(self.distance) #urls.py: router = DefaultRouter() router.register('all_runs', AllData, basename='all_runs') urlpatterns = [ path('average_data/', AverageData.as_view(), name='average_data'), ] urlpatterns += router.urls So, i started with http://127.0.0.1:8000/all_runs/ and it works. http://127.0.0.1:8000/all_runs/1 or something else - too. (i have added some data already). I see POST, DELETE options, etc. in drf web interface. But...if i add data via POST: i see "POST /all_runs/ HTTP/1.1" 201 9187 - seems like OK. try to http://127.0.0.1:8000/all_runs/ again... and don't see added data! restart server (django by default, sqlite3, etc.) and... see added data! Seems like POST works, but i see data after re-starting server only in web-interface of drf. Same problems with Postman. Please, help. What is wrong in my code or common settings … -
Django: Implementing Group_Concat with optional separator with SQLITE
While Django implementation of Group_Concat on my_sql or mariaDB seem to be well documented, I am not able to make Group_Concat work in Django with optional separator on SQLITE. class GroupConcat(Aggregate): function = 'GROUP_CONCAT' separator = '-' def __init__(self, expression, separator='-', distinct=False, ordering=None, **extra): super(GroupConcat, self).__init__(expression, distinct='DISTINCT ' if distinct else '', ordering=' ORDER BY %s' % ordering if ordering is not None else '', output_field=CharField(), **extra) self.separator = separator It works well with the default separator ',' when using the distinct option def as_sqlite(self, compiler, connection, **extra_context): if self.separator: return super().as_sql( compiler, connection, separator=self.separator, template="%(function)s(%(distinct)s%(expressions)s)", **extra_context ) I figured out that with SQLITE, we can not use both distinct and declare separator, but I don't understand why it does not work without the distinct as in: def as_sqlite(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, separator=self.separator, template="%(function)s(%(expressions)s,%(separator)s)", **extra_context ) Whatever I try, I always end-up with an error: File "C:\Users\Gil\Gilles\Perso\Maison\Projets perso\Formacube\Formacube test App\Github_FormApp\FormApp\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: near ")": syntax error -
unable to view my model objects in django using cbv
i am unble to view my model item in django i did everthing right but my model item i not showing my model class Quote(models.Model): todays_Quote = models.CharField(max_length=500, blank=False) by = models.CharField(max_length=100, blank=False) created = models.DateTimeField(auto_now=True) def __str__(self): return self.todays_Quote my views class home(View): def get(self, request): quote = Quote.objects.all() return render(request, 'home.html', {'qoutes':quote}) my html for rendering it <section> <div class="col-11"> <div class="text-center"> {% for Quote in quotes %} <h1>{{ Quote.todays_Quote }} hello</h1> <p style="float: right;">{{ Quote.by }}</p> <p>Todays Date :- <span id="date"></span></p> {% endfor %} </div> </div> </section> any idea what wrong in that & yes i did the migration -
Django save-Making Two Orders on single click
i have created my ecommerce platform. Whenever I click the order-now-buttons, it makes two orders in my backend, I don't see where the error comes from. But it outputs a complete and incomplete, order.Here is my view.py makeorder function def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) print(data) if request.user.is_authenticated: customer = request.user order, created = Order.objects.get_or_create( customer=customer, complete=False) total = order.get_cart_totals order.transaction_id = transaction_id if total == order.get_cart_totals: order.complete = True print("Total equals") order.save() if order.shipping == True: print("Wrong") ShippingAddress.objects.create( customer=customer, order=order, firstname=data['shipping']['firstname'], lastname=data['shipping']['lastname'], address=data['shipping']['address'], city=data['shipping']['city'], zipcode=data['shipping']['zipcode'] ) else: print("User doesn't exist") print('Data:', request.body) return JsonResponse('Payment Submitted', safe=False) I know the error is inside my function, but i cant figure it out Thanks for your help in advance -
How to add pagination : super()
I am trying to add pagination using super().list() method in modelviewset def list(self, request, **kwargs): print('list') try: if 'learner_id' in kwargs: learner_id = self.kwargs.get('learner_id') else: learner_id = request.learner.id details = RecentlyViewedVideos.objects.filter(learner_id=learner_id) response_data = super().list(details, kwargs) in output, it displays all the documents in the table, but I only need those details in the "details", give me a way to get the exact output. -
Programming Error with the Alias of my SQL Query
I am getting the below error for the below SQL query, I am pretty sure it has something to do with the Alias given to PostGl. I just don't know how to correct it. Query: all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] AS genLedger'\ 'Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = PostGL.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType'\ 'WHERE genLedger.AccountLink <> 161 OR 162 OR 163 OR 164 OR 165 OR 166 OR 167 OR 168 OR 122 ' Error : ProgrammingError at /Kyletrb ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'genLedger'. (102) (SQLExecDirectW)") -
how to show api end in swagger ui that has auth required after authentication django
is there any way to show an auth-required api endpoint in the swagger UI after successfully authentication of the user? -
Django Python With Gspread: 'choices' must be an iterable containing (actual value, human readable name) tuples
I am trying to do something that I have never seen done before with django, I am trying to make a model field(path_choices) that shows all of the unique path_names from my google sheet in a choice box so that the user can select one of them. However when I tried to make my choices CharField I am getting the error: ERRORS: dashboard.Robot.path_choices: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. Right now the google sheet that I am trying to pull from with gspread only has two path-names, so if anybody has any idea on what is causing this problem or what I can do better with this, the help would be appreciated! My Code: from django.db import models import gspread from oauth2client.service_account import ServiceAccountCredentials class Robot(models.Model): name = models.CharField(max_length=100) status_choices = [('driving', 'driving'), ('waiting', 'waiting'), ('stuck', 'stuck')] status = models.CharField(choices=status_choices, max_length=7, default='waiting') scope = ["REDACTED",'REDACTED',"REDACTED","REDACTED"] creds = ServiceAccountCredentials.from_json_keyfile_name("dashboard/Files/creds.json", scope) client = gspread.authorize(creds) sheet = client.open("tutorial").sheet1 path_name_fetch = sheet.col_values(1) path_names = [] temp_list = [] path_options = [] for i in path_name_fetch: if i not in path_names: path_names.append(i) for path_name_options in path_names: temp_list.append(f'{path_name_options}') temp_list.append(f'{path_name_options}') path_options.append(tuple(temp_list)) path_choices = models.CharField(choices=path_options, max_length=20, default='Default') -
Errno 2 No such file or directory in django
When I try to run server in django writing python manage.py runserver , python gives an error which is C:\Users\Alim Írnek\AppData\Local\Programs\Python\Python39\python.exe: can't open file 'C:\Users\Alim ├ûrnek\PycharmProjects\mysite\manage.py': [Errno 2] No such file or directory Is it because of spaces in my username or something else? -
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" } ]