Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static File Not Serving Django Python Socket IO Evenlet
I am trying to using python socket io library with django. For i am also using eventlet but problem is comming where my all static files not working. It is displaying not Not Found static file import os from django.core.wsgi import get_wsgi_application import socketio from apps.chatbox.views import sio os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chatbot.settings") django_app = get_wsgi_application() application = socketio.Middleware(sio, wsgi_app=django_app, socketio_path='socket.io') import eventlet import eventlet.wsgi eventlet.wsgi.server(eventlet.listen(('', 8000)), application) Error Not Found: /static/js/main.a9e46e37.chunk.js 127.0.0.1 - - [08/Jun/2020 20:28:47] "GET /static/js/main.a9e46e37.chunk.js HTTP/1.1" 404 1976 0.017001 Not Found: /static/js/4.f274b99f.chunk.js 127.0.0.1 - - [08/Jun/2020 20:28:47] "GET /static/js/4.f274b99f.chunk.js HTTP/1.1" 404 1967 0.021015 Not Found: /static/js/main.a9e46e37.chunk.js 127.0.0.1 - - [08/Jun/2020 20:28:47] "GET /static/js/main.a9e46e37.chunk.js HTTP/1.1" 404 1976 0.010007 Without bellow code in wsgi file, everything works better import eventlet import eventlet.wsgi eventlet.wsgi.server(eventlet.listen(('', 8000)), application) -
Sending attachment in django using SendGrid
I have an html string I convert to PDF using Weasyprint and thereafter attaching it to an email which is sent using SendGrid. The code below is working. But I have two question: Since I store the file to MEDIA_ROOT using Weasyprint, will the fail be saved and therefore has to be deleted after sending? Or is it only stored temporary? Is there a way to generate the PDF file without storing it at all and in some way attach the PDF file from an object only? Code: message = Mail(from_email = ...... pdf_file = HTML(string=html_content, base_url=settings.MEDIA_ROOT).write_pdf() temp = tempfile.NamedTemporaryFile() temp.write(pdf_file) temp.seek(0) with open(temp.name, 'rb') as f: data = f.read() encoded = base64.b64encode(data).decode() #build attachment attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('application/pdf') attachment.file_name = FileName('test.pdf') attachment.disposition = Disposition("attachment") attachment.content_id = ContentId("PDF Document file") message.attachment = attachment If anyone have any inputs on this I am very grateful. -
Problem With django-cron -code executes from command line, but not crontab
I am not sure if this is for StackOverflow or a different forum, but I have installed django-cron for my Django project and am struggling to get it working when the command is scheduled in crontab. I know that the code executes because if I run it from the command line as below then the code is executed and I can see the results. python3 manage.py runcrons If I then schedule the command to run in the crontab, I have tried both for root and logged on user, the code doesn't seem to execute. When I run "grep CRON /var/log/syslog" then I get the following output: Jun 8 15:55:01 DJANGO-DEV-1 CRON[6616]: (<username>) CMD (source /home/<username>/.bashrc && source /home/<username>/environments/<appname>/bin/activate && python3 /home/<username>/Documents/<appname>/manage.py runcrons > /home/<username>/cronjob.log) Jun 8 15:55:01 DJANGO-DEV-1 CRON[6617]: (root) CMD (source /home/<username>/.bashrc && source /home/<username>/environments/<appname>/bin/activate && python3 /home/<username>/Documents/<appname>/manage.py runcrons > /home/<username>/cronjob.log) Jun 8 15:55:01 DJANGO-DEV-1 CRON[6614]: (CRON) info (No MTA installed, discarding output) Jun 8 15:55:01 DJANGO-DEV-1 CRON[6615]: (CRON) info (No MTA installed, discarding output) Jun 8 15:55:01 DJANGO-DEV-1 CRON[6618]: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1) I can check for the "cronjob.log" file, but it is not there. If I deactivate the environment and … -
problem with serving static files of django on server with nginx
Hi everyone I have changed default file of nginx where is in /etc/nginx/sites-available/default as below upstream django { server 127.0.0.1:8000; } server { listen 80; location /static/ { root /home/django/chistaa/chistaa/settings; try_files $uri =404; } location / { try_files $uri @send_to_django; } location @send_to_django { proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://django; } } but it doesnt load my static files. What did I wrong?! -
Django ORM .values() not works properly
This code dos not work: analyzer_signs = Sign.objects.filter(is_analyzer_used=True).values('code', 'name') for analyzer_sign in analyzer_signs: print(analyzer_sign) It prints nothing (doesn't enter the cycle) But when I delete .values('code', 'name') - It works greate: analyzer_signs = Sign.objects.filter(is_analyzer_used=True) for analyzer_sign in analyzer_signs: print(analyzer_sign) And I even can print text from fields code and name. I dont know what the *uck happens. And no one of my teammates doesn't. Please, help! Here is the model code: class ShortNameMixin(models.Model): short_name = models.TextField(blank=True) class Meta: abstract = True # class CodeMixin(models.Model): code = models.CharField(max_length=125) class Meta: abstract = True class AbstractBaseItem(common_models.CommonInfoAutoIncrementPK): name = models.TextField() is_active = models.BooleanField(default=True) class Meta: abstract = True def __str__(self): return self.name class SimpleDirectoryItem(ShortNameMixin, CodeMixin, AbstractBaseItem): class Meta: abstract = True class Sign(SimpleDirectoryItem): additional_code = models.CharField(max_length=255, null=True, blank=True) .... is_analyzer_used = models.BooleanField(default=False) alias = 'it-is-allias' class Meta: db_table = 'signtable' unique_together = ('sign_type', 'name',) ordering = default_ordering default_permissions = () permissions = (.......) PS: I tried to install differents db dumps, launched this project on Linux Mint (virtualbox) and Windows - still not works! But my teammates says "It works on my machine"... Can you suppose, what the problem is? Any help! -
After creating a new row in a table using .append() and click this new created row jquery is not working
In my code when I click on a of a table, for every tr a corresponding page is open using jquery. But problem is after calling ajax when I add a new tr by using jquery .append() method new tr is added at the end of the table but jquery click event is not working for newly added row. It need to refresh the whole page. In this back-end I use django. My jquery code is here <script type="text/javascript"> $('#add_student_submit_btn').click(function() { image = document.getElementById('student_image').files[0]; name = $('input[name = student_name]').val(); email = $('input[name = student_email]').val(); phone = $('input[name = student_phone]').val(); formData = new FormData(); formData.append('image',image); formData.append('fullname',name); formData.append('email',email); formData.append('phone',phone); formData.append('csrfmiddlewaretoken',$('input[name = csrfmiddlewaretoken]').val()); $.ajax({ url: {% url 'ajax.addstudents' %}, type: "POST", data: formData, processData: false, contentType: false, success: function (data) { console.log(data); markup = '<tr scope="row" data-student-id="'+ data.id + '"class="students_row">'; markup += '<td><img src="{{ MEDIA_URL }}/' + data.image + '" alt="" class="student_img_table"></td>'; markup += '<td>' + data.fullname +'</td>'; markup += '<td>' + data.email +'</td>'; markup += '<td>' + data.phone +'</td>'; markup += '<td>' + '5' +'</td>'; markup += '</tr>'; tableBody = $("#student_table"); tableBody.append(markup); $('#add_student_model').modal('hide'); } }); }); $('.students_row').click(function(){ id = $(this).attr('data-student-id'); location.replace("/profile/"+id); }); </script> And here is my Html <section> <div class="container"> <table … -
Django formset set field queryset based on URL pk
I have a working formset. My goal is a one field gets choices from other model, based on queryset using pk passed on url. It's almost working, but init method is executed twyce and cleans wkargs passed. Model: class Delito(models.Model): numero = models.ForeignKey(Expediente, on_delete=models.CASCADE, blank = False) delito = models.ForeignKey(CatalogoDelitos, on_delete=models.CASCADE, blank = False) imputado = models.ForeignKey(Imputado, on_delete=models.CASCADE, blank = False) categoria = models.CharField('Categoria', max_length = 20, blank = False, choices = CATDEL_CHOICES) My URL: path('crear_delito/<int:pk>', login_required(CrearDelito.as_view()), name ='crear_delito'), Forms.py: class CrearDelitoForm(forms.ModelForm): class Meta: model = Delito exclude = () def __init__(self, numero_pk = None, *args, **kwargs): super(CrearDelitoForm, self).__init__(*args, **kwargs) self.fields["imputado"].queryset = Imputado.objects.filter(numero_id = numero_pk) DelitoFormset = inlineformset_factory( Expediente, Delito, form=CrearDelitoForm, extra=1, can_delete=True, fields=('imputado', 'delito', 'categoria'), } ) Views.py: class CrearDelito(CreateView): model = Delito form_class = CrearDelitoForm template_name = 'crear_delito.html' def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['formset'] = DelitoFormset() context['expedientes'] = Expediente.objects.filter(id = self.kwargs['pk']) return context def get_form_kwargs(self, **kwargs): kwargs['numero_pk'] = self.kwargs['pk'] return kwargs If I print queryset, it works at first time, but is passed twice cleaning "numero_pk" value: System check identified no issues (0 silenced). June 08, 2020 - 11:33:57 Django version 2.2.12, using settings 'red.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. <QuerySet [<Imputado: Martín … -
Django template tags conditionals
Right, am struggling with my blog app when trying to render some logic through the template view. So the idea is to render a one time only button for the newly authenticated users that do not have a post published and after the user has published its first post the button will be rendered within a for loop so he/she'll be able to create/delete a new one from there. views.py @login_required(login_url='app_users:login') @allowed_users(allowed_roles=['admin', 'staff', 'users']) def blog(request): posts = BlogPost.objects.all().order_by('date_posted') context = {'title': 'Blog', 'posts': posts} return render(request, 'app_blog/blog.html', context) models.py class BlogPost(models.Model): title = models.CharField(max_length=100, null=True) content = models.TextField(null=True) date_posted = models.DateTimeField(default=timezone.now, null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title blog.html {% block content %} {% if request.user not in posts|last %} <div class="container" style="float: left;"> <a class="btn btn-primary btn-sm mt-1 mb-1" href="{% url 'app_blog:blog_create' user.id %}"><h5>C'mon {{ request.user.username }}, don't be shy! Create Your First Blog Post!</h5></a> </div> {% endif %} <br> <br> {% for post in posts %} <br> <div class="container"> <article class="media content-section"> <img class="rounded-circle account-img" src="{{ post.author.profile.image.url }}" alt="Image could not be uploaded!"> <div class="card-body media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'app_blog:blog_user_detail' post.id %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"d F Y" }}</small> </div> … -
How to add a Customer after he has signed up in and to make him a able to add items into his cart in Django
I created a user registration and log in form in my Django E-commerce website but I cannot log in a new user, it shows me the error bellow ` File "/home/bryo/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/bryo/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/bryo/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/bryo/PycharmProjects/Ecom/store/views.py", line 47, in store data = cartData(request) File "/home/bryo/PycharmProjects/Ecom/store/utils.py", line 49, in cartData customer = request.user.customer File "/home/bryo/lib/python3.8/site-packages/django/utils/functional.py", line 225, in inner return func(self._wrapped, *args) File "/home/bryo/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 420, in __get__ raise self.RelatedObjectDoesNotExist( django.contrib.auth.models.User.customer.RelatedObjectDoesNotExist: User has no customer. [08/Jun/2020 14:30:59] "GET / HTTP/1.1" 500 86843 ` How can I solve this problem so that a user can log in successfully and be able to add items to his cart?? -
opening the last page raises "That page contains no resuls" error when a second "next-page" button is added in django
The django pagination works well. Main html for pagination: <div class="pagination"> {% if entries.has_previous %} <a class=left-holder href="?page={{ entries.previous_page_number }}"> <img class=left-arrow src="{% static 'icons\leftarrow.png' %}" alt="leftarrow"></a> {% endif %} {% if not request.user_agent.is_mobile %} <div class="dropdown"> <button onclick="dropdown()" class="dropbtn">{{entries.number}}<span class=arrow-down><span class=spanito>&#9660;</span></button> <div id="myDropdown" class="dropdown-content"> {% for i in page_list %} <a href="?page={{i}}"><span {% if i == entries.number %} class=exception {% endif %}>{{i}}</span></a> {% endfor %} </div> </div> {% else %} <div class="dropdown"> <button onclick="phone_select()" class="dropbtn">{{entries.number}}<span class=arrow-down><span class=spanito>&#9660;</span></button> {% endif %} {% if entries.has_next %} <a class=next href="?page={{ entries.next_page_number }}"> <img class=right-arrow src="{% static 'icons\rightarrow.png' %}" alt="rightarrow"></a> {% endif %} <a href="?page={{ entries.paginator.num_pages }}"><button class=last-page>{{entries.paginator.num_pages}}</button></a> <b>-</b> </div> </div> I added a pop-up selection feature for mobile only and for practicality I also added another "next-page" button to the pop-up menu. Pop-up html from base.html: <div class="overlay6" id="overlay6"> <div id=fullscrean3> <div class=scrollable-div id=scrollable-div> {% for i in page_list %} {% if i == entries.number %} <a class=scroll-select id=exception2 href="?page={{i}}"><span id=exception>{{i}}</span></a> {% else %} <a class=scroll-select href="?page={{i}}">{{i}}</a> {% endif %} {% endfor %} </div> <button class=button-prevp onclick="kapat('overlay3') ">prev page</button> <a href="?page={{ entries.next_page_number }}"><button class=button-nextp></button>next page</button></a> </div> </div> When the second next page button is included the last page becomes inaccessible and raises … -
Can't run migrations for sorl-thumbnail
I'm trying to install sorl-thumbnail but when I run makemigrations I get "no changes detected". I upgraded the package to the latest version (12.6.3). When I try to continue using sorl-thumbnail in my html templates I get the expected error no such table: thumbnail_kvstore because I can't run mirations. I also tried manage.py makemigrations thumbnail. Here's my models.py: from sorl.thumbnail import ImageField class Profile(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) slug = AutoSlugField(populate_from='user', unique_with='user') profile_image = models.ImageField(default='image.png', upload_to='profile_images', blank=True, null=True, validators=[validate_image]) -
Is this a good way to stream data through django channels?
I have a database where new data is being inserted every second. When the websockets connection is first established, I want to send all the data using django channels. Then, I want the new data data that goes every second into the database to be sent through the same websocket. I have the following consumers.py class DataConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({ "type": "websocket.accept" }) obj = ... send the whole db await self.send({ 'type': 'websocket.send', 'text': obj }) while True: await asyncio.sleep(1) obj = ... send only new records await self.send({ 'type': 'websocket.send', 'text': obj }) async def websocket_receive(self, event): print("receive", event) async def websocket_disconnect(self, event): print("disconnected", event) Here Django Channels - constantly send data to client from server they mention that the loop will never exit if the user disconnects. They present a potential fix, but I don't understand it well. How could I fix it? -
how to send a some data from a class that has foreignkey to another class through DRF?
I have a Certificate model as below: class Certificate(models.Model): """Certificates for users who passed specific tests""" user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='certificates', on_delete=models.CASCADE, null=True) name = models.CharField(verbose_name='نام', max_length=255) image = models.ImageField(null=True, upload_to=certificate_image_file_path) thumbnail = models.ImageField(null=True, upload_to=certificate_image_file_path) grade = models.IntegerField(verbose_name='نمره', null=True) minimum_grade = models.IntegerField(verbose_name='حداقل نمره') def __str__(self): return self.name and as you can see it has a foreigkey to my custom user model. I want to send the Certificate object that is assigned to a user alongside the properties of the user. the user's serializer.py: class UserSerializer(serializers.ModelSerializer): """Serializer for the user object""" # TODO # certificates # videos = serializers.PrimaryKeyRelatedField( # many=True, # queryset=Tag.objects.all() # ) class Meta: model = get_user_model() # TODO add certificates and videos fields = ('id', 'email', 'password', 'first_name', 'last_name', 'phone_number', 'credit', 'points') extra_kwargs = {'password': {'write_only': True, 'label': 'گذرواژه', 'min_length': 5}} def create(self, validated_data): """Create a new user and return it""" return get_user_model().objects.create_user(**validated_data) def update(self, instance, validated_data): """Update a user and return it""" password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user and view.py: class ManageUserView(generics.RetrieveUpdateAPIView): """Manage the authenticated user""" serializer_class = UserSerializer authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get_object(self): """Retrieve and return authenticated user""" return self.request.user what should I add to … -
Serving two Django apps with Nginx
I have a Django app running with Nginx and Gunicorn on mysite.com. I would like to deploy a second Django app to be reachable under mysite.com/secondapp while my first app still just by mysite.com. I followed the tutorial from DigitalOcean and my current config for App 1 is: /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application /etc/nginx/sites-available/myproject server { listen 80; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/myprojectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } My question is: do I need to create 2 separate .socket and .service file for my App 2 and how do I make App 2 accessible by mysite.com/secondapp ? -
Django - Embed python inside HTML to trigger two form actions
All I want to do is to have a condition in order when the user clicks FOR SALE button to be redirected to url 'salesearch' or when clicks TO RENT to be redirected to url 'rentsearch'. Here's the code: <div class="search"> <form action="{% url 'salesearch' %}"> <div class="form-row"> <div class="col-md-4 mb-3"> <label class="sr-only">Keywords</label> <input type="text" name="keywords" class="form-control" placeholder="Keyword (Pool, Garage, etc)"> </div> <div class="col-md-4 mb-3"> <label class="sr-only">City</label> <input type="text" name="city" class="form-control" placeholder="City"> </div> <div class="form-row"> <div class ="col-md-6 mb-3"><button class="btn btn-secondary btn-block mt-4" type="submit" name ='For Sale'>For Sale</button> </div> <div class ="col-md-6 mb-3"><button class="btn btn-secondary btn-block mt-4" type="submit" name = 'To Rent'>To Rent</button> </div> </div> </form> With the above example I am redirected always at url 'salesearch path. Is there any way to have a conditional to determine the url's path? -
I'm trying to login with django. but always fail. why?
i'm doing my own project. the project is signup, signin in django. i make my own model. not django model. i use AbstractBaseUser, and create my own model. this model get name, id, companyname, companycode. i succeed signup. get name, id, companyname, companycode. and save mysql. but when i login with this information, always fail. i think authentication function is error. but i don't know where is the error. could you help me? models.py class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, username, userid, company, companycode, password=None): if not username: raise ValueError(_('Users must have an name!')) user = self.model( username=username, userid = userid, company= company, companycode = companycode, ) user.save() return user def create_superuser(self, username, userid, company, companycode, password): user = self.create_user( username=username, userid = userid, company = company, companycode = companycode, password=password, ) user.set_password(password) user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=10, unique=True, verbose_name="이름") userid = models.CharField(max_length=100, unique=True, verbose_name="아이디") company = models.CharField(max_length=10, verbose_name="회사") companycode = models.CharField(max_length=100, verbose_name="회사코드") created_date = models.DateTimeField(auto_now_add=True, verbose_name="생성날짜") is_admin = models.BooleanField(default=False) #is_active = models.BooleanField(default=True) class Meta: db_table = 'user' objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['userid', 'company', 'companycode'] def __str__(self): return self.username def get_full_name(self): return self.username def get_short_name(self): return self.username @property … -
Django / nested Inlineformset with class based view -> inlineformset not rendered?
I want to use nested inlineformset See below my ER diagram: Administration AdministrationSuivi adm_ide 1 ____ adm_sui_ide adm_nom |___ * adm_ide adm_sui_dem So, I have created my forms. forms.py: TREATMENT = Thesaurus.options_list(1,'fr') AdministrationSuiviFormset = inlineformset_factory( Administration, AdministrationSuivi, fields=('adm_sui_dem',), widgets={ 'adm_sui_dem': forms.Select(choices=TREATMENT), }, extra=1, can_delete=True, ) class AdministrationCreateForm(forms.ModelForm): def __init__(self, *args, **kwargs): # self.request = kwargs.pop("request") super(AdministrationCreateForm, self).__init__(*args, **kwargs) self.fields["adm_nom"] = forms.CharField(label = "Nom d'utilisateur pour l'application", widget = forms.TextInput) class Meta: model = Administration fields = ('adm_nom',) And i my view, I render my forms. Views.py class AdministrationSuiviCreateView(FormView): template_name = 'project/administrationsuivi_edit.html' form_class = AdministrationCreateForm def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data["utilisateur"] = self.request.user.username # nom de l'utilisateur connecté data["administration"] = AdministrationSuiviFormset(self.request.POST) else: data["administration"] = AdministrationSuiviFormset() return data def form_valid(self, form): context = self.get_context_data() administrationsuivi = context["administration"] self.object = form.save() if administrationsuivi.is_valid(): administrationsuivi.instance = self.object # instance Administration administrationsuivi.save() return super().form_valid(form) def get_success_url(self): return reverse("project:index_administration") But field adm_nom of AdministrationCreateForm is well render but not field adm_sui_dem of AdministrationSuiviFormset. What is wrong? -
I want to add all the images stored in a folder to a website in django
How can I loop through images in a folder and add them to the website? -
Django - allow user to run custom python code
Simple question that I can't seem to find an answer to: Is there a way in django to allow user to write their own custom code inside a textbox and to execute the code later on or on button-click? With this i mean the same it is implemented in w3scools: https://www.w3schools.com/python/trypython.asp?filename=demo_default I don't need to be able to visualize the result in a second screen or anything. The goal is to allow the user to write some basic but custom functionality! Imagine having access to a dictionary, and the user wants to transform the value of one of the keys: e.g. _dict = {'key1': 'xxx yyy', 'key2': 'yyy zzz'} and the user can create a custom key3 which is a concatenation of the two other keys. _dict['key3'] = _dict['key!'] + _dict['key2'] So here I have to expose the variable containing the dictionary and allow the user to write a custom python code to do whatever they want with it. OR embed the custom code into the actual code on run-time. Security for now is not a concern (but interesting to know how this could be handled). -
Create query if not existing with get_or_create not working
I am builing a Q/A where users can vote. I have two models, Topic which deal with the votes and question and VoteUser that set a boolean to True when a user vote. def upvote(request, qa_id): qa = get_object_or_404(Topic, pk=qa_id) vote = VoteUser.objects.get_or_create(author=request.user, topic=qa_id) vote = get_object_or_404(VoteUser, author=request.user, topic=qa_id) if vote.vote_status == False: qa.votes += 1 qa.save() vote.vote_status = True vote.save() But when I tried the request it gives me an error : vote = VoteUser.objects.get_or_create(author=request.user, topic=qa_id) -
Django Channels - Error during WebSocket handshake: net::ERR_CONNECTION_RESET
Trying to set up a simple websocket example with Django channels: Project structure: dashboard dashboard settings.py routing.py consumers.py urls.py chart urls.py views.py templates chart.html The relevant parts of each file: # dashboard/settings.py ASGI_APPLICATION = 'dashboard.routing.application' # dashboard/routing.py from django.conf.urls import url from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from .consumers import DataConsumer application = ProtocolTypeRouter({ # WebSocket chat handler "websocket": AuthMiddlewareStack( URLRouter([ url("websockets/", DataConsumer), ]) ), }) #dashboard/consumers.py from channels.consumer import AsyncConsumer from datetime import datetime class DataConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) async def websocket_receive(self, event): # when a message is received from the websocket print("connected", event) async def websocket_disconnect(self, event): # when the socket disconnects print("disconnected", event) #dashboard/urls.py from django.contrib import admin from django.urls import include from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('chart/', include("chart.urls")), ] #chart/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.chart) ] #chart/views.py from django.shortcuts import render def chart(request): return render(request, 'chart.html') #templates/chart.html <script> var loc = window.location var wsStart = "ws://" if (loc.protocol == 'https:'){ wsStart = 'wss://' } var endpoint = wsStart + loc.host + "/websockets/" console.log(endpoint) socket = new WebSocket(endpoint); socket.onopen = function(message) { console.log("open", message); } socket.onmessage = function(message) { … -
Django. autocomplete... It doesn't look up the search
I'm new to Django with autocomplete. I'm trying to use autocomplete search. I'm following this tutorial: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.rst Django doesn't give me any mistakes. All works except it doesn't actually looking for results in the search. Instead it gives me this phrase: "the results could not be loaded" In html, in developer section it gives me following mistakes: When first get to the page - GET http://dal-yourlabs.rhcloud.com/static/collected/admin/js/vendor/jquery/jquery.js net::ERR_NAME_NOT_RESOLVED When typing into the search field: jquery.min.js:2 GET http://127.0.0.1:8000/scrap_site/raildict-autocomplete/?q=ghj 500 (Internal Server Error) I don't use get method, since I am posting searches into database... I am using post method. Also I tried to set this code: into the template - <script type="text/javascript" src="http://dal-yourlabs.rhcloud.com/static/collected/admin/js/vendor/jquery/jquery.js"></script> and into the base.html-<link src="/static/collected/autocomplete_light/vendor/select2/dist/css/select2.css" type="text/css" media="all" rel="stylesheet" /> <link src="/static/collected/autocomplete_light/select2.css" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/static/collected/autocomplete_light/autocomplete.init.js"></script> <script type="text/javascript" src="/static/collected/autocomplete_light/select2.js"></script> Like it was advised in this post: Django: django-autocomplete-light does not work properly But it doesn't really help. What am I doing wrong? Thank you! -
Django - Send email with multiple dynamic images inline base64
I am building a system for sending bulk emails using django. on the frontend template: I have a div with quill where the user can customize his email with text , insert images etc`. also, an option to attach a file. in django views I have a function for sending the email. views.py: the relevant part: backend = EmailBackend(host="smtp.example.com", port=2525, username="example@eample.com", password="***", use_tls=True, fail_silently=False) email = EmailMultiAlternatives(subject, message, from_email, [], bcc=recepients, connection=backend) if request.FILES: uploaded_file = request.FILES['document'] email.attach(uploaded_file.name, uploaded_file.read(), uploaded_file.content_type) email.content_subtype = 'html' email.mixed_subtype = 'related' email.send() form.save() the problem is when a user inserting images into quilljs editor - it is converted to base64 data and email clients can read the images. I have found solutions when I know what images files are being send. for example: img_data = request.POST['image'] img = MIMEImage(img_data[img_data.find(",")+1:].decode('base64'), 'jpeg') img.add_header('Content-Id', '<file>') img.add_header("Content-Disposition", "inline", filename="file.jpg") msg.attach(img) but in my case , the user can insert several imagess, I do not have file names and do not know how to convert them to attached images. any solutions? options? thanks. -
django import export error in import xlsx
I don't understand why i'm getting this error. invoiceNumber is my primary key. -
Django & SQLite: how to prefetch when there is a limit on the number of variables
SQLite has a SQLITE_MAX_VARIABLE_NUMBER constant that controls the maximum number of variables that a SQL query can use. To illustrate, let's say I have these models: from django.db import models class A: name = models.CharField(max_length=20) class B: a = models.ForeignKey(A, on_delete=models.PROTECT) key = models.CharField(max_length=20) class C: b = models.ForeignKey(B, on_delete=models.PROTECT) value = models.CharField(max_length=20) Now, I have a bunch of A instances, for which I want to prefetch data transitively. A simple solution would be some_a_instances = A.objects.filter(name__in=search_input).unique() models.prefetch_related_objects( some_a_instances, 'b_set', 'b_set__c_set', ) But, depending on the cardinality of a <--> b and b <--> c, this may generate SQL queries with more variables than allowed by SQLITE_MAX_VARIABLE_NUMBER. So far, I've used a simple workaround - split the input in smaller chunks and prefetch each chunk sequentially. def chunks(items, chunk_size=100): return [items[i:i + chunk_size] for i in range(0, len(items), chunk_size)] for a_chunk in chunks(some_a_instances): models.prefetch_related_objects( a_chunk, 'b_set', 'b_set__c_set', ) But that doesn't work in every situation (for example, if one A instance is linked to a large number of Bs, or one B linked to a large number of Cs). Is there any way to tell django to prefetch (transitively), with at most N variables in each query ? Notes Let's …