Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How run task asynchronously whith Celery in Django App?
My settings.py CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_ALWAYS_EAGER = 'False' my celery.py from __future__ import absolute_import import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_try.settings') from django.conf import settings from celery import Celery app = Celery('celery_try', backend='amqp', broker='amqp://guest@localhost//') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True) @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) i have a view: def home(request): try: return render(request, 'app/home.html') finally: print '1' mytask.delay() and I have a script: from celery import shared_task @shared_task() def mytask(): time.sleep(10) print("Test 1234!") Actually it render home.html after 10 seconds and after print Test 1234! My goal is render home.html and AFTER 10 seconds run mytask() Any solution? -
How to redirect to homepage from navbar?
I'm very new to web-development. I created some pages such as products,create,delete. I have a navbar in base.html. The problem is that when i go to a page for example "product page" and then when clicked create on navbar it brought me to "http://127.0.0.1:8000/products/create/" and it doesn't exist I want to go to "http://127.0.0.1:8000/create/ from that, how do I do it? Thank you very much urlpatterns = [ path('admin/', admin.site.urls), path('', homepage, name ="home"), path('create/', create_product), path('products/', view_allproducts), path('products/<str:slug>/', retrive_product), path('products/<str:slug>/edit', update_product), path('products/<str:slug>/delete', delete_product), path("register/",register, name="register"), ------------------------------------------------------------- -
code examples of django-logpipe for kafka,thanks
I've seen documents on the official website, Document description is not detailed. as below: from django.db import models from rest_framework import serializers import uuid class Person(models.Model): uuid = models.UUIDField(default=uuid.uuid4, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class PersonSerializer(serializers.ModelSerializer): MESSAGE_TYPE = 'person' VERSION = 1 KEY_FIELD = 'uuid' class Meta: model = Person fields = ['uuid', 'first_name', 'last_name'] @classmethod def lookup_instance(cls, uuid, **kwargs): try: return Person.objects.get(uuid=uuid) except models.Person.DoesNotExist: pass -
Django rest framework Serializer: get source from POST request
I want to add data from a POST request to my serializer: class DeviceSerializer(ModelSerializerWithFields): class Meta: model = Device exclude = ("groups",) last_values = serializers.JSONField(source="get_graph_data", read_only=True) How can I get the resulting values from passing a specific request to get_graph_data? Ideally something like: last_values = serializers.JSONField(source="get_graph_data", read_only=True, payload="{'foo':1, 'bar':15}") but if not, at least a way to pass one value so I can edit the endpoint to take this specific case into account -
Query for abstract model class in Django
I have a abstract class I want like this: def detail(request,slug): game=get_object_or_404(Game,slug=slug) if game.type='1' lol=get_object_or_404(LeagueOfLegendsGame,....) elif game.type='2' warcraft=get_object_or_404(WarcraftGame,...) (i know abstract class cannot create object. What should you suggest) model.py class Game(models.Model): slug=models.SlugField(unique=True)... type=models.CharField(max_length=10,null=True,blank=True) class Meta: abstract = True class LeagueOfLegendsGame(Game): fields.... class WarcraftGame(Game): fields.... -
Django csv output with react
I am working on a task that needs to write to csv and download in the frontend. In views I have done: ...omitted details data = data.values(*values_fields) response = HttpResponse(content_type='text/csv') writer = csv.DictWriter(response, fieldnames=values_fields) writer.writeheader() writer.writerows(data) return response And, in the frontend: let a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; const blob = new Blob(res, {type: "text/csv"}); const url = window.URL.createObjectURL(blob); a.href = url; a.download = 'data.csv'; a.click(); window.URL.revokeObjectURL(url); a.remove() First of all, when I inspect res, I have only seen arrays of integers instead of dictionaries. How can I download my data? -
Where to put extra logic in django web API, in the view, or in the serializer?
I have a DRF view which extends CreateModelMixin and GenericViewSet. In the body of the post request, I want to accept an extra field, which does not belong to the related model. Then, I want to pop that extra field, use it for other purposes. I do not want to put that extra field back to the http response because it is a big and complex object. To explain it better here is a sample json input and the response that I want to return to the user: Request: # request { "name": "Why Nations Fail", "extra_field": { "my_keys": ["I'm", "a", "very", "big", "JSON-array", "object.", "..."] } } Response: # response { "id": 120 "name": "Why Nations Fail" } My problem is, I can't decide where to do this pop this extra_field; in the view or in the serializer (which extends ModelSerializer). Currently, I managed to do that by extending the create method handler of my view. But according the books and tutorials I've read: We should keep our views thin and our serializers thick. Keeping this in mind, I have tried to pop the field in the serializer but I couldn't manage to do that, I think because I'm … -
Cant use JsonResponse in Django
I have a bunch of values which I would like to send from views.py function to my template in Django. I saw some topics that the best way is by json format. So I did so. But because my values are not ascii I'm using a upgraded version which worked in normal Http response but don't work in JSON response. HERE is my code base = {weather_main_key : weather_main_values, wind_speed_key : wind_speed_value + "m", wind_deg_key : wind_deg_value, base_temp_key : base_temp_value + " ℃", base_press_key : base_press_value + " mbar", base_hum_key : base_hum_value + " % " } base = json.dumps(base, ensure_ascii=False).encode('utf8') return JsonResponse(json.dumps(base)) So I had an error msg In order to allow non-dict objects to be serialized set the safe parameter to False. So I did as it told me JsonResponse(json.dumps(base, safe=False, ensure_ascii=False).encode('utf8')) And now the error is __init__() got an unexpected keyword argument 'safe' And I can't move... -
Django - objects.all() shows nothing
I'm trying to get a list of objects in Django from a model. I just want to get the list of 'dht node' from the request user, but it shows nothing in the html file (as if the list was empty). The user that I'm using has 2 'dht nodes' and they're shown in the django admin. I don't know what is wrong, because if I use the instruction "member.dht.create(...)" in the views function and a create a new 'dht node' like this, this is shown. Only 'dht nodes' that I enter by form do not show. Can be the form? Thanks a lot, Here's my code: Models.py class Node(models.Model): name = models.CharField(primary_key=True, null=False, max_length= 50) description= models.CharField(default=None, null=False, max_length= 250) topic=models.CharField(default=None, null=False, max_length= 50, unique=True) def __unicode__(self): return self.name class dht(Node): temp = models.IntegerField(default=None, null=True) hum = models.IntegerField(default=None, null=True) class UserProfile(User): uid = models.CharField(default=None, null=False, max_length= 250) dht = models.ManyToManyField(dht, blank=True) def __unicode__(self): return self.user.username Views.py -dht list- @login_required(login_url = '/web/login') def listDhtSensor(request): member = request.user.userprofile list = member.dht.all() return render(request, 'web/listDhtSensor.html', {'list':list}) Html -listDhtSensor.html- {% block content %} {% for dht in list %} {{ dht.name }} {{ dht.topic }} {% endfor %} {% endblock %} Forms.py class … -
Python library can be found in PyPi but can't be installed by 'pip install'
I got django project code and tried to install all the requirements by 'pip install -r requiremets.txt' but somehow it doesn't work. occurred error is below Could not find a version that satisfies the requirement mkl-fft==1.0.9 (from -r requirements.txt (line 14)) (from versions: 1.0.0.17, 1.0.2, 1.0.6) No matching distribution found for mkl-fft==1.0.9 (from -r requirements.txt (line 14)) I tried to upgrade pip but it didnt work. -
How to show login form error in login page?
I'm trying to create a login page. I have used the default auth_view templates. I want to print the username and password field error in my login page. But cannot show them. I have tried using {{ form.username.errors }} but it is not working. But when is say {{ form.error }} it shows like below: __all__ Please enter a correct username and password. Note that both fields may be case-sensitive. urls.py path('login/', auth_views.LoginView.as_view(template_name='profiles/login.html'), name="login"), form template <div class="login-clean"> <form method="post"> <h2 class="sr-only">Login Form</h2> <div class="illustration"><i class="icon ion-code" style="color: rgb(71,151,244);"></i></div> {% csrf_token %} {{form.errors}} <div class="form-group"><input class="form-control" id="{{ form.username.id_for_label }}" type="text" name="{{ form.username.html_name }}" placeholder="username"></div> <div class="form-group"><input class="form-control" id="{{ form.password.id_for_label }}" type="password" name="{{ form.password.html_name }}" placeholder="username"></div> <div class="form-group"><button class="btn btn-primary btn-block" type="submit" style="background-color: rgb(71,151,244);">Log In</button></div><a class="forgot" href="#">Forgot your email or password?</a> </form> I want to see error results also If I want to style it, How to do it? -
Django with Apache and mod_wsgi: Timeout error
I'm trying to deploy Django application on a CentOS 7 server with Apache and mod_wsgi. The application is using plotly library to create graphs and plotly is using orca application to export created graph to image. I tested the application using the integrated django web server - everything works perfectly. So I set up Apache and mod_wsgi according official documentation. When I connect to Apache the application works, but it is not possible to export graphs. Browser ends up with Gateway Timeout Error. I inserted logger messages to the code which creates and exports graphs. The code runs until this line: static_image_bytes = plotly.io.to_image(figure, format='png', width=800, height=450) This line should run local Orca application and translate figure object to PNG image bytes. Orca requires X11 display server and CentOS is installed without GUI. I'm using Xvfb to emulate X11 (according to Orca's github page). Orca application is an AppImage downloaded from github. /bin/orca #!/bin/bash echo "`date` - ORCA STARTING with $@" >> /tmp/orca.log xvfb-run /usr/u/s/orca-1.2.1-x86_64.AppImage "$@" echo "`date` - ORCA FINISHED" >> /tmp/orca.log Also, I have tried to link /bin/orca directly to AppImage using: ln -s /usr/u/s/orca-1.2.1-x86_64.AppImage /bin/orca and adding this line to my code: plotly.io.orca.config.use_xvfb = True Apache error_log: … -
How do i get solve value error while using migrate command in django
I am working on exam-app using django frmaework and my make migration command is working properly but migrate command is giving error I have used Django frmawork but migration command givig error (ValueError: invalid literal for int() with base 10: 'Super Admin') this is my models.py file: `import uuid from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password, **kwargs): if not email or not password: raise ValueError('User must have a username and password') user = self.model( email=CustomUserManager.normalize_email(email), **kwargs ) user.set_password(password) user.save() return user def create_superuser(self, email, password, **kwargs): user = self.create_user(email, password, **kwargs) user.is_admin = True user.is_staff = True user.save() return user class User(AbstractBaseUser): SUPER_ADMIN = 1 STUDENT = 2 TEACHER = 3 ROLE_CHOICES = ( (STUDENT, 'Student'), (SUPER_ADMIN, 'Super Admin'), (TEACHER , 'Teacher'), ) first_name = models.CharField(max_length=255, null=False) last_name = models.CharField(max_length=255, null=False) email = models.EmailField(null=False, unique=True) is_active = models.BooleanField(default=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(default=False) # Add custom fields here api_token = models.UUIDField(default=uuid.uuid4, editable=False) token_created_date = models.DateTimeField(auto_now_add=True) role = models.SmallIntegerField(choices = ROLE_CHOICES, null = True) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def get_full_name(self): return self.first_name + " " + self.last_name def get_short_name(self): return self.first_name def has_perm(self, … -
Trigger Django Signal from Different Database other than default db
I have different database other than default. @receiver(post_save, sender=Customer) def customer_post_save_task(sender, instance, created, **kwargs): print("hmm", created) But This only triggers when Customer is created from default db If Customer is created from another db it does not get invoked. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'mydb': { 'ENGINE': 'django.contrib.gis.db.backends.mysql', 'NAME': 'Halanx', 'USER': 'root', 'PASSWORD': 'test', 'HOST': 'localhost', 'PORT': '3306', } When customer is created in mydb signal doesnot trigger. What can I do? -
How to capture middleware exception from other middleware in Django
I coding backend system with Django now, and I want control all exception from Django, so I create one middleware which name is CustomExceptoinMiddleware to control exception. But sometimes other middleware also raise exception, I hope CustomExceptoinMiddleware can capture it too, but I don't know how to do it. Can somebody help me? Thanks in advance! Python version: 3.7 Django version: 2.2.3 Setting.py MIDDLEWARE = [ ... "api.core.middleware.CustomExceptoinMiddleware ", "api.core.middleware.RaiseExcceptionMiddleware", ... ] # middleware.py class CustomExceptoinMiddleware(MiddlewareMixin): def process_exception(self, request, exception): print(f"Capture exception: {type(exception)}") class RaiseExcceptionMiddleware(MiddlewareMixin): def process_request(self, request): raise KeyError() -
Which is good for static and media when building a web server that can download files?
I want to build a web server that can only be downloaded to users by uploading large files. Where should I store my data files, static or media? Is it going to be good? (Size is 1 to 10GB compressed file.) Let me know if you have a better solution. -
Execute code in background after render page in Django
I have a script with twilio: from twilio.rest import Client def wa(testo): client = Client() # this is the Twilio sandbox testing number from_whatsapp_number='whatsapp:+14155238886' to_whatsapp_number='whatsapp:+39xxxxxxxxxx' ts = 'Anomalia Rapportino ' + str(testo) client.messages.create(body=ts, from_=from_whatsapp_number, to=to_whatsapp_number) I imported this script in view and I have this def: def grazieeprint(request, pk): intermedio = get_object_or_404(IntermProd, pk=pk) datilavoro = WhoWork.objects.get(pk=intermedio.work_id) try: return render(request, 'FBIsystem/thanksandprint.html', {'pkpreso': pk}) finally: try: appo = datilavoro.pezziorastima * 2 if datilavoro.pezziora >= appo: testo = datilavoro.pk subprocess.Popen([wa(testo)], shell=True) except: pass I need to run 'wa(testo)' after django load the page because all the process of sending message take approx 15/20 sec. I try whit 'try and finally' and whit 'subbrocess.Popen' but it send always the message before render the page. Please help TY -
ValueError: operands could not be broadcast together with shapes (256,) (128,)
I am making a Django Application using OpenCV and Dlib Library. I just wanted to implement face recognition feature using FILE UPLOAD. To store Image Hash at the backend I am using MongoDB. And hence I am using Djongo library to implement the same. Now here's the model which adds faces and it's hash to the database. Models.py class FaceDetails(models.Model): """ Model To Submit Face Details onto DB """ id_of_the_person = models.CharField(max_length=255, primary_key=True, default=uuid.uuid4, editable=False) name_of_the_person = models.CharField(max_length=255, blank=True) img_hash = models.CharField(max_length=4000, blank=True, null=True, editable=True) remarks = models.TextField(help_text='Remarks', blank=True, null=True) image_of_the_person = models.ImageField(upload_to='uploads/') created_at = models.DateTimeField(auto_now=True) def __str__(self): return "{}".format(self.name_of_the_person) @property def get_absolute_image_url(self): return '%s' % (self.image_of_the_person) @receiver(signals.post_save, sender=FaceAddition, dispatch_uid="update_img_hash") def face_addition_completed(sender, instance, **kwargs): img = cv2.imread(instance.get_absolute_image_url) bbs = dlib_detector(img) for k, bb in enumerate(bbs): shape = sp(img, bb) curr_rep = list(facerec.compute_face_descriptor(img, shape)) if kwargs.get('created', True): fa_object = FaceAddition.objects.get(id_of_the_person=instance.id_of_the_person) fa_object.img_hash = curr_rep fa_object.save() Here's my views.py file which handles image upload against which we search the database. I have done it very crudely though. Views.py def comparison_with_db(curr_rep): id_list = [] img_h_array = [] distance = 0.0 qs_fa = FaceDetails.objects.all() for obj in qs_fa: to_str_rp = obj.img_hash.replace( '[', '').replace(']', '').replace(",", "").replace("'", "").split() # So that it can be converted to list … -
How to pass a list instead of dictionary in python-django to html page
I want to display the list "response_body" to my html page "home.html" For that I retrieved id attribute from response_body and the last id which was stored in "id" variable is printed to my html file. I want to retrieve all the id's and print it to the html page I know this will be done through loop but how? I am new to django and python any help will be greatly appreciated. I have tried printing the last id before the loop ended and I was successful with it but now I want to print all the id'd in the loop. i tried passing response_body to html instead of context but it gives me an error as response_body is a list type and it asked me to pass a dictionary variable like context which works fine. how can I print all the id's in the reponse_body list home.html <p>results</p> <p>{{id}}</p> views.py as this is a fairly long code i am posting just the code which maybe useful. response_body = json.loads(response.read().decode('utf-8')) for j in response_body: print(j['id']) id = j['id'] context = { 'id': id, } return render(request, 'home.html', context) -
How to add a reset password button in django-administration
How to add a reset password button in django-administration. And also Reset password button act like Email verificationI want like this image -
Adding XSS to OPTIONS Call in Django
I wanted to add x-xss-protection to all my requests in my Django application. So I added secure_browser_xss_filter = True. All my requests are now safe. But when I look at the options, I am still not able to see "x-xss-protection: 1; mode=block" How can I add X-Xss to my OPTIONS call also? -
Django 2.3: Struggling to have form send email with an attachment. Not sure how files should be treated/ handled using FormView
OK so I am attempting to create a form on my website that will take input from a user. The fields include first_name, last_name, email, and then a file upload form that should take their resume. Unfortunately I cannot get this program to send an email that includes any document I attach. I am using FormView with django in order to handle the incoming information which seemed straightforward until it came time to handle a file. What i've seen from various other answers is that you'd use something like request.FILES['resume'] but that seems to be if you aren't using formview. I've been struggling with this for over 10 hours and would really love to have someone point me in the right direction. forms.py: from django.core.mail import EmailMessage from templated_email import get_templated_mail from django.conf import settings class UploadResumeForm(forms.Form): first_name = forms.CharField( widget=forms.TextInput( attrs={ 'type':'text', 'class': 'form-control', 'placeholder': 'First Name', }), required=True) last_name = forms.CharField( widget=forms.TextInput( attrs={ 'type':'text', 'class': 'form-control', 'placeholder': 'Last Name', }), required=True) email = forms.EmailField(widget=forms.TextInput( attrs={ 'type':'text', 'class': 'form-control', 'placeholder': 'Email', }), required=True) resume = forms.FileField(widget=forms.FileInput( attrs={ 'name': 'resume', 'placeholder': 'Resume', 'class':'file-path validate', }), required=False) class Meta: title = 'Resume Upload' def send_message(self, email, first_name, last_name, file): email_obj = … -
How do I import a PostgreSQL table into d3 for use?
I am currently using d3.csv to import a table for use in a graph, however, I instead want to use a table from my Postgres database. I have the database connected to Django however I am unsure what d3 function I can use to fetch a table from the database and use it instead of a csv file. d3.csv("[link]", function(data) { console.log(data); Console.log(data) returns a table that looks like this: IMG -
Avoid dyanmic content's translation in msgstr
I am using Django translations for ja and de using makemessage. There is a translation in that I don't want to translate dynamic content in de. I am using the following translations. msgid " and %(level3)s subgroups" msgstr "und aller Untergruppen von %(level3)s " But now I don't want to use dynamic content 'level3' in msgstr. I simply need need und aller Untergruppen von. so I changed it to msgid " and %(level3)s subgroups" msgstr "und aller Untergruppen von " but while doing compilemessages it's getting error CommandError: Execution of msgfmt failed: /Users/treeni/treeni_produts/sustain-online/so-web/locale/de/LC_MESSAGES/django.po:4409: a format specification for argument 'level3' doesn't exist in 'msgstr' msgfmt: found 1 fatal error -
Django API: Connect to different databases dynamically
I have a django app which asks user for the ip address, port, username, password and database of the server it wants to connect to. I want to create an API that connects to these databases dynamically, and execute a query like SHOW TABLES on it. I am unable to figure out how to do this. What I think is I will have to dynamically set settings. py and use it. Also the databases can be of any type amongst SQL, Mongo. The user also specifies the type of database.