Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Failed to change read-only flag pycharm in ubuntu
When I try to write something in file it show error "Failed to change read-only flag from pycharm in ubuntu" -
Google one tap Login With Django ( The given origin is not allowed for the given client ID issue )
I'm trying to connect Google One Tap Login with Django framework, but I'm having issue. I'm not sure why this is displaying an issue. I followed all of the guidelines described in the Google documentation. issue - The given origin is not allowed for the given client ID Here is my Google API client configuration for the javascript origin url. Here is the login html template code. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Hi Reddit</h1> <script src="https://accounts.google.com/gsi/client" async defer></script> <div id="g_id_onload" data-client_id="i don't want to shere" data-context="signin" data-ux_mode="popup" data-login_uri="http://localhost:8000/google/login/" data-auto_select="true" data-itp_support="true"> </div> <div class="g_id_signin" data-type="standard" data-shape="pill" data-theme="outline" data-text="continue_with" data-size="large" data-logo_alignment="left"> </div> </body> </html> </body> </html> I'm not sure why this is displaying an issue. Is it possible to load Google One Tap Javascript in Django? What should I do to load Google One Tap Javascript in Django? -
Django if statement is not working inside a html tag
(https://i.stack.imgur.com/tGf0u.jpg) I am trying to execute if statement in html file inside Js block in which I am writing JavaScript code. When I am trying to insert if statement is showing Expression Expected but if statement is written outside tag it is working. I tried to write it outside tag it is working but inside tag it is not working. -
Object update by PATCH for Django REST Framework
I am using viewsets.ModelViewSet from rest_framework import viewsets class ProjectViewSet(viewsets.ModelViewSet): serializer_class = s.ProjectSerializer queryset = m.Project.objects.all() def patch(self,request,*args,**kwargs): instance = self.get_object() serializer = self.get_serializer(instance,data = request.data) if serializer.is_valid(): self.perform_update(serializer) return Response(serializer.data) return Response() Then I test to update the object via django restframework UI. Then this error occurs. My basic idea that changing object data via PATCH is correct? How can I update the data via Django REST Framework Expected view ProjectViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. -
Selenium in Django on Linux - Ubuntu
I have problem with python selenium in Django when my project run on apache2 - Ubuntu Desktop. My app send forms to selenium script which reset user password. If im running server like this python3 manage.py runserver everything is fine and works good. When app works on apache i got error like this: Exception Type: TimeoutException Exception Value: Message: Failed to read marionette port Im sending forms - "name" and "ID" from function 'submitmyfrom' to 'reset_user_pw'. view.py: def submitmyfrom(request): form = FormsReset(request.POST) my_name = request.POST['name'] my_id = request.POST['id'] ip = request.META.get('REMOTE_ADDR') if len(id) < 12: passwd = reset_user_pw(user_name=my_name) mydictionary = { "my_name" : my_name, "my_id" : my_id, 'password' : passwd } return render(request,'submitmyfrom.html', context=mydictionary) reset_user_pw: def reset_user_pw(user_name): os.environ['MOZ_HEADLESS'] = '1' pwd = mypwd LoginName = "login" user_login = user_name cert = webdriver.FirefoxProfile() cert.accept_untrusted_certs = True web = webdriver.Firefox(executable_path='/var/www/my_project/src/geckodriver', log_path='/var/www/my_project/src/Reset/geckodriver.log', service_log_path='/var/www/my_project/src/myapp/geckodriver.log') web.get('https://example.com/test') time.sleep(1) next is the rest of the function reset_user_pw I use firefox and would ideally like to stay with it What can i do to make it on apache2. I remind you that the python3 manage.py runserver run fine -
I can't pass values to database with Ajax and Django
i'm new in Ajax and Django i'm try sent videoP1 = 1 when percentage = 100 i'm use script tag on html to write js To get videoP1-videoP17 from database via views.py to set value in array and call it. var videos = [ { id: 1, name: "1", src: "../static/frontend/video/1.mp4", videoP1: {{ video_db.videoP1 }}, }, { id: 2, name: "2", src: "../static/frontend/video/2.mp4", videoP2: {{ video_db.videoP2 }}, }, { id: 17, name: "17", src: "../static/frontend/video/17.mp4", videoP17: {{ video_db.videoP17 }}, }, ]; var player = videojs("videoP"); function light(Cvideo) { for (let i = 0; i < videos.length; i++) { let video = videos[i]; if (videos[i].id === Cvideo) { document.getElementById("nameV").innerHTML = videos[i].name; player.src({ type: "video/mp4", src: videos[i].src }); player.play(); if (!video["videoP" + (i + 1)]) { player.controlBar.progressControl.hide(); player.on("timeupdate", function() { var percentage = (player.currentTime() / player.duration()) * 100; document.getElementById("percentage").innerHTML = Math.round(percentage) + "%"; if (percentage === 100) { video["videoP" + (i + 1)] = 1; var videopro = video["videoP" + (i + 1)] = 1; $.ajax({ type: "POST", url: "/update-video-progress/", data: { video_id: video.id, videoPro: videopro, }, success: function(response) { console.log("Video progress updated"); }, error: function(xhr, textStatus, errorThrown) { console.error("Failed to update video progress"); }, }); return; } }); } else { … -
Django Views which one should I follow? [closed]
I'm new to Django framework I'm confused about the difference in which one I should follow use. Many developers use "django.views import View" and some are using "django.views.generic import ListView ..." which one is optimized in both of them? I know their output are the same but which one should I follow? from django.views import View .... class HomePage(View): def get(self, request): posts = Post.object.all().order_by('created') context = {'posts':posts} return render(request, 'html/homepage.html', context) or this one class HomePage(ListView): model = Post template_name = 'html/homepage.html' context_object_name = 'posts' ordering = ['created'] paginate_by = 3 -
How to get specific objects based on ManyToMany field match
I'm doing a cookbook app, which help users find meal thay can do with their ingridients. I'm using Django RestFramework, and i need to return list of avaliable meals that user can do, but don't know how to do search by ingridients My models.py: #models.py class Meal(models.Model): name = models.CharField(max_length=250) description = models.TextField(blank=True, null=True) recipe = models.TextField() is_published = models.BooleanField(default=False) category = ForeignKey('Category', on_delete=models.CASCADE, null=True) user = ForeignKey(User, verbose_name='User', on_delete= models.CASCADE) difficulty = ForeignKey('Difficulty', on_delete=models.PROTECT, null=True) ingridients = models.ManyToManyField('Ingridient') class Ingridient(models.Model): name = models.CharField(max_length=100, db_index=True) ico = models.ImageField(upload_to="photos/%Y/%m/%d/", blank=True, null=True) category = ForeignKey('CategoryIngridients', on_delete=models.CASCADE, null=True) def __str__(self): return self.name class CookBookUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ingridients = models.ManyToManyField('Ingridient') serializer.py class MealSerializer(serializers.ModelSerializer): class Meta: model = Meal fields = "__all__" views.py class CraftWithUsersIngridientsListAPIView(generics.ListAPIView): serializer_class = MealSerializer def get_queryset(self): return Meal.objects.filter(ingridients=CookBookUser.objects.filter(user_id = self.request.user.id).ingridients) CraftWithUsersIngridientsListAPIView isn't working and I get AttributeError 'QuerySet' object has no attribute 'ingridients', can someone help fix this? I tried building different serializer but it doesn't help -
Annotate over multiple Foreign keys of the same type in one model
I have the following models. I absolutely have to use multiple foreign keys instead of a many-to-many field. class Job(models.IntegerChoices): ADMIN = (0, "Admin") ARCHITECT = (1, "Architect") ENGINEER = (2, "Engineer") class Employee(models.Model): job = models.IntegerField(_("Job"), choices=Job.choices) salary = models.DecimalField(_("Salary"), max_digits=12, decimal_places=4) class Company(models.Model): name = models.CharField(...) employee_one = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True) employee_two = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True) employee_three = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True) ... employee_ten = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True) I want to get the total salary for each job, as in the following format: {'name': 'MyCompany', 'admin_total': 5000, 'architect_total': 3000, 'engineer_total': 2000}. I do this by iterating through each of the ten employees, checking their role and adding them together if they have the same role: Company.objects.all().annotate( admin_one=Case( When(employee_one__job=Job.ADMIN, then=F("employee_one__salary")), default=0, output_field=models.DecimalField(max_digits=12, decimal_places=4), ), admin_two=Case( When(employee_two__job=Job.ADMIN, then=F("employee_two__salary")), default=0, output_field=models.DecimalField(max_digits=12, decimal_places=4), ), ..., admin_total=F("admin_one") + F("admin_two") + ... + F("admin_ten"), ) As you can see this is just a very long query and it is only including the one of the three total salaries. And if another job is added, the annotation will just get longer. Is there a more efficient way to do this? -
ValueError at /approve/2/ Field 'id' expected a number but got ''
I am workin on a projec using modelformset to render multiple instance of a model and whenever i try to update my data, i get the error below. Template error: In template /home/dubsy/virtualenvs/djangoproject/libmain/templates/books/approve.html, error at line 67 Field 'id' expected a number but got ''. 57 : <thead> 58 : <tr> 59 : <th>Book Title</th> 60 : <th>Approved</th> 61 : <th>Not Approved</th> 62 : </tr> 63 : </thead> 64 : <tbody> 65 : {% for form in formset %} 66 : <tr> 67 : <td> {{ form.instance.book.title }} </td> 68 : <td>{{ form.approved }}</td> 69 : <td>{{ form.not_approved }}</td> 70 : </tr> 71 : {% endfor %} 72 : </tbody> 73 : </table> 74 : <button type="submit">Update</button> 75 : </form> 76 : 77 : </body> Exception Type: ValueError at /approve/2/ Exception Value: Field 'id' expected a number but got ''. I have tried using the users context in views.py to render out the form which works fo book title but doesn't work for the two input field as it renders out the value from database instead of a checkbox input field Here is my views.py def approve(request,pk): users = PendingRequest.objects.filter(member__id=pk) RequestFormset = modelformset_factory(PendingRequest, fields=("approved", "not_approved"),extra=0) if request.method == "POST": formset … -
django_plotly_dash: error exporting to pdf with html2pdf.js
I am trying to export a django_plotly_dash dashboard to pdf and can't quite get it. I am stuck with the following error in console when clicking on the button to trigger the export: ReferenceError: html2pdf is not defined at Object.nClicksToPDF [as n_clicks] which is telling me that html2pdf cannot be found. I have tried importing in assets folder as well as cdn directly in the app layout but nothing seems to do the trick and I am out of things to try: here is how I import it in the app: html.Script(src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"), here is my callback where it is called: app.clientside_callback( """ function nClicksToPDF(n_clicks){ if(n_clicks > 0){ document.querySelector('.chkremove').style.display = 'none'; const opt = { margin: 2, filename: 'myfile.pdf', image: { type: 'jpeg', quality: 0.98 }, html2canvas: { scale: 1}, jsPDF: { unit: 'cm', format: 'a2', orientation: 'p' }, pagebreak: { mode: ['avoid-all'] } }; console.log('ok') html2pdf().from(document.getElementById("print")).set(opt).save(); setTimeout(function(){ document.querySelector('.chkremove').style.display = 'block'; }, 2000); } } """, Output('js','n_clicks'), Input('js','n_clicks') ) Don't know what else to do, any help would be highly welcome! -
Django - overload post on UpdateView so it auto completes some fields
So I have this view: class ProfileView(generic.UpdateView): model = User fields = [....] template_name_suffix = '_update_form' success_url = reverse_lazy('home') def post(self, request, *args, **kwargs): self.object = self.get_object() self.object.is_active = False return super().post(request, *args, **kwargs) when the user saves his data on update, I want some fields to be completed automatically, such as is_active = False. I used the approach above but my inserted fields aren't changed. Why and how can I get the desired result? Thanks. -
Django views.py Exception Value: Could not parse the remainder:
Good afternoon. Tell me, please, what could be the matter - I get an Exception Value error: Could not parse the remainder: '(column)' from 'item.get(column)' views.py : def home(request): position = DjangoEmail.objects.get(Email=request.user).Position year_filter = Q(Year=now.year) | Q(Year=now.year-1) | Q(Year=now.year+1) if position == 7: data = Employee.objects.filter(year_filter, Mlkk=request.user).order_by('Year','OblastTM').values('Year', 'OblastTM', 'Category', 'ProductGroup','NameChaine').annotate(Januaru=Sum('January')) elif position == 6: data = Employee.objects.filter(year_filter, Rmkk=request.user).order_by('Year','OblastTM').values('Year', 'OblastTM', 'Category', 'ProductGroup','NameChaine').annotate(Januaru=Sum('January')) elif position == 5: data = Employee.objects.filter(year_filter, Dmkk=request.user).order_by('Year','OblastTM').values('Year', 'OblastTM', 'Category', 'ProductGroup','NameChaine').annotate(Januaru=Sum('January')) else: data = Employee.objects.filter(year_filter).order_by('Year','OblastTM').values('Year', 'OblastTM', 'Category', 'ProductGroup','NameChaine').annotate(Januaru=Sum('January')) columns = ['Year', 'OblastTM', 'Category', 'ProductGroupe', 'NameChaine','January'] removed_columns = request.GET.getlist('remove') columns = [column for column in columns if column not in removed_columns] return render(request, "home.html", {'data': data, 'columns': columns}) home.html : <table> <thead> <tr> {% for column in columns %} <th>{{ column|title }}</th> {% endfor %} </tr> </thead> <tbody> {% for item in data %} <tr> {% for column in columns %} <td>{{ item.get(column)}}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> error : Exception Value:Could not parse the remainder: '(column)' from 'item.get(column)' Error in the line : <td>{{ item.get(column)}}</td> I tried to replace it with {{ item[column] }} - it didn't help. -
makemigrations command doesn' work in Django Project when using sqlalchemy
I took over a django project which doesn't use the models.py under /myapp folder but a customed file Models.py under /myapp/classModel using sqlalchemy. I changed the database structure in /myapp/classModel/Models.py and imported it to /myapp/models.py, then ran python manage.py makemigrations. Only to get message No changes detected . I wonder if this is the correct way to do migration? Any help is appreciated -
Hosting Firebase Django Welcome Page
I ran all the commands need like npm install -g firebase-tools firebase login firebase init firebase deploy but it still shows me the welcome screen -
Django payload before sending
This is a code to send invoice via , but I cannot enter a " for loop " loop on it to put product name and price and quantity of it , so how to deal with this to put products and other data , I tried to add for loop but it didn't work , ###########Send Payment########### baseURL = "https://apitest.myfatoorah.com" token = 'rLtt6JWvbUHDDhsZnfpAhpYk4dxYDQkbcPTyGaKp2TYqQgG7FGZ5Th_WD53Oq8Ebz6A53njUoo1w3pjU1D4vs_ZMqFiz_j0urb_BH9Oq9VZoKFoJEDAbRZepGcQanImyYrry7Kt6MnMdgfG5jn4HngWoRdKduNNyP4kzcp3mRv7x00ahkm9LAK7ZRieg7k1PDAnBIOG3EyVSJ5kK4WLMvYr7sCwHbHcu4A5WwelxYK0GMJy37bNAarSJDFQsJ2ZvJjvMDmfWwDVFEVe_5tOomfVNt6bOg9mexbGjMrnHBnKnZR1vQbBtQieDlQepzTZMuQrSuKn-t5XZM7V6fCW7oP-uXGX-sMOajeX65JOf6XVpk29DP6ro8WTAflCDANC193yof8-f5_EYY-3hXhJj7RBXmizDpneEQDSaSz5sFk0sV5qPcARJ9zGG73vuGFyenjPPmtDtXtpx35A-BVcOSBYVIWe9kndG3nclfefjKEuZ3m4jL9Gg1h2JBvmXSMYiZtp9MR5I6pvbvylU_PP5xJFSjVTIz7IQSjcVGO41npnwIxRXNRxFOdIUHn0tjQ-7LwvEcTXyPsHXcMD8WtgBh-wxR8aKX7WPSsT1O8d8reb2aR7K3rkV3K82K_0OgawImEpwSvp9MNKynEAJQS6ZHe_J_l77652xwPNxMRTMASk1ZsJL' def send_payment(): url = baseURL + "/v2/SendPayment" payload = "{\"CustomerName\": \"Ahmed\",\"NotificationOption\": \"ALL\",\"MobileCountryCode\": \"+965\"," \ "\"CustomerMobile\": \"12345678\",\"CustomerEmail\": \"xx@yy.com\",\"InvoiceValue\": 100," \ "\"DisplayCurrencyIso\": \"KWD\",\"CallBackUrl\": \"https://google.com\",\"ErrorUrl\": " \ "\"https://google.com\",\"Language\": \"en\",\"CustomerReference\": \"ref 1\",\"CustomerCivilId\": " \ "12345678,\"UserDefinedField\": \"Custom field\",\"ExpireDate\": \"\",\"CustomerAddress\": {\"Block\": " \ "\"\",\"Street\": \"\",\"HouseBuildingNo\": \"\",\"Address\": \"\",\"AddressInstructions\": \"\"}," \ "\"InvoiceItems\": [{\"ItemName\": \"Product 01\",\"Quantity\": 1,\"UnitPrice\": 100}]} " headers = {'Content-Type': "application/json", 'Authorization': "Bearer " + token} response = requests.request("POST", url, data=payload, headers=headers) print("Send Payment Response:\n" + response.text) I tried this and made for loop but it didn't work url = baseURL + "/v2/SendPayment" sss={'ItemName': 'product 01', 'Quantity': 30, 'UnitPrice': 10,}, payload={ "CustomerName": "name", # Mandatory Field ("string") "NotificationOption": "SMS", # Mandatory Field ("LNK", "SMS", "EML", or "ALL") "InvoiceValue": 300, # Mandatory Field (Number) # Optional Fields "MobileCountryCode": "+966", "CustomerMobile": "12345678", #Mandatory if the NotificationOption = SMS or ALL # "CustomerEmail": "mail@company.com", #Mandatory if … -
django-environ and Postgres environment for docker
I am using django-environ for my Django project. I provided the DB url in the .env file, which looks like this: DATABASE_URL=psql://dbuser:dbpassword@dbhost:dbport/dbname Then, I created a docker-compose.yml where I specified that my project uses Postgres database, i.e.: version: '3.8' services: ... db image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=??? - POSTGRES_PASSWORD=??? - POSTGRES_DB=??? - "POSTGRES_HOST_AUTH_METHOD=trust" How do I provide these POSTGRES_* env. variables there? Do I need to provide them as separate variables alongside with the DATABASE_URL in my .env file? If yes, what's the best way do accomplish this? I aim to avoid duplication in my settings. -
django form commit=false after how to save many to many field data
Model.py class Branch(models.Model): # Branch Master status_type = ( ("a",'Active'), ("d",'Deactive'), ) name = models.CharField(max_length=100, unique=True) suffix = models.CharField(max_length=8, unique=True) Remark = models.CharField(max_length=200, null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1, choices = status_type, default = 'a') def __str__(self): return self.name class Vendor(models.Model): status_type = ( ("a",'Active'), ("d",'Deactive'), ) branch = models.ManyToManyField(Branch) company = models.CharField(max_length=200) name = models.CharField(max_length=200) phone = models.CharField(max_length=11, unique = True) email = models.EmailField(max_length=254, unique = True) gst = models.CharField(max_length=15, unique = True) pan_no = models.CharField(max_length=10, unique = True) add_1 = models.CharField(max_length=50, null=True, blank = True) add_2 = models.CharField(max_length=50, null=True, blank = True) add_3 = models.CharField(max_length=50, null=True, blank = True) Remark = models.CharField(max_length=200, null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1, choices = status_type, default = 'a') def __str__(self): return self.company form.py class VendorForm(ModelForm): class Meta: model = Vendor fields = 'all' exclude = ['created_by', 'branch'] widgets = { 'company':forms.TextInput(attrs={'class':'form-control'}), 'name':forms.TextInput(attrs={'class':'form-control'}), 'phone':forms.TextInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}), 'gst':forms.TextInput(attrs={'class':'form-control'}), 'pan_no':forms.TextInput(attrs={'class':'form-control'}), 'add_1':forms.TextInput(attrs={'class':'form-control'}), 'add_2':forms.TextInput(attrs={'class':'form-control'}), 'add_3':forms.TextInput(attrs={'class':'form-control'}), 'Remark':forms.Textarea(attrs={'class':'form-control','rows':'2'}), 'status':forms.Select(attrs={'class':'form-control'}), } Views.py I have pass branch in session. I want to save with branch which is many to many field def Add_Vendor(request): # for vendor add msg = "" msg_type = "" … -
Django & SQLite.db - data is duplicated
I created 2 models in the Django framework. The first model is responsible to save emails and the second model to save messages. All emails and messages are saved in the SQLite.db. But when I add the same emails multiple times, the data base creates a new record and I don't have a clue how can I manage saving data to retrieve multiple emails with the same name and then pass them as a one mutual email to the HTML template with all assigned messages to them. An example: I sent 3 messages from test@test.com. Messages: ['Hi', 'Hello', 'Bonjour'] and one message from user@user.com ['Hi'] DB table: Actual result: 3 records test@test.com | 'Hi' test@test.com | 'Hello' test@test.com | 'Bonjour' user@user.com | 'Hi' Then I want to pass all data to the HTML template in order to display them: def emails(request): """Show all emails.""" emails = Email.objects.order_by('date_added') context = {'emails': emails} return render(request, 'home/emails.html', context) HTML portion: <h1>Emails</h1> <ul> {% for email in emails %} <li> <a href="{% url 'home:email' email.id %}">{{ email.text }}</a> </li> {% empty %} <li>No emails have benn added yet.</li> {% endfor %} </ul> But the final result is: test@test.com message_1: Hi test@test.com message_1: Hello test@test.com … -
Cannot correct a failed migration django
I inadvertently did this: ordering = models.IntegerField(default="Order/position") what I meant to do was this: ordering = models.IntegerField(default=0, verbose_name="Order/Position") I ran makemigrations and got no error. When I ran migrate it blew up with the error: ValueError: invalid literal for int() with base 10: 'Order/position' I updated to the correct field definition and while makemigrations is happy and noted the change migrate still keeps throwing that same error. How do I fix this? In case this matters - I am running Django with Postgres and both are in Docker containers -
The model is not displayed in the django admin panel
I don't have the advertisement module displayed in the django admin panel. Here is the model code from django.db import models class Advertisement(models.Model): title = models.CharField(max_length=1000, db_index=True) description = models.CharField(max_length=1000, default='', verbose_name='description') creates_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) price = models.FloatField(default=0, verbose_name="price") views_count = models.IntegerField(default=1, verbose_name="views count") status = models.ForeignKey('AdvertisementStatus', default=None, null=True, on_delete=models.CASCADE, related_name='advertisements') def __str__(self): return self.title class Meta: db_table = 'advertisements' ordering = ['title'] class AdvertisementStatus(models.Model): name = models.CharField(max_length=100) admins.py / from django.contrib import admin from .models import Advertisement admin.site.register(Advertisement) I was just taking a free course from YouTube. This was not the case in my other projects. Here I registered the application got the name in INSTALLED_APPS. Then I performed the creation of migrations and the migrations themselves. Then I tried to use the solution to the problem here , nothing helped. I didn't find a solution in Google search either. -
Import CSV file into model Django
I am trying to enter data using the model in the sqlite3, but I am facing a problem in determining the type of this data. Here is the dataframe: enter image description here I have written the following script: enter image description here When I run the code: .mode csv, then .import data.csv name_of_model I obtained this result: enter image description here I have tried to change the type of database but I still get the same result. -
how to integrate and generate invoices with django?
i am new in django , i would like to integrate an invoice functionality in my pharmacy app , but i have difficulties with table relations and i also lack some inspiration , i would also like to add the elements of my database how the product, the price ... in the invoice but I don't know how to do if you can not only help me solve this but you can also give me ideas for a pharmacy application. thank you in advance! I don't have an idea, I lack an idea to generate invoices for my models file and there from django.db import models class Client(models.Model): name = models.CharField(max_length = 30) date = models.DateTimeField(auto_now_add=True) class Stock (models.Model): balance = models.IntegerField(null=True) date = models.DateTimeField(auto_now_add=True ) class Produit(models.Model): name = models.CharField(max_length=100 , verbose_name= 'Nom') quantite = models.IntegerField(null=True , verbose_name= 'Quantité') price = models.IntegerField(null=True , verbose_name = 'Prix') expiration = models.DateField(null=True , verbose_name= 'Expiration') stock = models.ForeignKey(Stock , blank=True, null=True , on_delete= models.SET_NULL, verbose_name= 'Stock') date = models.DateTimeField(auto_now_add=True ,verbose_name= 'Date') description = models.CharField( blank= True , null= True, max_length=500 ) class Vente(models.Model): name = models.CharField(max_length=30) quantite = models.IntegerField(null=True) price = models.IntegerField(null=True) total = models.IntegerField(null=True) produit = models.ForeignKey(Produit, on_delete=models.CASCADE ) date = … -
How to generate credentials.json in Google Cloud Platform?
I am trying to use Google Storage for my Django application deployed in Compute Engine. To enable this I have to download a credentials.json in my console. I have made a new service account. However I do not see any download json for this credentials. How do you generate the json file? -
Both Dockerize and be able to debug a Django app using vscode
Is it possible to both Dockerize a Django app and still be able to debug it using Visual Studio Code's debugging tool? If yes, how? E.g, using docker-compose to run Django app, postgres, and a redis instance and be able to debug the Django app via Visual Studio Code. Thanks in advance