Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can anyone help me out this? [closed]
>>> django.setup() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) -
my default python3 is 3.5 , how to install django for python 3.6 on Ubuntu?
used pip method(pip3) I used pip3. But it installs django for default python3 version i.e,3.5. -
{% csrf_token %} printing as text from js file django
{% csrf_token %} printing as text from js file in Django the code is working if use it in script tag but when I try to use from an external js file it doesn't work {% csrf_token %} printing as text from js file in Django the code is working if use it in script tag but when I try to use from an external js file it doesn't work {% csrf_token %} printing as text from js file in Django the code is working if use it in script tag but when I try to use from an external js file it doesn't work HTML <div class="box container" id="box2"> <div class="skillbox"> <div class="workquestion"> How Many work Exprience you wanted <br> to add in your resume ? </div> <div class="row" id="butt"> <div class="form-group col-md-2"> <button type="button" class="btn btn-success" onclick="updateform(1)" id="butt1">1</button> </div> <div class="form-group col-md-2"> <button type="button" class="btn btn-success" onclick="updateform(2)" id="butt2">2</button> </div> <div class="form-group col-md-2"> <button type="button" class="btn btn-success" onclick="updateform(3)" id="butt3">3</button> </div> <div class="form-group col-md-2"> <button type="button" class="btn btn-success" onclick="updateform(4)" id="butt4">4</button> </div> <div class="form-group col-md-2"> <button type="button" class="btn btn-success" onclick="updateform(5)" id="butt5">5</button> </div> <div class="workquestion" style="color: red;"> Maximum </div> </div> <div class="row" > <div class="form-group col-md-2"> <button type="button" class="btn btn-success" onclick="updateform(6)" id="butt6">6</button> … -
Django get total count and count by unique value in queryset
I have models Software and Domain described loosely as: class Software(models.Model) id = models.BigInteger(primary_key=True, db_index=True, null=False) company = models.ForeignKey('Company') domain = models.ForeignKey('Domain') type = models.CharField(null=False) vendor = models.CharField(null=False) name = models.CharField(null=False) class Domain(models.Model): id = models.BigInteger(primary_key=True, db_index=True, null=False) type = models.CharField() importance = models.DecimalField(max_digits=11, decimal_places=10, null=False) And I get a Software queryset with: qs = Software.objects.filter(company=c).order_by('vendor') The desired output should have an aggregated Domain importance with total count for each unique Software, i.e. [ { 'type': 'type_1', \ 'vendor': 'ajwr', | - unique together 'name': 'nginx', / 'domains': { 'total_count': 4, 'importance_counts': [0.1: 1, 0.5: 2, 0.9: 1] # sum of counts = total_count }, }, { ... }, ] I feel like the first step here should be to just group the type, vendor, name by Domain so each Software object has a list of Domains instead of just one but I'm not sure how to do that. Doing this in memory would make it a lot easier but it seems like it would be a lot slower than using querysets / SQL. -
how to create a navigation menu system with Django?
I want to create a dynamic menu for my weblog made by Django. but I don't know where to start the menu should be able to define url for every object in the database (posts, pages, tags, ... ). how can I do that ? the menus of Joomla and wordpress system are good examples for what I expect. -
Can't type password in my PyCharm terminal (for Django admin)
I am new to Python and Django. I was trying to create an admin user for the first time. But for some reason, I can't type anything in my password section. Whatever I type, I can't see any output in PyCharm terminal: https://prnt.sc/uhnyp5 (Same goes for windows cmd). Would you please help me to solve this? Regards. -
Sharing domains with 2 different sites
I have a a pre-existing square-space blog with a domain hosted by square-space and I wish to share the domain name with a new django application that is hosted on linode, is it possible? -
Exporting to mdb file formats using django admin
I'm new to both python and Django. I've been working on a task using Django import export. If possible I'm looking for a way to export models into the .mdb format using Django. Any help would be much appreciated, thank you. -
Django: TemplateSyntaxError: Could not parse the remainder (extends tag)
I'm getting this error when I go to http://127.0.0.1:8000/ I've gone through other similar threads and have tried playing around with spaces as well as single and double quotation marks but with no luck. I'm trying to have the index.html file inherit the code in master.html, which is contained in a folder structure that looks like this. Here are a few snippets of some of the files that I think are causing this error: from settings.py: BASE_DIR = Path(__file__).resolve().parent.parent INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tracker', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] from index.html (this is the only line in this file) {% extends ‘layouts/master.html’ %} from views.py # Create your views here. from django.shortcuts import render def index(request): return render(request, 'index.html') Error traceback: Exception Type: TemplateSyntaxError at / Exception Value: Could not parse the remainder: '‘layouts/master.html’' from '‘layouts/master.html’' What seems to be causing the syntax error? Thanks in advance -
Django format `Available user permissions`, i.e. make Title case
So Django docs recommend setting model's verbose_name and verbose_name_plural in lowercase, and then capitalizing it when required. However in the djangop admin under Home › Authentication and Authorization › Users › username It uses the lowercase verbose name. How does one capitalize the app labels and model names. E.g. For the row selecting, and it would become: Auth - Group | Can add group -
django social auth does not create user profile
I have profile with django social-auth, when users using social auth, their data is only avaiable in social auth(a), not default django profile (b). screenshot from django admin-panel What I should do? -
Throttling users based on their groups
I'd like to limit form requests for users based on their group for a Saas application (Free, Paid), so if a free user hit their limit, they get redirected to another page or show a pop-up I tried using throttling but I can't figure out how to implement the conditions settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication'], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.UserRateThrottle', 'contact.throttling.FreeDailyRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'user': '5/second', 'Free': '200/day' } } views.py class FreeDailyRateThrottle(UserRateThrottle): scope = 'Free' user = request.user if user.groups.filter(name=Free).exists() : #i'm not sure what to do here! else : #redirect to a different page @login_required(login_url='login') @api_view(['POST']) @throttle_classes([FreeDailyRateThrottle]) def ad_gen(request): context ={} if request.method!="POST": return render(request , 'Ad Gen.html' , context) else: // some logic return render(request , 'Ad result.html' ,context) -
How to create settings like AUTH_USER_MODEL for own model in django?
Suppose i've model called class A(models.Model): name = .... age = .... Now I want to access this model using settings file. for example, we can access User model using django settings file like this from django.conf.settings import AUTH_USER_MODEL Now I wan't to achieve same behavior for my custom model. I'm not sure this is possible or not. -
Django, How to update image
I hope the title is enough to understand my problem, as you can see in the image below, i can get the pciture from my database, the problem is when I update the data and I didnt change the picture displayed, it makes an error, the cause of the error is I didnt get any data from html <label for="myfile3"> <img id="output3" src="{{selectbanner.image.url}}" style="height:225px;width:250px;" class="subimage"/><br> <input type="file" accept="myfile" id="myfile3" name="image" value="{{selectbanner.image.url}}" onchange="loadFile3(event)" > </label> <script> var loadFile3 = function(event) { var reader = new FileReader(); reader.onload = function(){ var output3 = document.getElementById('output3'); output3.src = reader.result; }; reader.readAsDataURL(event.target.files[0]); }; </script> this is my views.py image = request.FILES.get('image') print(image) update = Banner.objects.get(id=banner_id) update.image = image update.title = Title update.sub_title = Sub update.description = Description update.save() return redirect('Banners') -
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="{% …