Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin URL conflict with slug in URL
I want to redirect news to http://localhost/<CATEGORY>/. But Django admin does not work anymore. How I can fix this in urls.py? url(r'^', include('website.urls')), url(r'^admin/', admin.site.urls), Django tries to find admin category and raise error. -
How to pass database queryset objects from class based views(class SignUp(generic.CreateView)) to templates in Django
views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views import generic from .forms import CustomUserCreationForm class SignUp(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' urls.py urlpatterns = [ url(r'signup/', views.SignUp.as_view(), name='signup'), url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), ] I used django custom user creation method to sign up users, its working fine. But how to pass objects to templates in my class SignUp. I'm new to class based view. Please help me. -
Calling Django view from AJAX function
I have a button which passes ID of an object. On pressing of button i want that its corresponding Django view should be displayed. views.py from django.views.decorators.csrf import csrf_exempt @csrf_exempt def updateUser(request, id): user= get_object_or_404(CustomUser, pk=id) if request.method == 'POST': form = UpdateUser(request.POST, instance=user) try: print("DJANGO VIEW") if form.is_valid(): form.save() messages.success(request, ("New user account has been created")) else: messages.warning(request, ("Data in fields is incorrect, please try again")) except Exception as e: messages.warning(request, ("Error: {}". format(e))) else: form = UpdateUser(instance=user) context ={'form': form, 'user': user,} return render(request, 'user/updateUser.html', context) urls.py path('updateUser/<int:id>/', views.updateUser, name="updateUser"), my.js function myfunction($this) { var stid = $this; console.log("button clicked"); var request_data = '/user/updateUser/'+stid; alert(request_data); console.log("data: " + stid); $.ajax({ url: "../updateUser/" + stid+"/" , contentType: "application/json; charset=utf-8", processData: true, type: 'post', dataType: 'html', success: function (data) { alert("Success"); $("#updateUser").html(response); }, error: function (xhr, textStatus, errorThrown) { alert(textStatus + ':' + errorThrown); } }); } Django view is called but the view is not displayed. Button should render the respective page. -
How to post file and payload from angular
I would like to post files together with some payload/security information HTTP client only allow three parameters which I have used for url , file and httpoptions. I can successfully post it in python requests but struggle to post it in angular ... My code in Angular(which I cannot find a way to put in the payload/security information.. addS3file (s3file: S3File, url: string, data:string): Observable<S3File> { return this.http.post<S3File>(url, s3file, httpOptions).pipe( tap((s3file: S3File) => this.log(`added s3file w/ id=${s3file.id}`)), catchError(this.handleError<S3File>('adds3file')) ); } Code in Python Direct to s3 via Python file_path = 'screen.png' with open(file_path, 'rb') as data: files = {'file': data} url = post_data['url'] request_data = post_data['fields'] r = requests.post(url, data=request_data, files=files) appreciate if someone can show me how to post in angular similarly to python's requests.. -
django use template tag in has_perm()
I my project I have to use a model less permission. I wrote my own template tags in order to show or not an action button or content in a template. Here my template tags: from django.template import Library from django.contrib.auth.models import Permission register = Library() @register.filter(name='is_allowed_for') def is_allowed_for(permission, user): if user.is_superuser: return True user_group_permissions = Permission.objects.filter(group__user=user).values_list('codename', flat=True) if permission.title() in user_group_permissions: return True return False @register.filter(name='in_department') def in_department(permission, department_name): if permission != '': new_permission = department_name.title() + '.' + permission.title() else: new_permission = department_name.title() return new_permission In my template this works like expected: (department_name is passed from the view) {% if 'Dashboard.View'|in_department:department_name|is_allowed_for:user %} has Department Dasboard view {% else %} has not Department Dasboard view {% endif %} This does not work, I receive a TemplateSytaxError: {% if user.has_perm('Dashboard.View'|in_department:department_name) %} has Department Dasboard view {% else %} has not Department Dasboard view {% endif %} Isn't the tag applied before the has_perm method is called? Or what is wrong...? Thx for any help. -
How can i make this shorter in jquery
i have a formset in Django. On a select field which i have attached given numbers, I would like to display depending on the number selected correspondingly many forms in the formset. How can i abbreviate my code? Or is there a better way to access ID's in a formset? $("#id_personenanzahl").change(function() { if ($("#id_personenanzahl").val() == "0"){ $("#id_form-TOTAL_FORMS").hide("fast"); } else { $("#id_form-TOTAL_FORMS").hide("fast"); } if ($("#id_personenanzahl").val() == "1"){ $("#div_id_form-0-vorname").show("fast"); $("#div_id_form-0-nachname").show("fast"); $("#div_id_form-0-geburtsdatum").show("fast"); } else { $("#div_id_form-0-vorname").hide("fast"); $("#div_id_form-0-nachname").hide("fast"); $("#div_id_form-0-geburtsdatum").hide("fast"); } if ($("#id_personenanzahl").val() == "2"){ $("#div_id_form-0-vorname").show("fast"); $("#div_id_form-0-nachname").show("fast"); $("#div_id_form-0-geburtsdatum").show("fast"); $("#div_id_form-1-vorname").show("fast"); $("#div_id_form-1-nachname").show("fast"); $("#div_id_form-1-geburtsdatum").show("fast"); } else { $("#div_id_form-1-vorname").hide("fast"); $("#div_id_form-1-nachname").hide("fast"); $("#div_id_form-1-geburtsdatum").hide("fast"); } if ($("#id_personenanzahl").val() == "3"){ $("#div_id_form-0-vorname").show("fast"); $("#div_id_form-0-nachname").show("fast"); $("#div_id_form-0-geburtsdatum").show("fast"); $("#div_id_form-1-vorname").show("fast"); $("#div_id_form-1-nachname").show("fast"); $("#div_id_form-1-geburtsdatum").show("fast"); $("#div_id_form-2-vorname").show("fast"); $("#div_id_form-2-nachname").show("fast"); $("#div_id_form-2-geburtsdatum").show("fast"); } else { $("#div_id_form-2-vorname").hide("fast"); $("#div_id_form-2-nachname").hide("fast"); $("#div_id_form-2-geburtsdatum").hide("fast"); } }) Below my code as i have the formset built into the template. <div class="main main-raised"> <div class="container"> <div class="row"> <div class="col py-5"> <form class="form-daytrip-ajax" action="." method="post"> {% csrf_token %} <h3>Ihre Reisedaten</h3> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.reiseziel|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.datum_abfahrt|as_crispy_field }} </div> </div> <h3>Rechnungsadresse</h3> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.vorname|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.nachname|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col mb-0"> {{ form.adresse|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-4 … -
How to format elements accessed from a many to many relationship?
I'm sorry for the noob question, I just started learning Django.. I have a manytomany relationship in a model, and I'm trying to format the output of that model to include all the elements in the many to many relationship. I figured out how to access them, as just using self.toppings resulted in orders.Toppings.none. Now I have a query set returned. I'm assuming I have to iterate over the items in the query set to format the string, but I'm not sure how to do that and also return the string, unless I should store the data in a new list prior to retuning.. I also tried forcing it to format as a list (per Djangos docs) like this: def __str__(self): return f"{self.item} with {list(self.toppings.all())}" But it is formatted the same. Here's my code for context: class CreatedItem(models.Model): item = models.ForeignKey(MenuItem, on_delete=models.CASCADE, related_name="createdItem") toppings = models.ManyToManyField(Topping) def __str__(self): return f"{self.item} with {self.toppings.all()}" -
Django virtualenv name forgotten
I have created and worked on a Django application (Simple website with user registration and login) without ever closing the virtualenv i was working on. Now that some time went through I can't remember the name of the virtualenv I was working on and so I can't activate it. How can I find the name of the virtualenv? The name of the directory of my django app is "uniweb" and is on the desktop of my computer. I haven't yet put it on Github. -
Why doesn't Vue show up?
I just started to learn using Vue. I wrote really simple code like the following. <!DOCTYPE HTML> <html> <head> </head> <body> <script src="https://unpkg.com/vue"></script> <div id="app"> <h2>{{number}}</h2> <h2>Here it is!</h2> </div> </body> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { number:0 } }) </script> </html> However, there is no number value. I definitely checked network by chrome dev tool and I got successfully vue.js from https://unpkg.com/vue@2.5.22/dist/vue.js What's wrong with it? -
How to decide granularity when it comes to test cases?
I have written a permissions middleware for a python/django API. Now the permissions depend on the combination of 4 different attributes let's call them a b c and d Further c and d can be 1) Empty 2) Singular or 3) Multiple values so the combinations even increase further. Initially I decided to write a single test case which would generate the combinations and map the expected outcome using truth tables. # Generate all possible combinations possible_combinations = list(itertools.product([0, 1], repeat=len(possible_values))) for combination in possible_combinations: # Get expected result for this combination expected_result = get_expected_result( test_type=test_type, combination=combination, possible_values=possible_values) Based on the combination value, set as 0 or 1 I decided the values of a b c and d Now I am doing this as part of a new team and the team members came back with a criticism of the approach as it is not granular and doesn't follow best practices of having a test case do one thing. My view on best practices is that they should very clearly and obviously serve a purposes and the purpose can depend on the task or team at hand. In this particular case the team members failed to suggest why writing this … -
user order_by() seperate from query
I am retrieving some Posts using order_by in my for loop as given below all_posts = [] for foll in followings: all_posts += Posts.objects.all().filter(user_profile=foll.id).order_by('trending_ratio') It sorts the Posts for each user, but I want to sort all post based on their trending ratio. for e.g the above code sorts all posts of user1 based on their tending_ratio, then it sorts posts user2 based on trending_ratio and so on. But, I simply want to perform sorting after all the posts from all users is stored in all_posts i.e all_posts.order_by('trending_ratio') after my for loop execution -
Is there a Django decorator to prevent mutating underlying object?
Is there a Django @decorator I can attach to a model's method that would prevent that method from making any changes to the database? I think of the right expression to Google for. -
Django Cassandra Map field
I am trying to use Django cassandra to build restful server. In my DjangoCassandraModel I want to create a columns.Map field. However, as per my understanding, DjangoCassandraModelSerializer does not support Map field. As I request a url which uses the serializer, it raises the following error for the Map field. Exception Type: KeyError Exception Value: 'Class Map not found in lookup.' Exception Location: /home/saikat/.conda/envs/django-nonrel/lib/python3.6/site-packages/rest_framework/utils/field_mapping.py in __getitem__, line 40 Is there any workaround to use map field for Django Cassandra serializer? The following is my model snippet. class ShopProfileModel(DjangoCassandraModel): shop_id = columns.Ascii(required=True, index=True) owner = columns.Ascii(required=True, index=True) shop_name = columns.Text(required=True, index=True) shop_details = columns.Map(required=False) The Serilizer field is below. class ShopSerializer(DjangoCassandraModelSerializer): class Meta: model = ShopProfileModel fields = ('shop_id', 'shop_name', 'owner', 'shop_details') -
Why django object related fields are not updated when changed from outside?
user1 = User.objects.create(username="user") # user1, user2 are actually pointed to the same record user2 = User.objects.get(username="user") # profile is a one-to-one related object of User, created by post_save after User created user2.profile.bio = "abc" user2.save() if user1.profile.bio == "abc": # False ??? pass I expected that after user2 changed the profile, user1.profile should automatically be updated, but it's not. Why? (Django 2.1.5) -
Django: Is there a way to set argument of templatetag using javascript?
What I'm trying to do is to create a form on modal-like fixed element. And I' having trouble associating an child object with the parent object. For the page, there are a bunch of posts and when the user push the comment button, the modal shows up. The first problem is the templatetag's argument doesn't work as expected when I use it inside loop. All the argument is going to be the one with first loop. So I moved the form element and now I'm trying to pass the argument to the templatetag using javascript but I don't know a good way to do it. My code is like this. {% for entry in entries %} ... <a class="btn" onclick="showCommentForm(this)" data-id="{{ entry.pk }}">Comment</a> {% endfor %} {% render_comment_form entry as comment_form %}<!-- How I can pass argument here? --> <div id="comment-form-section" style="display: none;> <form id="comment-form" method="POST" action="" novalidate> {% csrf_token %} <div class="form-group"> <div> <div> {{ comment_form.text|add_class:'form-control' }} </div> <div> <button type="submit" name="comment_form" class="btn btn-outline-primary">Post</button> </div> </div> </div> </form> </div> templatetag @register.simple_tag(takes_context=True) def render_comment_form(context, entry): request = context['request'] if request.method !='POST': comment_form = CommentForm(user=request.user, entry=entry) return comment_form I need to associate the comment with an entry here. and js function … -
my 127.0.0.1:5000 page is not getting refresh using flask python and HTML ,css
i am using flask as web frame using python. i am facing the following problem http://127.0.0.1:5000/profile/World page is not getting refresh , even thought when i change content in my profile.html page, it is loading previously loaded content. its not getting refresh. and when i use style.css and call the link in profile.html , css file is not working. from flask import Flask, render_template app = Flask(name) app.debug = True @app.route('/profile/') def profile(name): return render_template("profile.html", name=name) if name == "main": app.run(debug=True) Flask welcome to Flask World, {{name}} `h1{ color: aquamarine; } Thank you all -
AttributeError - 'DeferredAttribute' object has no attribute 'all'
I keep getting an error in posts = Post.published.all() This is my models.py in Django 2.0 from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): STATUS_CHOICES = ( ('draft','Draft'), ('published','Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='published') author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE) body = models.TextField() published = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices = STATUS_CHOICES, default='draft') def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) class Meta: ordering = ('-published',) def __str__(self): return self.title This is my views.py from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish_year=year, publish_month=month, publish_day=day) And I keep getting this error whenever i run my server... AttributeError at /blog/ 'DeferredAttribute' object has no attribute 'all' from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request): posts = Post.published.all() ... Also some tips to make my own blog page would be helpful`` -
How do I get Django StaticLiveServerTestCase to use an existing database
I have a Django server running on an AWS EC2 instance at 0.0.0.0:8000. This instance host my development site (staging site) and I want to run tests against the actual Postgres DB associated with this instance (on RDS) using selenium. I am trying to run some Functional Tests (inherit from StaticLiveServerTestCase) against this server from my local machine. When I run my FT's against the server running on my EC2 instance, I use STAGING_SERVER=instanceID.us-east-2.compute.amazonaws.com:8000 python manage.py test functional_tests Inside my Functional Tests I set the live_server_url attribute to the STAGING_SERVER environmental variable declared in the console command. staging_server = os.environ.get('STAGING_SERVER') if staging_server: self.live_server_url = 'http://' + staging_server The issue I'm having is that inside of my test classes I create objects via model methods because I need to populate the DB for some of my tests. For example, I need to create users so that I can log them into the site. The issue I'm having is that the browser via selenium interacts with my staging server at 0.0.0.0:8000 which also interacts with my actual database, but the objects created inside my test classes are being inserted into the test_database created by the TestCase class, i.e. I have two databases … -
How to use nested anchor tag within a ul > li
I'm working on a project using Python(3.7) and Django(1.10) in which I have a model of Categories for categories and subcategories for products, now I need to add a list of all categories on the frontend to filter the products. The categories are listing correctly, but the links for all subcategory within each Parent category is loading the same URL, I believe there's something wrong with my HTML template, because when I check the inspect element the links are loading correctly but when I click it loads the same URL. For example: If we have two categories with ids: 2 & 3 under parent id 1 The links are displaying the right id in URL(check-in inspect element) but on click, it always loads the page with the first id link. A testing url: http://www.orderfetchers.com/grocery_order Here's what I have tried: From models.py: class Categories(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=200) parent_id = models.IntegerField(null=True) position = models.IntegerField(default=0) enable_flag = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.id) From views.py: all_category = Categories.objects.filter(parent_id__isnull=True, enable_flag=1) all_subcategory = Categories.objects.filter(parent_id__isnull=False, enable_flag=1) ****from html template:*** <div class="sidebar_block cat_block"> <h5 class="s_block_head">Product Categories</h5> <ul class="p_c_list"> {% for cat in all_category %} <li class="cat_list_item" id={{ cat.id }} … -
django email validation issue
I'm trying to create a custom column type using django_tables2 so that I can render contact details as a mailto: link when the result is a valid email address, and just standard text otherwise. The issue that I'm having is that my value seems to be returned as iterated characters, and as per the code below, the first character of the email address is render as part of mailto: whilst the second character of the email address is rendered in the column. Aside from validate_email I have tried if "@" in and regex, all returning the same iterated character results. class ContactColumn(tables.Column): def render(self,value): try: validate_email(value) return format_html('''<a href="mailto:{}">{}</a>''',*value) except ValidationError: return value Can anyone point me in the right direction as to how to successfully render either a mailto: link or just standard text based on valid email address? Any help is much appreciated! -
How do I iterate over or access the @property of a related model in another @property?
I'd like to return a sum of fields (with @property) from a related model, that is itself the same type of sum (again using @property). I'm running into an issue that the Queryset that is being created in the ExpenseCategory model is either not iterable, or that the 'total_amount' is not a field in the related model (which is understandable). How should I approach this? class ExpenseCategory(models.Model): name = models.CharField(max_length=255, blank=False) @property def total_amount(self): expenses = self.category_expenses.all() return expenses.aggregate(Sum('total_amount')) class ExpenseLineItem(models.Model): category = models.ForeignKey(ExpenseCategory, related_name='category_expenses') amount = models.DecimalField(max_digits=20, decimal_places=2, blank=True, default=0) @property def total_amount(self): return self.amount -
Django: How can the size of textarea change depending on the size of the screen?
How can the size of Django form textarea change depending on the screen size? I created a form on fixed area and want to change the textarea size depending on the screen size but I don't know how to do it. Even when the screen size gets smaller, the textarea size cannot change. Currently my code is like this. <div style="background-color: #fff; position: fixed; bottom: 0px; right: 0; left: 0; height: 320px; max-width: 800px; margin-left: auto; margin-right: auto; margin-bottom: auto;"> <form method="POST" novalidate> {% csrf_token %} <div class="form-group"> <div> <div> {{ message_form.text|attr:"rows:10"|attr:"cols:80" }} <div> <button type="submit" class="btn btn-outline-primary">Send</button> </div> </div> </form> </div> -
Loop through nested list and retrieve attribute (python)
I'm trying to loop through a json object to retrieve data in a list called matched-bets when I try this I get a KeyError: 'matched-bets' How do I retrieve attribute from nested list? data = [ { "TIMESTAMP": "2019-01-17 23:03:05.353141", "id": 1017749216980022, "event-id": 1016778383070015, "event-name": "Grigor Dimitrov vs Thomas Fabbiano", "created-at": "2019-01-17T13:29:53.128Z", "status": "matched", "in-play": false, "matched-bets": [ { "id": 1017749216980222, "offer-id": 1017749216980022, "odds": 10.6, "odds-type": "DECIMAL", "decimal-odds": 10.6, "stake": 5.0, "potential-profit": 48.0, "commission": 0.1, "currency": "EUR", "status": "open", "created-at": "2019-01-17T13:29:53.128Z" } ], "Latency": 0.069594 }] for d in data: id = d['matched-bets'][0]['id'] print(id) -
upload a file to S3 without creating a temporary local file
I am trying to save a signature in s3 database. 1- so, first i get image of signature in encoded base64 format. 2- then i split base64 tag from rest of the string, then decode it and save it to a variable. 3- then create a file name. 4-then i open that file and write the string in that.This process creates a local file in my project. then i upload that file to S3 and delete it. class SaveSignature(View): def post(self,request): config = GetConfig().config(request) tub = config['tub'] CLOUD_FRONT_URL = config['CLOUD_FRONT_URL'] host_ = "https://" user_id = request.session.get('user_id') image_data = request.POST.get('d') format, imgstr = image_data.split(';base64,') ext = format.split('/')[-1] data = base64.b64decode(imgstr) file_name = str(user_id)+"_signature" +"."+ ext user_signature = "{}/Signature/{}".format(user_id,file_name) sign_url = host_ + CLOUD_FRONT_URL + user_signature with open('static/user_signature/'+file_name, 'wb') as f: f.write(data) s3.meta.client.upload_file('static/user_signature/'+file_name,BUCKET, user_signature, ExtraArgs={'ACL':'public-read'}) though this method works but i want to upload directly without creating an extra file and writing extra code for it. But i'm not able to figure it out how to do so! -
3 OR conditions in single queryset filter
I'm trying to use 3 or statements in a single filter, but it isn't working. cart = carts.filter(Q(status='completed') | Q(status='paid') | Q(status='started')) Do you know what the correct syntax is? Thanks!