Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python manage.py dumpdata killed prematurely
I'm migrating a database from MySQL to Postgres. This question has been very helpful. When running the python manage.py dumpdata --exclude contenttypes --indent=4 --natural-foreign > everything_else.json to create a json fixture the connection is aborted by the database server. All other steps have been successful. The MySQL database is hosted on RDS and the connection is aborted at the same point in the file each time I try to run this. Logs from the RDS instance state the problem as follows (db, user and host changed): [Note] Aborted connection 600000 to db: 'mydb' user: 'myUsername' host: '127.0.0.1' (Got an error writing communication packets) In the terminal the message is simply killed. Why would this error be happening and how can I create this json fixture? -
Even if i serve media files with nginx, they don't appear on the website
I am trying to use nginx to put my django app on production. But I cannot use images in the website even though I configured nginx. My nginx server's setup: server { server_name example.com www.example.com; location /static/ { root /home/myusername/myproject/static/; } location /media/ { root /home/myusername/myproject/media/; } location / { proxy_pass http://127.0.0.1:8000; } } My html file: {% extends 'base.html' %} {% block content %} <div class="column"> {% for dweet in dweets %} <div class="box"> {{dweet.body}} <span class="is-small has-text-grey-light"> ({{ dweet.created_at }} από {{ dweet.user.username }}) </span> <figure> <img class="is-rounded" src="/media/{{dweet.image}}" alt="connect" style="max-height:300px"> </figure> </div> {% endfor %} </div> {% endblock content %} I have played around with directory paths, but still nothing. -
Differentiate which button was used to submit form Django/JS
I have a Django view of a form that presents the user with two options. On form submission, one Button will send them to one view, the other will send them to another. This is the part of that view: form = MenuItemForm(request.POST or None, request.FILES or None) if request.method != 'POST': # No data submitted; create a blank form. form = MenuItemForm() else: if 'add_ingredients' in request.POST: # POST data submitted; process data. if form.is_valid(): menu_item = form.save(commit=False) menu_item.menu = menu_instance menu_item.save() return redirect('core:add_ingredient', menu_item_id=menu_item.id) else: # POST data submitted; process data. if form.is_valid(): menu_item = form.save(commit=False) menu_item.menu = menu_instance menu_item.save() return redirect('core:edit_menu') This worked fine on its own. Here are the form and buttons in the template: <form id="form" class="form" method="post" action="{% url 'core:add_ingredient' menu_item.id %}"> {% csrf_token %} {{ form.as_p }} <div class="button-container"> <button id="another-ingredient-button" type="submit" name="add_ingredient">Add Another Ingredient</button> <button type="submit" name="substitute">Add Substitute</button> <button class="done" type="submit" name="done">Done</button> </div> </form> After I added the code below, the form still submits, but it doesnt recognize which button was clicked that submitted the form, and always sends me to one view, I thought about adding an eventListener to each button but then the my alert box and the other code … -
How to load a PDF passed by Django to Angular?
In Django I have this function that returns a pdf to me def get(self, request): with open(filepath, 'rb') as f: pdf = f.read() return HttpResponse(pdf, content_type='application/pdf') In Angular i have this.http.get(apiUrl, { responseType: 'arraybuffer' }).subscribe( response => { // Create a blob object that represents the PDF file var blob = new Blob([response], { type: 'application/pdf' }); // Create an object URL that points to the blob var objectURL = URL.createObjectURL(blob); // Use the object URL as the src attribute for an <iframe> element // to display the PDF file document.getElementById('iframe').src = objectURL; }, error => { console.log(error) } ); In the <iframe> I get "Unable to upload PDF document" What am i doing wrong? -
How fix this error : exchangelib.errors.InvalidTypeError: 'tzinfo' <UTC> must be of type <class 'exchangelib.ewsdatetime.EWSTimeZone'>
In my Django project, I have bump the Exchangelib version (3.2.1 to 4.9.0) and now an error occurs. Traceback : File "/home/.../workspace/my_project/exchange_manager/models.py", line 297, in create_event event = self.create(*args, **kwargs) File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/query.py", line 453, in create obj.save(force_insert=True, using=self.db) File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/base.py", line 763, in save_base updated = self._save_table( File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/base.py", line 906, in _do_insert return manager._insert( File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1409, in execute_sql for sql, params in self.as_sql(): File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1352, in as_sql value_rows = [ File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1353, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1353, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1294, in prepare_value value = field.get_db_prep_save(value, connection=self.connection) File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 842, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1428, in get_db_prep_value return connection.ops.adapt_datetimefield_value(value) File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/db/backends/sqlite3/operations.py", line 247, in adapt_datetimefield_value value = timezone.make_naive(value, self.connection.timezone) File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/django/utils/timezone.py", line 256, in make_naive return value.astimezone(timezone).replace(tzinfo=None) File "/home/.../.local/share/virtualenvs/my_project-iOt348t5/lib/python3.8/site-packages/exchangelib/ewsdatetime.py", line 128, … -
How can I make user is authenticated?
Sorry, I dont know how to change syntax in stackowerflow and decided just put link to repository for you: https://github.com/ilya-6370/todo-react The folder backend/todo is main folder with settings,py and main file scheme.py The folder backemd/todoapp is the folder with details of app and api for todos in scheme.py the folder frontend is the folder with react app where i am using apolo client to make request and to add custom header When I am trying to fetch todos I get permission error: {"errors":[{"message":"You do not have permission to perform this action","locations":[{"line":2,"column":3}],"path":["todos"]}],"data":{"todos":null}} headers: request headers : accept: */* Accept-Encoding: gzip, deflate, br Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7 authorisation: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InVzZXIiLCJleHAiOjE2NzA1MzgwNzIsIm9yaWdJYXQiOjE2NzA1Mzc3NzJ9.eGl0oI2x7kYeuhRyryhUdcLyNgnvXuUSRsBJu6_iHFY Connection: keep-alive Content-Length: 111 content-type: application/json Host: 127.0.0.1:8000 Origin: http://localhost:3000 Referer: http://localhost:3000/ sec-ch-ua: "Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108" sec-ch-ua-mobile: ?0 sec-ch-ua-platform: "Windows" Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: cross-site User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 I have a custom field "authorisation" with token. How I can make user authorased for system by jwt token (I think it is my problem because I made authontication requiered fields in my scheme.py file in todoapp folder. I think that token does not give authonticated status, I need a way to make user … -
chown(): Operation not permitted occurred due to chown-soket of uwsgi【nginx】
I tried to run a django program using nginx and uwsgi, but the following error occurs in nginx. connect() to unix:/var/www/html/view/dbproject/dbproject.sock failed (13: Permission denied) while connecting to upstream I thought this error was probably because the owner of dbproject.sock, which is created when uwsgi is started, is username:username and not username:www-data. Therefore, I added chown-soket = %(username):www-data in the uwsgi initialization file uwsgi.ini, but when I restart uwsgi, chown(): Operation not permitted is written in the uwsgi log. How can I make the socket owner %(username):www-data? Thank you. uwsgi.ini [uwsgi] # path to your project chdir = /var/www/html/view/dbproject username = myusername # path to wsgi.py in project module = dbproject.wsgi:application master = true pidfile = /var/www/html/view/dbproject/django.uwsgi.pid socket = /var/www/html/view/dbproject/dbproject.sock # http = 127.0.0.1:8000 # path to python virtualvenv home = /var/www/html/view/myvenv chown-socket = %(username):www-data chmod-socket = 660 enable-threads = true processes = 5 thunder-lock = true max-requests = 5000 # clear environment on exit vacuum = true daemonize = /var/www/html/view/dbproject/django.uwsgi.log # Django settings env DJANGO_SETTINGS_MODULE = dbproject.settings -
django queryset filter on whether related field is empty
here is my models: class Flag(models.Model): ban = models.ForeignKey('flags.Ban', on_delete=models.CASCADE, related_name='flags') class Ban(models.Model): punished = models.BooleanField(default=None) Flag is triggered when user report some content. and they are summarised in to a Ban instance for administrator to verify. briefly, a ban can have many flags. there is one occasion, that the author getting reported, manually deletes the content he/she has sent before admin heads over there. the ban should be dismissed. therefore. in ban list view, I try to filter them out and delete. to_deletes = [] for ban in Ban.objects.all(): if not len(ban.flags.all()): to_deletes.append(ban) for ban in to_deletes: ban.delete() I wonder if there is a way I can write this into a queryset, all I need is a Ban.objects.all() that rejected empty flags for list view for performance and elegancy. -
AttributeError at /check 'QuerySet' object has no attribute 'name'
i wanted to check whether the name is exists in owner table or not. this is my index.html ` <form style="color:black" method="POST" action="check" class=" mt-3"> {% csrf_token %} <div class="row mb-3"> <label for="inputText" class="col-sm-3 col-form-label">Username</label> <div class="col-sm-8"> <input type="text" name="name" placeholder="Username" class="form-control"> </div> </div> <div class="row mb-3"> <label for="inputText" class="col-sm-3 col-form-label">Password</label> <div class="col-sm-8"> <input type="text" name="password" placeholder="password" class="form-control"> </div> </div> <button class="btn btn-success mb-3" type="submit">Login</button> <a class="btn btn-danger mb-3" href="index">Go Back</a> </form> this is my urls.py path('index', views.index), path('check', views.check), this is my views.py def check(request): owners = owner.objects.all() if request.method == "POST": name = request.POST.get('name') password = request.POST.get('password') if owners.name == name and owners.password == password : return render(request, "card/check.html") it gives error on this line if owners.name == name and owners.password == password : ` how to check whether the name exist or not in table -
How can i add paginator to Django filter
How can I add a paginator to the Django filter? I tried to add but whenever I am creating I got an error sometimes when the user chooses to filter by category paginator will not work all the content will show for eg: If I give paginate_by = 25 and when the user selects filter by category more than 25 data will be shown. when the paginators work filtering does not work These is my views.py class blogview(ListView): model = wallpapers template_name = 'blogs/blog.html' context_object_name = 'blogs' ordering = '-created_on', '-time' paginate_by = 2 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter']=WallpaperFilter(self.request.GET, queryset=self.get_queryset()) return context I am trying to add paginator to these function -
Django prefetch_related for many to many join not working
I have a many to many relation on models. Product can have many images and image can assign to multiple productions. this is my model type : from django.db import models class Image(models.Model): image_id = models.AutoField(primary_key=True) image_name = models.TextField(max_length=200) class Product(models.Model): product_id = models.AutoField(primary_key=True) product_name = models.TextField(max_length=200) image = models.ManyToManyField(Image, related_name="image") and in view im filling model like this : def home(self): """Renders the home page.""" assert isinstance(self, HttpRequest) all_product = Product.objects.prefetch_related('image').all() return render( self, 'app/index.html', { 'all_product': all_product } ) and in my template if i call model like this : {% for each_model in all_product %} <label> {{each_model.product_id}}</label> <label> {{each_model.image.image_id}}</label> {% endfor %} only items shows from products not the joined value from manyTomany table. -
Xlwt Excel Export Foreign Key By Actual Values / Django
I export products in excel format using xlwt.But foreign key fields are exported as id. How can I export foreign key fields with their actual values? I want to export brand_id and author fields with their actual values. Here is my product model : class Product(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(User,on_delete= models.CASCADE, verbose_name='Product Author', null=True) brand_id = models.ForeignKey(Brand,on_delete=models.CASCADE, verbose_name="Brand Names") name = models.CharField(max_length=255, verbose_name="Product Name") barcode = models.CharField(max_length=255, verbose_name="Barcode") unit = models.CharField(max_length=255,verbose_name="Product Unit") def __str__(self): return self.name Here is my export view: def export_excel(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = "attachment; filename=Products-" + str(datetime.datetime.now().date())+".xls" wb = xlwt.Workbook(encoding="utf-8") ws = wb.add_sheet('Products') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ["Product Id","Product Author","Product Brand","Product Name","Product Barcode","Product Unit"] for col_num in range(len(columns)): ws.write(row_num,col_num,columns[col_num],font_style) font_style = xlwt.XFStyle() rows = Product.objects.filter(author = request.user).values_list("id","author","brand_id","name","barcode","unit") for row in rows: row_num +=1 for col_num in range(len(row)): ws.write(row_num,col_num,str(row[col_num]), font_style) wb.save(response) Thanks for your help. Kind regards -
How to extend data in one column using xlsxwritter python
How to extend data in one column seperated by commas in xlsxwriter. for x in y: worksheet.merge_range("G"+str(row)+":"+"L"+str(row),x.multiple_values, centercell) row+=1 my data is dynamic for every loop i want to write values seperated by commas in particular column. for example column A | column B data | 654654,649824,63928,624684 -
Django redirect after save form in context_processor
I will if form saved, redirect my users. But it does'nt worked. Error: dictionary update sequence element #0 has length 0; 2 is required context_processor from .models import StaticPages from .forms import ContactForm from django.shortcuts import redirect from django.urls import reverse def main(request): pages = StaticPages.objects.all() if request.method == 'POST': # If the form has been submitted... contactform = ContactForm(request.POST) # A form bound to the POST data if contactform.is_valid(): # All validation rules pass contactform.save() return redirect(reverse('index')) else: contactform = ContactForm() # An unbound form context ={ 'pages':pages, 'contactform':contactform } return(context) my main urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')), ... ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my core.urls: from django.urls import path from .views import MainDashBoard urlpatterns = [ path('', MainDashBoard, name='index'), ] -
Why do Django projects have so many files?
When I started my Django project, I encountered a lot of files in my folder What is the reason for the existence of many files in Django projects? And what is the difference between manage.py file and other files? I tried coding and using libraries in the __init__.py file but it didn't work. -
ValueError: Cannot assign "<User: salman>": "DoctorProfile.user" must be a "Doctor" instance
I'm trying to register two types of users the Doctor and the Patient but when I tried I got the following error which made me feel like I'm lost because I really don't know what's happning thi is the error Traceback (most recent call last): File "C:\Users\rachi\AppData\Local\Programs\Python\Python310-32\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request)..... .. raise ValueError( ValueError: Cannot assign "<User: salman>": "DoctorProfile.user" must be a "Doctor" instance. This is my code my models.py class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class Doctor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) number_phone = models.CharField( _('االهاتف :'), max_length=50, blank=True, null=True) last_login = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s' % (self.user.username) class DoctorProfile (models.Model): } user = models.OneToOneField(Doctor, on_delete=models.CASCADE, primary_key=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super(DoctorProfile, self).save(*args, **kwargs) def __str__(self): return '%s' % (self.name) # def get_absolute_url(self): # return reverse("doctor_detail", kwargs={"slug": self.slug}) def create_profile(sender, **kwargs): if kwargs['created']: DoctorProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) class Patient(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=50, verbose_name="الاسم ") last_login = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s' % (self.user.username) please tell me where is the probleme -
How to solve django.core.paginator.EmptyPage error?
I'm trying to filter and paginate objects in a template. I created a views and I have 3 objects. I want to list 1 object in a page. When I do it it shows the page numbers (should be 3 pages) when I click next it gives me the error: raise EmptyPage(_('That page contains no results')) django.core.paginator.EmptyPage: That page contains no results How can I solve that? views class EntitySelect(FormView): template_name = 'sgm/entity_select.html' form_class = EntitySelectForm def get_context_data(self): self.context = super().get_context_data(**self.kwargs) process_type = ProcessType.objects.get(id=self.kwargs['process_type']) entity = process_type.consolidate_on rows = getattr(entities, entity).objects.all() paginator = Paginator(rows, 10) page_number = self.request.GET.get('page') if page_number == None: page_number = 1 page_obj = paginator.page(int(page_number)) rows = getattr(entities, entity).objects.all() if entity == 'Merchant': tableFilter = MerchantFilter(self.request.GET, queryset=rows) else: tableFilter = CustomerFilter(self.request.GET, queryset=rows) rows_2 = tableFilter.qs paginator = Paginator(rows_2, 2) page_number = self.request.GET.get('page') if page_number == None: page_number = 1 page_obj = paginator.page(int(page_number)) self.context['entity_type'] = entity self.context['columns'] = [field.name for field in getattr(entities, entity)._meta.local_fields if field.name != 'entity_ptr'] self.context['tableFilter'] = tableFilter self.context['columns'] = [field.name for field in getattr(entities, entity)._meta.local_fields if field.name != 'entity_ptr'] self.context['rows'] = page_obj self.context['process_type'] = process_type template <table class="table table-striped table-condensed table-hover"> <thead> <th> Select </th> {% for column in columns %} <th> {{ column|title|pretty_title … -
403 Forbidden error response coming back in flutter http
<!DOCTYPE html> I/flutter ( 4559): <html style="height:100%"> I/flutter ( 4559): <head> I/flutter ( 4559): <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> I/flutter ( 4559): <title> 403 Forbidden I/flutter ( 4559): </title></head> I/flutter ( 4559): <body style="color: #444; margin:0;font: normal 14px/20px Arial, Helvetica, sans-serif; height:100%; background-color: #fff;"> I/flutter ( 4559): <div style="height:auto; min-height:100%; "> <div style="text-align: center; width:800px; margin-left: -400px; position:absolute; top: 30%; left:50%;"> I/flutter ( 4559): <h1 style="margin:0; font-size:150px; line-height:150px; font-weight:bold;">403</h1> I/flutter ( 4559): <h2 style="margin-top:20px;font-size: 30px;">Forbidden I/flutter ( 4559): </h2> I/flutter ( 4559): <p>Access to this resource on the server is denied!</p> I/flutter ( 4559): </div></div><div style="color:#f0f0f0; font-size:12px;margin:auto;padding:0px 30px 0px 30px;position:relative;clear:both;height:100px;margin-top:-101px;background-color:#474747;border-top: 1px solid rgba(0,0,0,0.15);box-shadow: 0 1px 0 rgba(255, 255, 255, 0.3) inset;"> I/flutter ( 4559): <br>Proudly powered by <a style="color:#fff;" href="http://www.litespeedtech.com This type of response is comming back please anyone help me asap Acctually I am sending requewst on my url but in response i am getting back the 403 forbidden error in response -
Django signals calling asynchronous task without celery
I'm doing in signal: @receiver(post_save, sender=User) def send_something(sender, instance, created, **kwargs): if created: loop = asyncio.get_event_loop() async_function = sync_to_async(send_id, thread_sensitive=True) loop.create_task(async_function(instance.id)) my another function is: def send_id(user_id): print(user_id) But function is not calling -
regex for telephone number in validation form
in a django template with the html pattern tag and boostrap for form validation with this regex it validates a sequence of numbers that can be separated by a dash "^[+-]?\d(?:-?\d)+$" example: 12-65-25-75-84 or 12-255-0214 the javascript : (() => { 'use strict' const forms = document.querySelectorAll('.needs-validation') Array.from(forms).forEach(form => { form.addEventListener('submit', event => { if (!form.checkValidity()) { event.preventDefault() event.stopPropagation() } form.classList.add('was-validated') }, false) }) })() and the html <input type="text" class="form-control" id="exampleFormControlInput1" name="tel" id="tel" placeholder="Tel" pattern="^[+-]?\d(?:-?\d)+$" required> </div> I would like to know how to modify it to have the possibility of putting spaces between the numbers (in addition to the dashes) example: 12 57 125-98-457 and limit the total number of digits to 15 (excluding spaces and dashes) for example a string like this: 12-28-35-74-12 or 12 28 35 74 12 or 123-478 25 12 124-15 thank you -
Django MigrationSchemaMissing exception on Azure SQL using service principal auth
I'm actually working on a client's project we are connecting Azure SQL DB via service principal authentication. Our client has given us access to Azure SQL and they have given us the credential for it. so to connect to Azure SQL we're using Microsoft's mssql-django package. so this is what the DB configurations look like. DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': <db_name>, 'USER': <db_user>, 'PASSWORD': <db_password>, 'HOST': "<url>.database.windows.net", 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'connection_timeout':60, 'connection_retries':3, "extra_params": "Authentication=ActiveDirectoryServicePrincipal", }, } so when I'm trying to run the migrate command I'm getting the below error raise MigrationSchemaMissing( django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The specified schema name "<db_user>@<azure_tenant_id>" either does not exist or you do not have permission to use it. (2760) (SQLExecDirectW)')) by looking at the error we can definitely say that either the schema is not created or the DB user that they have given us does not have permission to create the tables in the DB. can anyone please suggest what could be going wrong, this is definitely not an issue from the Django or from the django-mssql package but an issue … -
How to organize multithreading
I have code, comes up WARNING: QApplication was not created in the main() thread, but the code runs, but 1 time, when it starts to run 2 times the site dies, how can I arrange multi-threading that it would not crash? from .forms import UserForm from bs4 import BeautifulSoup from django import forms from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QUrl from PyQt5.QtWebEngineWidgets import QWebEnginePage import sys import time import re import requests regex = r"price_85d2b9c\s+\w+\D+(?P<price>\d+\s+\d+)" class Client(QWebEnginePage): def __init__(self,url): global app self.app = QApplication(sys.argv) QWebEnginePage.__init__(self) self.html = "" self.loadFinished.connect(self.on_load_finished) self.load(QUrl(url)) self.app.exec_() def on_load_finished(self): self.html = self.toHtml(self.Callable) print("Load Finished") def Callable(self,data): self.html = data self.app.quit() def index(request): submitbutton= request.POST.get("submit") From='' To='' url='' prices = [] form= UserForm(request.POST or None) if form.is_valid(): From = (form.cleaned_data.get("From")).partition(", ")[2] To = (form.cleaned_data.get("To")).partition(", ")[2] context= ({'form': form, 'From': From, 'To': To, 'submitbutton': submitbutton,'prices': prices}) return render(request, "index3.html", context) I tried using the QThreadPool Class, but it didn't work correctly. What can I do to make the code handle links and not crash. -
Django mysql connection errors
Try to connect my django project with MySQL using wamp server i am facing error "Django.db.utils.NotsupportedError" I am tried older version of django To solve this error, but it seems also Same error. -
How to pass a dictionary to an url in POST request in Python
I have to get information about product stocks from marketplace's API via POST request. API requires to send products IDs (sku) in url Example: https://api.market.com/campaigns/{campaignId}/warehouse/{warehouseId}/stocks/actual.json?sku=sku1&sku=sku2&sku=sku3 So I guess, I have to pass a dict like {'sku': '1', 'sku': '2', 'sku': '3'} But of course, It's impossible to create a dict with same keys. I don't know how to solve this task. I made a function, using urllib (urlencode) that works. But it create an url with only last element in params. params = {"sku": "ps-22-1", "sku2": "ps-22-7-2", "sku3": "ps-22-7-3"} def get_stocks(self, campaign_id, warehouse_id, sku): """ Method for parse stocks Parameters: campaign_id (int): client_id in Store warehouse_id (int): warehouse_id in Warehouse sku (str): product sku in Product Returns: data (json): JSON with stocks data """ url = f"{self.url}campaigns/{campaign_id}/warehouses/{warehouse_id}/stocks/actual.json?" req = requests.get(url + urllib.parse.urlencode(sku), headers=self.headers) if req.status_code == 200: return True, '200', req.json() return False, req.json()["error"]["message"] I keep products IDs in my DB in such model: class Product(models.Model): name = models.CharField(max_length=150) sku = models.CharField(max_length=10) -
Django: Exception Value: The 'image' attribute has no file associated with it
Hi everyone I'm trying to create an auction system with Django. But when I go to the item profile, Django sends me an error: Exception Value: The 'image' attribute has no file associated with it. auction.html {% extends "base.html" %} {% block content %} {% load static %} <div class="page-header"> <h1>OPEN AUCTIONS</h1> </div> <div class="container"> <div class="row"> {% for item in auction %} <div class="col-sm-4"> <div class="card border-secondary" style="width: 25rem;"> <div class="card-header"> Auction {{item.id}} </div> <img src="{{ item.image.url }}" class="card-img-top" width="250" height="180"> <div class="card-body"> <h3 class="card-title" style="text-align:center" >{{ item.object }}</h3> <p class="card-text">{{item.description}}<br> Price: ${{ item.open_price}}<br> End: {{ item.close_date }}</p> <form method="POST"> {% csrf_token %} <input type="number" name='auct_id' value={{item.id}} readonly> <button type="submit" class="btn btn-primary btn-sm">Go</button> </form> </div> </div> </div> {% endfor %} </div> </div> {% endblock %} If I remove item from <img src="{{ item.image.url }}" class="card-img-top" width="250" height="180"> the page work correctly but the image doesn't display. Like this: view.py @login_required(login_url="login") def auction(request): if request.user.is_superuser: messages.error( request, "super user can access to admin/ and new_auction page only" ) return redirect("new_auction") auction = Auction.objects.filter(active=True) for data in auction: check = check_data(data.close_date) if check is False: data.active = False data.save() check_winner( request, data.id ) check_prof = check_profile( request ) if check_prof is …