Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Audio file is not passing through Ajax
I am trying to send data in form with audio file when ever I send data request this error in console pop up [enter image description here][1] [1]: https://i.stack.imgur.com/q5Hi2.png This is my form code <body> <h1>Audio</h1> <form id="form" method="POST"> {% csrf_token %}{{form.as_p}} <input type="text" id="first_name" placeholder="student Name"><br> <input type="text" id="Reg_No" placeholder="Registration No"><br> <input type="text" id="Health_status" placeholder="Health Status"><br> <input type="text" id="deparment" placeholder="Department"><br> <input type="submit" name="submit" value="submit"> <h1>{{message}}</h1> </form> <div id="output"> </div> <button id="startRecordingButton">Start recording</button> <button id="stopRecordingButton">Stop recording</button> <button id="playButton">Play</button> <button id="downloadButton">Download</button> <button id="SubmitButton">Submit</button> audio file is storing in blob variable blob = new Blob([view], { type: 'audio/wav' }); }); I am trying to send it through ajax in dataform submit.addEventListener("click", function (e) { e.preventDefault(); let formData = new FormData(); var recording = blob; formData.append("recording", recording); formData.append("first_name", first_name); formData.append("deparment", deparment); formData.append("Reg_No", Reg_No); formData.append("Health_status", Health_status); $.ajaxSetup({ headers: { "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value, } }); $.ajax({ type: 'POST', url: "{% url 'HealthTest' %}", data: formData, dataType: "json", success: function (data) { // $('#output').html(data.msg) /* response message */ alert('created new user'); }, failure: function () { } }); }); here is my views.py function where i am actually storing data for audio file i just need to read audio and send it to pickle so i created … -
Can you iterate through model fields when you overwrite the save() method in django?
I'm calling a custom save method in my model. The save method is designed to produce some values in the model based on the content of a TextField. This content is stored in a dictionary, and is generated correctly. I'm trying to write a for loop to store the values of the dictionary. The keys correspond to the model field names: def save(self, *args, **kwargs): if self.text != "": results_dict = analyze(self.text) for field_name in field_names_list: self.field_name = results_dict[field_name] The value is not stored in the corresponding field. Do I need to use setattr here instead? -
Update a model field in save method based on other field values selected including m2m field
I am trying to update a model field by overriding save method: class DataTable(models.Model): id = models.AutoField(db_column='Id', primary_key=True) country= models.ForeignKey(Countries,on_delete=models.DO_NOTHING,db_column='CountryId') university=models.ManyToManyField(Universities,db_column='UniversityId',verbose_name='University',related_name='universities') intake = models.CharField(db_column='Intake',blank=True, null=True, max_length=20, verbose_name='Intake') year = models.CharField(max_length=5,blank=True,null=True) application_status = models.ForeignKey(Applicationstages,on_delete=models.DO_NOTHING, db_column='ApplicationStageId',verbose_name='Application Status') requested_count = models.PositiveIntegerField(db_column='RequestedCount',blank=True,null=True) class Meta: db_table = 'DataTable' def __str__(self): return str(self.application_status) def __unicode__(self): return str(self.application_status) def save(self,*args, **kwargs): super(DataTable,self).save(*args, **kwargs) country_id= self.country intake= self.intake year= self.year universities= self.university.all() courses = get_ack_courses(country_id,universities) all_data = get_all_courses(intake,year,courses) ack_data = get_acknowledgements_data(all_data) self.requested_count =len(ack_data) super(DataTable,self).save(*args, **kwargs) I am trying to update the requested_count field using the other field values, but in save method when I try to get the m2m field data ; it is returning empty. I tried with post_save signal also and there also m2m field data is empty. I want the count field based on otherfields from this model. How to save when we have m2m fields? -
django: Outputting CSV with JsonResponse
def export_csv(request,query): p = Path(os.path.dirname(__file__)) FILE_JUDGEMENT = str(p.parent)+"/static/pygiustizia" content = "" res = {} res["status"] = "ok" res["data"] = content response = JsonResponse(res, status=200) if os.path.exists(nameFile): response["Content-Description"] = "File Transfer" response["Content-Type"] = "application/octet-stream" response["Content-Disposition"] = 'attachment; filename="somefilename.csv"' response["Expires"] = 0 response["Cache-Control"] = "must-revalidate" response["Pragma"] = "public" writer = csv.writer(response,delimiter =';') writer.writerow(headerData.values()) totalRowData = 0 #fdata = toDict(fdata) #print("fdata",fdata) for keyRow,valueRow in fdata.items(): #print("valueRow",valueRow.values()) writer.writerow(valueRow.values()) totalRowData = totalRowData + 1 return response I have a controller-view in python django framework. My goal is output and download a csv created querying data from elastisearch. it create somefilename.csv but in header csv file I have {"status": "ok", "data": ""}sendername;controparte;nomegiudice;annosentenza;codiceufficio;fascicoloprecedente_annoruolo; Why? -
How to send a file with FTP in JavaScript?
I want when a user uploads a file, this file should be sent to the server with FTP without pressing a button or submitting a form. I try to do that but it is not working. Firstly, I created a function with time intervals, which checks whether the file input is empty or not. If it is not empty, it should send the file to the server. var file = "/uploads/" + {{ api_id }} this should be the address of the file on the server. How can I do that or where is my mistake? <input type="file" class="form-control-file" id="exampleFormControlFile1" name="bankStat1"> <script> setInterval(displayHello, 1000); function displayHello() { var is_File = false if (document.getElementById("exampleFormControlFile1").files.length >= 1){ is_File = true var file = "/uploads/" + {{ api_id }} var ftp = new FtpConnection("ftp://myftp/") ; ftp.login("myuser", "mypass"); ftp.cd("uploads") ftp.put(file,document.getElementById("exampleFormControlFile1").files[0]) ; ftp.close() ; file.close() ; } console.log(is_File) } </script> -
how Count field using django orm
Hi Everyone i trying to count active and inactive status sepratally, below mention code to count all, i need to count active and inactive status sepratally,pls help me out. Type.objects.all().aggregate(Count('status')) output=5 -
Azure App Services: multi-containers not starting
I had my Django web app running on Azure VM then decided to move to Azure App Services using a multi-container instances. However, celery seems to be breaking Following is my docker-compose configuration and error logs for Azure App Service services: application: image: expressway.azurecr.io/expressways_application:v1 ports: - 80:8000 depends_on: - queue working_dir: /data command: gunicorn config.wsgi:application 0.0.0.0:80 restart: unless-stopped queue: image: expressway.azurecr.io/redis:v1 restart: unless-stopped worker: image: expressway.azurecr.io/expressways_worker:v1 restart: unless-stopped depends_on: - queue - application command: bash -c /data/docker-worker-entrypoint.sh volumes: static-files: media-files: ${WEBAPP_STORAGE_HOME}/site/wwwroot:/var/www/html ${WEBAPP_STORAGE_HOME}/phpmyadmin:/var/www/phpmyadmin **However, the only thing that I see in my App Service logs is:** ` ``` 2022-04-08T11:47:32.913Z ERROR - multi-container unit was not started successfully 2022-04-08T11:47:32.929Z INFO - Container logs from testoms_application_0_cb8acd23 = 2022-04-08T11:47:24.232210483Z [2022-04-08 11:47:24 +0000] [1] [INFO] Starting gunicorn 19.9.0 2022-04-08T11:47:24.236012528Z [2022-04-08 11:47:24 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) 2022-04-08T11:47:24.236677888Z [2022-04-08 11:47:24 +0000] [1] [INFO] Using worker: sync 2022-04-08T11:47:24.243640619Z [2022-04-08 11:47:24 +0000] [8] [INFO] Booting worker with pid: 8 2022-04-08T11:47:24.252172692Z [2022-04-08 11:47:24 +0000] [8] [ERROR] Exception in worker process 2022-04-08T11:47:24.252216296Z Traceback (most recent call last): 2022-04-08T11:47:24.252223297Z File "/usr/local/lib/python3.6/dist-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2022-04-08T11:47:24.252228597Z worker.init_process() 2022-04-08T11:47:24.252232898Z File "/usr/local/lib/python3.6/dist-packages/gunicorn/workers/base.py", line 129, in init_process 2022-04-08T11:47:24.252237698Z self.load_wsgi() 2022-04-08T11:47:24.252241799Z File "/usr/local/lib/python3.6/dist-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2022-04-08T11:47:24.252246299Z self.wsgi = self.app.wsgi() 2022-04-08T11:47:24.252250299Z File … -
how do I render 'address_one' object associated with a specific order
So the customer has an order page where I want to render their order details, specifically product name, date ordered, status, and their delivery location, right now I got everything to work except the delivery location("address_one"). I would really appreciate it if someone can help me out, thx! models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) class Product(models.Model): name = models.CharField(max_length=150) description = models.TextField() class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) address_one = models.CharField(max_length=200) views.py @login_required def orders(request): orderitems = OrderItem.objects.filter(order__customer__user=request.user) #how do I get the shipping address associated with order shipping = ShippingAddress.objects.filter() context = {"orderitems": orderitems, "shipping": shipping} HTML {% for orderitem in orderitems %} <div class="order-data-view"> <div class="order">{{ orderitem.product.name }}</div> <div class="date">{{ orderitem.date_added }}</div> <div class="status">dummydata</div> <div class="delivering-to">{{ shipping.address_one }}</div> </div> {% endfor %} -
serving apk file in heroku server via django not working?
I want to serve apk file in website hosted on heroku, it is serving also but while installing it shows error "There was a problem while parsing the package". And also downloaded apk file working in local server -> Backend is Django {% load static %} <a href="{% static 'app/home.apk' %}" download=""></a> -
how to submit onchange form without refresh in django
here is the code where submit onchange <div class="form-group row"> <div class="col-sm-10 col-md-7"> <select {{ form|validation_class:"devamsizlik" }} id="devamsizlik" name="devamsizlik" onchange="this.form.submit();"> <option value="">Gelme durumu</option> <option value="True"> <span style="font-family: wingdings; font-size: 200%;">&#10004;</span> </option> <option value="False"> <span style="font-family: wingdings; font-size: 200%;">&#10060;</span> </option> </select> </div> </div> ı try some ajax code but none of them working on it , ı could not find anything about while submitting on change page not reload. -
How to change admin model in external app in Django?
I have installed the tell-me app that is gathering users' feedback. I want to edit list_display and list_filter in the admin panel but I am not sure how to access this model in the admin.py file. Any advice on how to do that will be appreciated. -
Django "Client class" integration into VS Code
I have had several issues integrating Django testing into VSCode. Finally I succeeded to run most kinds of tests (the trick, it seems, is to run django.setup() before anything else happens, including importing Django modules), but now I am having a problem with Django's client class. I do a simple client.get() and I get a 400 (Bad Request) error from within VSCode. But if I run "python manage.py test" from the CLI the test works! I am completely at a loss as to what is happening... Here is my code. It couldn't be simpler. import logging import django django.setup() from django.test import Client, TestCase # noqa: E402 from django.db import DatabaseError # noqa: E402 logger = logging.getLogger('XXXX.debugger') class WorkflowAPIClient(TestCase): def test_createWorkflow(self): client = Client() resp = client.get('/workflow/') logger.debug(f'After request: {resp.status_code} - {resp.content}') self.assertEqual(resp.status_code, 200) When I run this from the CLI as "python manage.py test" it runs OK (assertEqual succeeds). When I try to run this from the test module of VSCode, it gives a status_code of 400 and thus assertEqual fails. I am using unittest for the VSCode test configuration and it discovers the test files without any problem. -
UTF-8 encoding for xhtml2pdf in Django
I am using xhtml2pdf package to generate a pdf file from an html template in my django application. The pdf file generates correctly (no errors), however, I have encountered a problem with UTF-8 encoding. My generated pdf file, instead of special charactes (PL language), shows black squares. I have gone through almost all solutions available online, but none of them helped. When I am using ReportLab and generate pdf without a template, all seems to be okay. Am I missing something perhaps on the views side? My html template {% load static %} <!DOCTYPE html> <html lang="pl-PL"> <head> <meta charset="UTF-8"> <title>PDF {{obj.orderNumber}}</title> <style> @font-face { font-family: 'Lato'; src: url(https://github.com/google/fonts/blob/master/ofl/lato/Lato-Regular.ttf?raw=True); } * { font-family: 'Lato'; } table { -pdf-keep-with-next: true; } p { margin: 0; -pdf-keep-with-next: true; } p.separator { -pdf-keep-with-next: false; font-size: 6pt; } .bander{ color:brown; font-size:13pt; } </style> </head> <body> <img src="media/logo.jpg" style="height:60px;"> <h2> PLAN ROZKROJU ZLECENIA: </h2> <h1 style="color:#997207;">{{obj.orderNumber}} {{obj.orderName}}</h3> <h2> Naklad: {{obj.orderQuantity}} szt </h2> <h4> Data utworzenia wydruku: {{obj3}} </h4> <div> <table class="table table-bordered" style="text-align: center; padding: 5px;" border="0.2"> <thead class="table-active"> <tr> <th scope="col">Nazwa materialu</th> <th scope="col">Ilosc</th> <th scope="col">Nazwa czesci</th> <th scope="col">Wymiar (mm)</th> <th scope="col">Wymiar 2 (mm)</th> </tr> </thead> <tbody> {% for item in obj2 %} <tr> … -
Django - column of relation already exists - should I use --fake?
I have a Django app using PostgreSQL with tenant_schemas. My DB has been imported from a .sql file, and now I have to run the migrations (with some changes in it, differen than the original DB imported from the .sql). When I do that, I get: django.db.utils.ProgrammingError: column "active_vendor" of relation "analysis_supplier" already exists I've researched this problem, and it looks like some people (on stackoverflow) recommend using --fake for this situation. But according to django docs: --fake Marks the migrations up to the target one (following the rules above) as applied, but without actually running the SQL to change your database schema. This is intended for advanced users to manipulate the current migration state directly if they’re manually applying changes; be warned that using --fake runs the risk of putting the migration state table into a state where manual recovery will be needed to make migrations run correctly. As I understand, this means that the migration will only be added to the migration table of django, and the SQL code will not be ran. I don't think I want that. Am I misunderstanding it? If so, should I use --fake in my situation? If not, how should I fix … -
How to prevent N+1 queries when fetching ancestors with Django Treebeard?
We are using Django Treebeard's materialized path to model an organizational hierarchy as follows: Now each node in the organizational tree can have multiple tasks: class Organization(MP_Node): node_order_by = ['name'] name = models.CharField(max_length=100) class Task(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) description= models.TextField() Given a list of tasks, we wish to include the full organizational path of each task in the result. How can we achieve this without the need for N+1 queries? Expected result for organization Factory 1 could be for example: Task name Organization Path Task 1 MyCompany/Factory 1/Maintenance Task 2 MyCompany/Factory 1/Operations Task 3 MyCompany/Factory 1 Task 4 MyCompany/Factory 1/Operations -
How to select single entity from multiple entity with maximum value of a field in django?
models.py def return_timestamped_id(): last_unique_id = RMLocation.objects.all().order_by('id').last() if not last_unique_id: return 'RM0001' else: timestamped_id = last_unique_id.unique_id timestamped_id = int(timestamped_id.split('RM')[-1]) width = 4 new_unique_int = timestamped_id + 1 formatted = (width - len(str(new_unique_int))) * "0" + str(new_unique_int) new_unique_id = 'RM' + str(formatted) return new_unique_id class RMLocation(models.Model): warehouse = models.ForeignKey(RMWarehouse, on_delete=models.CASCADE, related_name='l_warehouse') cabinet = models.CharField(max_length=255, blank=True, null=True) rack = models.CharField(max_length=255, blank=True, null=True) shelf = models.CharField(max_length=255, blank=True, null=True) file_name = models.CharField(max_length=255, blank=True, null=True) file_no = models.CharField(max_length=255, blank=True, null=True) unique_id = models.CharField(default=return_timestamped_id, max_length=255, blank=True, null=True) # Auto generated. uuid = models.CharField(max_length=40) record_extension = models.ForeignKey(DocumentExtension, on_delete=models.CASCADE, related_name='rec_ext', blank=True, null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='record_company') is_ocr = models.BooleanField(default=False) ocr_text_file = models.CharField(max_length=255, blank=True, null=True) is_trashed = models.BooleanField(default=False) trashed_on = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(default=timezone.now) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, related_name='l_created_by') updated_at = models.DateTimeField(blank=True, null=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, related_name='l_updated_by') deleted_at = models.DateTimeField(blank=True, null=True) deleted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, related_name='l_deleted_by') def __str__(self): return str(self.id) class Meta: db_table = 'record_location' class RMRecordVersion(models.Model): VER_TYPE_CHOICE = ( ('major', 'major'), ('minor', 'minor') ) record = models.ForeignKey(RMLocation, on_delete=models.CASCADE, related_name='rv_rec') scanned_file_location = models.TextField(blank=True, null=True) size_in_kb = models.FloatField(default=0.0) version_no = models.IntegerField(default=1) version_code = models.CharField(default='1.0', max_length=10) version_type = models.CharField(choices=VER_TYPE_CHOICE, max_length=10, default='major') created_at = models.DateTimeField(auto_now_add=True, null=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='rv_rm_user', null=True, blank=True) def … -
Merge two or more Many to Many models in Django admin page
How can I add or more Models on one page with Many-to-Many models in Django admin change view page? For example If I have the following models, what could be the best way to add them all on the same change view page : class Course(SoftDeletionModel, TimeStampedModel, models.Model): uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) title = models.CharField( _('Title'), max_length=100, null=False, blank=False) overview = models.CharField( _('Overview'), max_length=100, null=True, blank=True) description = models.CharField( _('Description'), max_length=200, null=False, blank=False ) def __str__(self): return self.title class Meta: verbose_name_plural = "Topics" ordering = ['ranking'] class SubTopic(TimeStampedModel, models.Model): """ Subtopic for the course. """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) sub_topic_cover = models.ImageField( _('Sub topic Cover'), upload_to='courses_images', null=True, blank=True, max_length=900) title = models.CharField( _('Title'), max_length=100, null=False, blank=False) description = models.CharField( _('Description'), max_length=200, null=False, blank=False ) course = models.ManyToManyField(Course, related_name='sub_topic', blank=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Sub topic" ordering = ['ranking'] class Lesson(TimeStampedModel, models.Model): """ Lesson for the sub topic. """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) title = models.CharField( _('Title'), max_length=100, null=False, blank=False) description = models.CharField( _('Description'), max_length=200, null=False, blank=False ) subtopic = models.ManyToManyField(SubTopic, related_name='lessons', blank=True) video_link = models.CharField( _('Video Link'), max_length=800, null=False, blank=False) def … -
Best way to create multiple sqlalchemy order_by statements from django REST
I want to use querystring parameters to set multiple order variants. Lets take a Table with the following columns: id, user_id, amount, date, text And ordering should be a list of dict like [{"amount": "desc"}, {"date": "asc"} ] in the crud-file: def get_multi_by_userid( db_session: Session, *, userid: int, skip=0, limit=1000, ordering ) -> List[Optional[transactions]]: orderstring = "" querystring = """db_session.query(transactions) .filter(transactions.userid == userid ) {} .offset(skip) .limit(limit) .all() """ for i in ordering: orderstring += ".order_by(transactions.{}.{}())".format(list(i.keys())[0],i[list(i.keys())[0]]) querystring.format(orderstring) return (eval(querystring), 200) now to my question: Is there a more elegant (and safer) way? -
Django - What is the benefit of squashing migrations?
So why would we want to squash migrations? I can think of two reasons so far: Cleanup. It is nice to have cleaned up migrations. Faster tests as creating the test database should be faster which is nice for the CI/CD pipeline. Overall it does not seem very important to do.. What do you guys think? -
Multiple Tables for one Django Model
How can I dynamically create multiple tables for one specific model? I have a model (e.g. "Data") and want each user to get a separate database table for this model. There will be between 30 and 40 users, each with about 20 million entries in "Data". So that the database table does not get 800 million rows, I would like to split it. Of course, it is also possible that there will be more in the future Is this still possible with Django ORM? I'm on PostgreSQL Thanks :) -
Getting "AuthToken.user" must be a "User" instance. in django-rest-knox register api and using Custom django user
I'm building a login and signup api with django rest frame work. I created a custom user, and I'm using django-rest-knox library for authentication. I'm getting error "AuthToken.user" must be a "User" instance. Custom User Definition class User(AbstractBaseUser): email = models.EmailField(verbose_name='email_address', max_length=255, unique=True,) full_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) phone_number = PhoneNumberField(region='NG', blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name', 'phone_number'] # Email & Password are required by default. def get_full_name(self): # The user is identified by their email address return self.full_name def get_short_name(self): # The user is identified by their email address return self.email def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" return self.staff @property def is_admin(self): "Is the user a admin member?" return self.admin objects = UserManager() Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'full_name', 'email', 'phone_number', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['email'], validated_data['full_name'], validated_data['phone_number'], validated_data['password']) … -
class CustomObtainAuthToken(obtain_auth_token): TypeError: function() argument 'code' must be code, not str
ObtainAuthToken is knwon as obtainauthtoken. enter image description here from rest_framework.authtoken.views import obtain_auth_token class CustomObtainAuthToken(obtain_auth_token): def post(self, request, *args, **kwargs): response = super(CustomObtainAuthToken, self).post( self, request, *args, **kwargs) token = Token.objects.get(Key=response.data['token']) user = User.objects.get(id=token.user_id) userSerializer = UserSerializer(user, many=False) return Response({'token': token.key, 'user': userSerializer.data}) Error: File "D:\project\backend\api\urls.py", line 2, in from api import views File "D:\project\backend\api\views.py", line 31, in class CustomObtainAuthToken(obtain_auth_token): TypeError: function() argument 'code' must be code, not str -
Django - query to sum value atribute from model in frontpage
I have a model class for Courses named "Curs" where i set a field with number of stundets (alocati_curs). When i loop in frontpage to show all the courses existed i show them {% for curs in profil.curs_set.all %} .... Also i can display the numaber of courses {% with profil.curs_set.all.count as total_cursuri %}.... . But i dont't know how to make a query to get the total students (alocati_curs) from all the courses. Please help me :) . Thank you. I tried {% with profil.curs.alocati_curs_set.all.count as total_cursuri %} and {% for curs in profil.curs.alocati_curs_set.all %} but is not working and i think is not correct. -
WebSocket connection to 'wss://...' failed: (Django + Gunicorn + Nginx + Daphne)
I'm getting an error while connecting the websocket. And I have read similar Q&A on stackoverflow but still not working for me. I've been trying all sorts of ways for days but still can't make the connection. This is my mistake The server I use is: Django + Gunicorn + Nginx + Daphne Browser error WebSocket connection to 'wss://mydomain/ws/some_url/' failed: Below is my config on the server Ngnix config: server { server_name ****** mydomain www.mydomain; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/django/magi/src/staticfiles/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass http://127.0.0.1:8001; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/magi.thcmedia.vn/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/magi.thcmedia.vn/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot }server { if ($host = www.magi.thcmedia.vn) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = magi.thcmedia.vn) { return 301 https://$host$request_uri; } # managed by Certbot server_name 103.221.223.183 magi.thcmedia.vn www.magi.thcmedia.vn; listen 80; return 404; # managed by Certbot } If you need to check any files, please comment below so I can add … -
Django allauth: Linking socail regsitered user to an account which has same email
Here is problem: I allowed user to social login with Google and Github. And both of them have a email scope. And it is possible to both of them have same email. In this kind of situations django redirects to another sign up page I want to connect both users to same account if their emails are same