Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write data to Amazon S3 with pythonocc-core StlAPI_Writer?
I have a Django application which it's deployed to Amazon Elastic Beanstalk(Python 3.7 running on 64bit Amazon Linux 2/3.0.3). I'm trying to convert a .stp file to a .stl file and save it to Amazon S3 Bucket by using pythonocc-core library. The convert2stl function works when I try to save to local but it doesn't work while saving the .stl to S3 bucket. Here is my convert2stl function: import boto3 import tempfile from OCC.Core.STEPControl import STEPControl_Reader from OCC.Core.StlAPI import StlAPI_Writer from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh @staticmethod def convert2stl(bucket, file): input_file = 'media/' + file if '.stp' in file: file_name = file.replace('.stp', '') else: file_name = file output_file = bucket + 'media/' + file_name + '.stl' s3 = boto3.resource('s3', region_name='eu-central-1') bucket = s3.Bucket('bucket') obj = bucket.Object(input_file) step_reader = STEPControl_Reader() tmp = tempfile.NamedTemporaryFile() with open(tmp.name, 'wb') as f: obj.download_fileobj(f) step_reader.ReadFile(tmp.name) step_reader.TransferRoot() myshape = step_reader.Shape() print("File readed") # Export to STL stl_writer = StlAPI_Writer() stl_writer.SetASCIIMode(True) mesh = BRepMesh_IncrementalMesh(myshape, 0.9) mesh.Perform() stl_writer.Write(myshape, output_file) print("Written") return output_file As you see, I gave the bucket url as output file but it doesn't work. Also it doesn't give any error. How can I write this file to S3 bucket? -
How can I order/sort a filtered search query and render it on another template on Django?
I am trying to change the ordering of a filtered search query on Django. I am using class based ListView for my search views. I am able to render a filtered queryset from search, but how can I change the order of the same queryset with the same searches and render it on another page. Kind of like how twitter can order searches by top or new. I tried making a different view and changing the order, but I am not sure how I can translate the same search query onto the new view. Please help! Below is my code. views.py class search_view(ListView): parameters captured in the url model = Post template_name = 'main/search.html' context_object_name = 'posts' paginate_by = 2 # searches through everything using Q import def get_queryset(self, *args, **kwargs): q = self.request.GET.get('q') self.posts = Post.objects.filter( Q(ticker__icontains=q) | Q(user__username__icontains=q) | Q(content__icontains=q) | Q(tags__name__icontains=q) ).annotate( upvoted=Exists(Post.upvotes.through.objects.filter( user_id=self.request.user.id, post_id=OuterRef('pk') ))).order_by('-date_traded') return self.posts template.html <a class="btn btn-secondary dropdown-toggle mb-3 ml-2" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Sort </a> <div class="dropdown-menu" aria-labelledby="dropdownMenuLink"> <a class="dropdown-item" href='?q={{ request.GET.q }}'>New</a> <a class="dropdown-item" href="#">Top</a> <!-- I would like to render the newly sorted results from here--> </div> <!-- the get request for the query--> <form class="form-inline" method="GET" … -
Json data get by key name in django loop
I have a json like : [{'name':'dd','name_ar':'ccc','price':'0.00'}] What i am doing in my code is given below: #customize service if sub.get("customized_services"): print(sub["customized_services"]) for f in json.loads(sub["customized_services"]): try: print(f['name]) except Exception as e: print(e) except Exception as e: print(e) pass but i am not getting the name after what i am doing wrong here can any one please help me related to this ????? -
Django GenericForeignKey how to get total value
my models class Vote(models.Model): user = models.ForeignKey('authentication.User', models.CASCADE, related_name='likes',) content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.IntegerField() rating = models.SmallIntegerField(default=0, validators=[MinValueValidator(-1), MaxValueValidator(1)]) created_at = models.DateTimeField(auto_now_add=True, null=True, editable=False) content_object = GenericForeignKey('content_type', 'object_id') class Post(models.Model): votes = GenericRelation(Vote) I need to get total rating from voted object how can i get it? def total_upvotes(self): self.votes__rating.?? return votes -
Perfom Django Validation for field that is NOT part of form
I would like to raise a ValidationError based on one of the fields in my Django model, without having the respective filed as part of a ModelForm. What I found after googling a bit is the concept of validators for models. So I tried to do the following: def minimumDuration(value): if value == 0: raise ValidationError("Minimum value accepted is 1 second!") class PlaylistItem(models.Model): position = models.IntegerField(null=False) content = models.ForeignKey(Content, null=True, on_delete=models.SET_NULL) item_duration = models.IntegerField(validators = [minimumDuration], default = 5, null=True, blank=True) playlist = models.ForeignKey(Playlist, null=True, on_delete=models.CASCADE) However, no error appears when I introduce 0 in the respective field. From Django's documentation I found out that validators are not automatically applied when saving a model. It redirected me to this page, but I don't really understand how to apply those. Any idea? -
Using permanent profiles and cookies in Selenium
I have a Django website and I'm using Selenium. I want to have one or two permanent profiles with Chrome or Firefox, to check that users remain logged in for example after I upgrade Django and then users login from another profile/session (the default is not to remain logged in, but I patched Django to remain logged in). For this I need permanent profiles and cookies. I want to login once, and then check that I'm still logged in the next time I run Selenium tests. I searched and found out this answer, but it's using Java and I need it with Python. It doesn't matter if I use Chrome or Firefox, but the best is to have permanent profiles and cookies with both of them. Is it possible? -
When does performance become an issue when writing html table to django template?
I am using Django to present users with transactional data, which could be a very large table of data. Just wondering if certain techniques are better than others when getting this data from the database (postgres) to the browser? Right now, I am: Generating the filtered queryset. Converting to a pandas df to apply some advanced operations. Pushing the pandas df to the html template and iterating over it to extract the contents of the df to the table. Using Bootstrap Tables (javascript) to paginate, sort by column, search etc. Just wondering if anybody has done this with reasonable amounts of data and whether performance was an issue? Are there any alternatives?? As a yardstick, say the size of the dataframe pushed to html template would be 50,000 rows. -
how to create a menu like Joomla menu for django?
how can I create a menu system for django that defines a url to articles, category lists, tagged items, etc? joomla menu: Each menu item defines an URL to a page on your site, and holds settings that control the contents (articles, category lists, tagged items, etc), view and style of that page -
How to add a different URL for each iteration in a for loop in Django?
I want to add a new URL link for each iteration in this for loop: <ul> {% for entry in entries %} <li>{{ entry }}</li> {% endfor %} </ul> This is my attempt, which I know is wrong because it is basically giving each entry the same CSS link: <ul> {% for entry in entries %} <li><a href = "{% url 'CSS' %}">{{ entry }}</a></li> {% endfor %} </ul> -
Race condition in django session
I have an API using django that uses session: def api_a(request): request.session["foo1"] = "bar1" return Response({}) def api_b(request): request.session["foo2"] = "bar2" return Response({}) If I call api_a THEN api_b, request.session is set to {foo1: bar1, foo2: bar2}, and that's the expected behavior. However, if I call simultaneously api_a and api_b (the calls are performed by a JavaScript front), it seems that when each call begins, request.session is empty, and each call saves the session with only one element, resulting request.session set to {foo1: bar1} (foo2 is missing) (or viceversa). Is there a way to change session behavior to resolve this race condition ? Note: session is configured with Redis (but I'm not sure it's relevant) : CACHES = {"default": {"BACKEND": "django_redis.cache.RedisCache",}} SESSION_ENGINE = "django.contrib.sessions.backends.cache" -
Django multiple images for post to render
For the past few days I have been trying to give access to the admin user to upload multiple images/slides for every single post, one idea I had in mind was nesting a for loop inside the posts for loop that for every post, render also every image associated with it but it seem's I cant get it quite right. class Post(models.Model): title = models.CharField(max_length = 128) image = models.ImageField(default = 'default.jpg', upload_to = 'post_pics') content = models.TextField() date_posted = models.DateTimeField(default = timezone.now) category = models.ForeignKey(Category, on_delete = models.CASCADE) def __str__(self): return f"{self.title} - {self.category}" def get_image_filename(instance, filename): title = instance.post.title slug = slugify(title) return "post_images/%s-%s" % (slug, filename) class Images(models.Model): post = models.ForeignKey(Post, default= None, on_delete = models.CASCADE, related_name= 'Images') image = models.ImageField( upload_to = get_image_filename, verbose_name = 'Images') def __str__(self): return f"imazh per {self.post}" and my Html: <div class="post-list-container"> {% for post in posts %} <article class="post-container"> <div class="post-top"> > Focus on the for loop here {% for post.Images in post.Images %} <img src="{{ post.Images.url }}"> {% endfor %} <div class="post-title"><a href="#"><h1>{{ post.title }} </h1></a></div> <div class="post-images"> <img class="rounded" src="{{ post.image.url }}"> </div> </div> <div class="post-middle"> <div class="post-content"><p> {{ post.content }}</p> </div> </div> <div class="post-bottom"> <div class="post-category"><a href="{% … -
Statics problem with django docker nginx gunicorn
I have a small problem with access to my django statics through nginx. I serve the django server running in a docker, on a url with a location in nginx: location /external/ { proxy_pass http://external; } For static configuration in nginx i add: location /external/static/ { autoindex on; alias /external/static/; } For the configuration of my statics on Django I set this code in the settings: STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/' + PREFIX + 'static/' ## -> with my config = /external/static/ In my Dockerfile I run my django server with gunicorn and I expose it through port 8000. When I access directly to the server with port 8000 (http://serveraddr.com:8000) I don't have statics problems but when I access it with nginx (https://serveraddr.com/external) I get a not found on my statics. Help me please -
Django TextField default value
In one of my tables I have a field game_fen_when_leave = models.TextField(). But it gives me an error "You are trying to add a non-nullable field 'game_fen_when_leave' to game without a default; we can't do that (the database needs something to populate existing rows)". Is it necessary for this field to have a default value? I saw an example without having a default. -
Django Oauth Toolkit customize validator
I swapped AccessToken model with my one, so it has relation to some Project model: class AccessToken(oauth2_models.AbstractAccessToken): """ Extend the AccessToken model with relation to projects. """ class Meta(oauth2_models.AbstractAccessToken.Meta): swappable = 'OAUTH2_PROVIDER_ACCESS_TOKEN_MODEL' project = models.ManyToManyField( Project, null=True, blank=True, related_name='project' ) Lets assume I get some incoming request which is executing some actions on some any objects related to this Project model: DELETE { "market": {"project_id": 2, "name": "EN"} } Authorization Bearer XXXX Now I`d like to check if the token of this incoming request has permissions to "deal" with this Project with id 2. I assume I need some custom validator MyValidator (some which are used in annotation @protected_resource(validator_cls=MyValidator)), but I cannot find any examples for that. And even not sure if it`s a valid/good approach at all maybe I should dig in another direction. -
how to compare two fields of different models in Django query-set?
Want to compare(if they are same or not) 'map_id' of 'map' model with 'uni_id' of 'Uni' model, return if they are same. Note: models map and Uni are also in different databases. Below are the two models: class map(models.Model): job_id = models.AutoField(db_column='job_id', primary_key=True) company = models.CharField(max_length=255, blank=True, null=True) map_id = models.CharField(db_column='Map_ID', max_length=255, blank=True, null=True) class Meta: managed = True db_table = 'Map' class Uni(models.Model): uni_id = models.BigAutoField(db_column='Uni_ID', primary_key=True) comp_name = models.TextField(blank=True, null=True) name = models.TextField(blank=True, null=True) class Meta: managed = True db_table = 'Uni' below is the code which i tried: obj_map = map.objects.using("Map").filter(map_id=pk).filter(map_id__in=F('uni_id')) -
I have an issue in django framework using mongodb database as backend the djongo models the code is as follows in models.py
This is the code which is in models.py file class ManageTribe(models.Model): _id=models.ObjectIdField() tribe_name=models.CharField(max_length=255) Date_created = models.DateTimeField(auto_now_add=True) Date_updated = models.DateTimeField(auto_now_add=True) objects = models.DjongoManager() def _str_(self): return self.tribe_name class User(models.Model): NORMALUSER = 'NOR' TRIBE_LEADER = 'TRL' SOCRAI_LEADER = 'SCL' SOCRAI_Admin = 'SCA' UserRoles = [ (NORMALUSER, 'NormalUser'), (TRIBE_LEADER, 'Tribe leader'), (SOCRAI_LEADER, 'Socrai leader'), (SOCRAI_Admin, 'Socrai admin'), ] _id=models.ObjectIdField() firstname=models.CharField(max_length=255) UserRoles = models.CharField(max_length=45,choices=UserRoles,default=NORMALUSER) lastname = models.CharField(max_length=255) password=models.CharField(max_length=255) username = models.CharField(max_length=255) current_level=models.CharField(max_length=255) current_level_point=models.IntegerField() leader_id=models.IntegerField() Date_created = models.DateTimeField(auto_now_add=True) Date_updated = models.DateTimeField(auto_now_add=True) tribename=models.EmbeddedField(model_container=ManageTribe,rel='tribe_name') objects = models.DjongoManager() def __str__(self): return self.firstname error is Value: ManageTribe object (None) must be an instance of <class 'dict'> The relationship is not created between to models -
Accessing data from a json array in python JSONDecodeError at /get/
My response looks like: [ {"_id":"5f6060d0d279373c0017447d","name":"Faizan","email":"faizan@test.com"} ] I want to get the name in python. I am tryting: response = requests.get(url) data = response.json() The error I am getting is: JSONDecodeError at /get/ -
Having an attribute error saying doesn't not have a attribute 'write'
[here is a photo of my cmd showing an attributeerror at base.py of my Django project. So I was able to track it there but can't see the cause of the error][ the other image is regarding my code at base.py file where the error is at. Please what's the cause of this error from the images I sent. Thanks in advance] -
removing cache of browser after clearing memcached from admin django
hello guys i want use memcached for one of my class like this: @method_decorator(cache_page(60 * 15), name='list') @method_decorator(csrf_exempt, name='list') class MostDiscountedCourses(generics.ListAPIView): and i use ajax for handling my request but i have a problem after clearing cache .my browser doesnt update if i dont use ctrl + shift + r. how can i handle it: the request of my header is this: {'Content-Length': '', 'Content-Type': 'text/plain', 'Host': '127.0.0.1:8000', 'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'Accept': 'application/json, text/javascript, /; q=0.01', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36', 'X-Requested-With': 'XMLHttpRequest', 'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty', 'Referer': 'http://127.0.0.1:8000/home/', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'fa-IR,fa;q=0.9,en-US;q=0.8,en;q=0.7', 'Cookie': 'pga4_session=cebb4feb-a0e0-477a-a580-651f8253b53f!tOhsFlL10HtTWOK6V0xwiTAjTcU=; csrftoken=MSqcZhyhrQjACjP5Qk18mDa27lL2XGYWQWAHBtd1UJa4D5gcklFt2G6z018nMt0o; sessionid=b3umdoks9u40n231olvmz99j3c81if22'} i thanks alot if anybody know it help me. -
Variable not reassigned in Django template
I am trying to reassign a variable in a for-loop. Depending on the value, I will proceed to do other things, before resetting it to another default. However, the value is not being replaced properly within the loop. These are my template tags: @register.filter def addition(val1, val2): return val1 + val2 @register.simple_tag def assignVar(arg1): return arg1 Here is a portion of my full template {% assignVar 50 as testVar %} <table> <tbody> {% for data in LIST %} <tr> A: {{testVar}} {% assignVar testVar|addition:20 as testVar %} B: {{testVar}} {% if testVar > 150 %} {{data}} {% assignVar 0 as testVar %} {% endif %} </tr> {% endfor %} </tbody> </table> My output is as such: A: 50 B: 70 A: 50 B: 70 A: 50 B: 70 ... Why does my testVar value not increase? Each time it loops, the testVar variable keeps going back to the initial value instead of being replaced with the new one. This was what I expected: A: 50 B: 70 A: 70 B: 90 A: 90 B: 110 ... -
Django 3.1 admin with tornado integration
There are multiple talks of integrating django with tornado. But they're all at least 3 years old and no longer up to date since django is (partly) async now, and tornado as well supports native async coroutines. Therefore it should be easier to integrate django with tornado, right? I only need admin interface from django. Therefore the question - how to do it? Does anyone already has an experience doing that? Some specifics: I still use tornado 5.1, haven't migrated yet. Python 3.8.5 Postgres 13 with asyncpg as an interface. Would hear any helpful thoughts on a subject. -
issue in redirecting user to home page django
When I try to login, it does not reedirect me to home page. instead, it shows me an error the url should be http://127.0.0.1:8000/ it shows http://127.0.0.1:8000/login I tried to user both function and path names urls.py app_name = "accounts" urlpatterns = [ path('', views.home,name="home"), path('register/',views.register, name='register'), path('login/',views.loginPage, name='login')] views.py def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request,username=username, password=password) if user is not None: login(request,user) return redirect('home') return render(request,'accounts/login.html') Error NoReverseMatch at /login/ Reverse for 'home' not found. 'home' is not a valid view function or pattern name. Request Method: POST Request URL: http://127.0.0.1:8000/login/ Django Version: 3.0.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'home' not found. 'home' is not a valid view function or pattern name. Exception Location: C:\Users\Mahmoud Ishag\AppData\Local\Programs\Python\Python37\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677 -
why topic object is showing instead of topic name
instead of topic name why it is showing topic object import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'third_project.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
including model to my Django app, no access: ImproperlyConfigured
I'm creating Django app, which should receive user questions, transfer them to the database, display some ML model answers and allow users to evaluate these answers. So, I've created model.py with class Dialog(models.Model) with text field, but there is some problem with including. models.py Dialog(models.Model): user_message = models.TextField(max_length=500, default="Hello world!") messages = models.Manager() def __str__(self): return f'User message: {self.messages.all()}' then I've changed settings.py: INSTALLED_APPS = [ 'django.contrib.staticfiles', # 'dialog.models.Dialog', # all variants that I tred # 'dialog.apps.DialogConfig', 'dialog', ] And add app.py: from django.apps import AppConfig class DialogConfig(AppConfig): name = 'dialog' but when I try to connect to my server, I get Atribute Error "Manager isn't accessible via Dialog instances". Then I've tried to run my models.py aim check the problem and I get: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. So, I tried several variations in settings.py and I have os.environ['DJANGO_SETTINGS_MODULE'] = 'chatbot.settings' either in settings.py and wsgi.py There is a structure of my project: bot_infr - chatbot - chatbot -__init__.py - asgi.py - settings.py - urls.py - wsgi.py - dialog - migrations - __init__.py - admin.py - apps.py - forms.py - models.py … -
check if Django is running background tasks
I am developing a django website. There is a function which is to read a large PDF and may use several minutes to complete the task. But I found out when running the function, user can actually refresh the page or leave the page. As you can see from the above screenshot, I actually jump to the admin page and it can still continue to read the PDF. But the server will fail if I upload another new PDF and run the same function again. What I want to achieve is a function like this: def readPDF(pdf_file): if There is there is another readPDF() is running: ignore else: read the PDF (Start the task) So I want to ask if there is any method to check whether the job is running, or any other method or idea to achieve my purpose??