Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter by Users Group
I only want to show buttons based on a user group. In this example I have a list of buttons then an IF Statement that checks if the user is in the group 'Recruiter', if they are then it displays some additional buttons: Is there an easier way to do this in the html, like {% if request.user.groups == 'recruiter' %} Views.py fields = request.user.groups if fields == 'Recruiter': fields1 = 'True' else: fields1 = '' context['fields1'] = fields1 html {% if fields1 %} a bunch of buttons {% endif %} -
How to use custom YAML file as API documentation in Django REST Framework?
I need to add API documentation to my project. I wrote my custom schema using swagger editor and now I have a YAML file as follows: swagger: "2.0" info: description: "This is the documentation of Orion Protocol API" version: "1.0.0" title: "Orion Protocol API" host: "127.0.0.1:8000" basePath: "/api/" paths: /api/decode: post: tags: - "pet" summary: "Decode the payload" consumes: - "application/json" produces: - "application/json" parameters: - in: "body" name: "body" description: "Packet data" required: true schema: $ref: "#/definitions/PacketData" responses: "405": description: "Invalid input" /api/encode: post: description: "Encoding configuration parameters for the devices" produces: - "string" parameters: - in: "body" name: "body" description: "Addresses and values of configuration parameters" required: true schema: $ref: "#/definitions/ConfigPayload" responses: "405": description: "Invalid input" definitions: PacketData: type: "object" required: - "payload" properties: payload: type: "string" description: "Packet string starting with 78" example: "78010013518BB325140400000500000AAA0000002A6E0000004AC05D00006A00000000" ConfigPayload: type: "object" properties: Addresses of the configuration parameter: type: "string" description: "According to the documentation of configuration protocol" example: "542" Now how can I add this to the project? Where it should locate in the project? May the views render this file? I need to have the following path: urlpatterns = [ path('documentation/', some-view-that-will-render-yaml) ] -
How to Use Q to filter using String
Suppose I can have these lists of strings(I already know how to get these list of strings from the user): {"title, "year", "stars"} and {"title"}. If I get the 1st one from the user, I want to filter the Movie objects such that it works like: Movie.objects.filter(Q(title__icontains=query) | Q(year__icontains=query) |Q(stars__icontains=query)). If i get the 2nd one from the user, it is like Movie.objects.filter(Q(title__icontains=query) We have assured that the string in the list is a field of model. -
who to pass the id from template to view
this is my view : def delete_chat(request, id): chat=get_object_or_404(Chat,id=id) chat.delete() return redirect('msgs:inbox') and this is my template: <a href="{% url 'msgs:delete_chat' id=Chat.id %}" class="parag delete-btn">Delete chat</a>'+ and this is the error : NoReverseMatch at /messages/inbox/ Reverse for 'delete_chat' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['messages\\/inbox\\/delete\\/$'] can someone plz help me to figure out who to pass the id? -
Django Formset Delete Field Not Showing
I need to manually render my formset in my template and I cannot get the delete checkbox field into the template when I render manually. However, it does show when I render {{form.as_table}}. views.py QuoteManifestForm= modelformset_factory(QuoteManifest, QManifestForm, can_delete = True) template - this does not display the {{form.DELETE}} but every other field shows fine, including id which I can see in the DOM. {{ manifest.management_form }} <--!I passed QuoteManifestForm to template as 'manifest'--> {% for form in manifest.forms %} <div id="form_set"> <table id = 'manifest-table25' class="manifest-table2" width=100%> {% csrf_token %} <tbody width=100%> <tr class="manifest-row"> <td width = 17.5% class="productCode" onchange="populateProduct(this)">{{form.ProductCode}}</td> <td width = 32.5% class="description">{{form.DescriptionOfGoods}}</td> <td width = 12.5% class="quantity" oninput="calculateUnit(this)">{{form.UnitQty}}</td> <td width = 12.5% class="unitType">{{form.Type}}</td> <td width = 12.5% class="price" oninput="calculate(this)">{{form.Price}}</td> <td width = 12.5% class="amount2">{{form.Amount}}</td> <td>{{form.DELETE}}</td> {{form.id}} </tr> </tbody> </table> </div> {% endfor %} Any idea why that is not working? -
Django user specific transfer of files/images/pdf
Consider there are two types of users 1. Creator. 2. Approver. The creator will upload a file and process it by clicking a button (by the way the file should not be in his queue) now, the file needs to move the approver and he will approve it and then the file needs to go back to the original creator. Any material links or suggestions about the same? -
Seeking advice what to continue learning [closed]
I am a young programmer(<15 years old) who has knowledge of Python, Java and C++. By basic, I mean enough to solve the first fifteen problems of Project Euler.https://projecteuler.net/archives To give an even better understanding, I was able to complete the Google's Code Jam - Qualification Round: Question A in a few hours. https://codingcompetitions.withgoogle.com/codejam/round/000000000019fd27/000000000020993c Most of programming knowledge rests in Python, since it is just so much easier. For a few days now I have been wondering whether to learn JavaScript, HTML and CSS to try and get started with Web Development, or to hook to a Python framework, specifically Django, or to give Data Science or Machine Learning a go and see if i can get the hang of the basics. I have almost no knowledge of algorithms. I one's I do know are bubble sort, and binary search. Which path should I take?? ( I am good at Math and have been trying to teach myself calculus. ) -
Flask is not dedicting a backslash in th URLS
So I have used this to create a route@app.route('/hi) Def hello(): return "Hello World But now if I go to mydomain.com/hi is works good but if I go to mydomain.com/hi/ it throws a 404 error any idea Thanks -
How to Upload my Django Project to bigrock.in Server
How can i upload my Django website on bigrock.in? I'm only getting solutions to deploy Django Project to Heroku but is there a way to deploy the Project to any other Hosting websites ? -
404 Error After Adding Argument To URL Path
Ive got a users profile page and an update_profile page. My projects urls.py: re_path(r'^profile/(?P<username>[\w-]+)/$', include('users.urls')), My users.urls: path('update_profile', views.update_profile, name='update_profile'), Prior to adding the username argument to the url both of these links were working. Since adding the username argument, I can access the profile page but the update_profile page throws a 404 error. My understanding is that if the address bar reads www.site/profile/testuser/update_profile the projects urls.py will strip the www.site/profile/testuser/ and pass just update_profile to the profile apps urls.py, which then should match the path ive given. Why isnt this working? On my profile page I have a check that ensures the username passed in matches the logged in user (so users can only access their own profiles). I will need a similar check on the update_profile page, but currently arent passing username to the update profile page. How could I perform this check without passing it in a second time like /profile/testuser/update_profile/testuser? Thank you. -
On migration in Django, I get error Integrity Error 1364, "Field 'id' doesn't have a default value"
This is something that appeared after a few iterations of saving and restoring the MariaDB database. It doesn't matter how simple the change is, or what I'm changing, it will perform the migration, then throw this error. File "/home/.virtualenvs/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/.virtualenvs/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/home/.virtualenvs/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/home/.virtualenvs/venv/lib/python3.7/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/home/.virtualenvs/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/home/.virtualenvs/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 412, in _query rowcount = self._do_query(q) File "/home/.virtualenvs/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 375, in _do_query db.query(q) File "/home/.virtualenvs/venv/lib/python3.7/site-packages/MySQLdb/connections.py", line 276, in query _mysql.connection.query(self, query) _mysql_exceptions.IntegrityError: (1364, "Field 'id' doesn't have a default value") This is something I can work around just by ignoring it, but it's quite annoying and distracting. How do I fix it? -
get_field is not returning value in advanced-custom-fields-pro
I using advanced-custom-fields-pro in wordpress to allow wordpress user to type page id they wish to display in web, is there any way to get the data from wordpress user and in backend using wp_query and display the page with the data user entered in advanced-custom-fields-pro? Please take note, i named the field as “feature” in plugin. For my case, ‘feature’ can be contain multiple value like 1,2,3,4 so i would like to get my ‘feature’ value in array, what can i do for this? Currently, get_field didnt get value sucessfully. $feature = get_field(‘feature’); $the_query_featured = new WP_Query( array( ‘posts_per_page’ => 2, ‘posts_per_page’ => 2, ‘nopaging’ => false, ‘order’ => ‘DESC’, //’order’ => ‘ASC’, ‘orderby’ => ‘date’, ‘meta-key’ => $feature, ‘page_id’ => $feature, ‘post_type’ => ‘any’ )); <?php while ( $the_query_featured->have_posts() ) : $the_query_featured->the_post(); ?> -
How to add styling in django templates inside for loop using css?
I am making a simple blog project in which I am trying to inject each post's data using for loop template tagging. But in doing so, the grid becomes distorted when css is applied on blog list template. However this css works perfectly fine when tested on manually added posts inside a separate Html page. How to fix this because most of the css that works fine on normal Html pages doesn't work properly when combined with django templates. Here is my Basic Blog Posts template: {% extends 'basic_app/base.html' %} {% block content %} <div class="centerstage"> {% for post in post_list %} <div class="cards"> <div class="card"> <img class="card__image" src="{{ post.blog_pic.url }}" alt=""> <div class="card__content"> <p> <a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a> </p> <p> {{ post.text|safe|linebreaksbr }} </p> </div> <div class="card__info"> <div> <i class="material-icons">{{ post.published_date|date:"D M Y"}}</i>310 </div> <div> <a href="{% url 'post_detail' pk=post.pk %}" class="card__link">Comments: {{ post.approve_comments.count }}</a> </div> </div> </div> </div> {% endfor %} </div> {% endblock %} Html Code that works fine on manually adding posts: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="cards_style.css"> <title>Blog</title> </head> <body> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <div class="cards"> <div class="card"> <img class="card__image" src="https://fakeimg.pl/400x300/009578/fff/" alt=""> <div … -
Django: OperationalError at /admin/User/profile/, no such column: User_profile.user_id
I will cut straight to the chase. Basically, I am recreating the django.contrib.auth.forms UserCreationForm from scratch using the forms.py, views.py, and templates. Everything seemed to be working fine, until I tried to access the database where my Users are listed. That is when this error pops up. I've been delayed by this for a week or so now, and I am genuinely frustrated. I will greatly take utilize any help and support. This is my second time encountering the no such column error, so if anyone could explain what this is being caused by, please inform me. forms.py. from django import forms from django.contrib.auth.models import User class UserRegisterForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'password1', 'password2'] def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords do not match") return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') form.save() messages.success(request, f'Your account has been created! You are now able to ' f'log in') return redirect('login') else: form = UserRegisterForm() … -
Using Django localsettings.py with Elastic Beanstalk
I am using a combination of settings.py (saved in git) and localsettings.py (not saved in git) to configure my app and keep sensitive info out of git. I'm deploying the Elastic Beanstalk for the first time and can't figure out how to upload or create the localsettings.py in the correct place. If I scp it it appears as the ec-user and I can't create the file with the right ownership directly in the deployment directory. The ultimate setup for me would be to have a "master" file that lives just above the /var/app/current directory that I can copy into the correct place whenever I deploy. Any help would be appreciated. -
Django login authentication form
views from django.shortcuts import render, redirect from django.http import HttpResponse from .models import User, Order, Date from django.contrib import messages from django.contrib.auth import authenticate, login, logout from .forms import OrderForm def login_page(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('order-list') else: messages.info(request, 'Username or password is incorrect') context = {} return render(request, "login.html", context) urls from django.urls import path,include from .views import order_list,date_list,create_order,update_order,delete_order,login_page app_name = 'accounts' urlpatterns = [ path('', login_page, name='login-page'), path('orderlist/', order_list, name='order-list'), path('datelist/', date_list, name='date-list'), path('create_order/', create_order, name='create-order'), path('update_order/<str:pk>/', update_order, name='update-order'), path('delete_order/<str:pk>/', delete_order, name='delete-order'), login.html <form method="POST" action=""> {% csrf_token %} <div class="container"> <input type="text" placeholder="Enter Username" name="username" > <input type="password" placeholder="Enter Password" name="password" > <button type="submit">Login</button> </div> {% for message in messages %} <p id="messages">{{message}}</p> {% endfor %} </form> I'm trying to create a login form, where a user can log in if his credentials exist in admin users. But seems like the form is just not working. nfondjfnjodnfndjfnjdnfjdnfjdnjfnjnfjnjsdfjdjbfhbfnfdjnfdkfbkdbfdfndfbnfnjkbfvbnfkgbfkbghfbhgbfbgbfhbghkfbgbfkgbfbg kjnjndfnjfnbjrnjgntrjnt rjrntjrjnyt yjtnynt yjtnynt yjnntnj jfojgiodrng nogdjtgnd gojtih t hojnt -
Autocomplete jquery sending wrong link in
I have a autocomplete in my form and the autocomplete sending in wrong link. here is my URL Path here my template where i implement the autocomplete and the template loaded in browse Now this is my issue, when i type anything ccNumber textbox I expect to send request in /scrapdisposal/ccautocomplete but when i check in my cmd, it send in /scrapdisposal us you can see below screenshot in my browser in my CMD what wrong im done here? -
The most correct way to create REST API with already existed project
There is a one already working project on Django Framework also there is a need to create some paid REST API which will use the same database as that project. So which way will be the most correct? Create new project for API. Create API on already existed project. -
Is it worth learning ASP .NET Core - haven't learned C# / Django vs NodeJS [closed]
I started programming at Feb 2020 with python. I can only use javascript and python. I was looking for a web-framework because recently I felt like studying backend. I was thinking of Django or Node.js since they are like the superstars. But I watched a youtube video about this ASP .NET Core and it looked pretty awesome. So I'm kinda confused if I should just go with my original plan or study C#. And how do you guys think of Django vs Nodejs? Since I'm a newbie it takes me a while to learn any kind of thing. -
i am using pycharm3 to debugging
i am trying to store data in my database via registration form on browser but it is unable to store that and shows below error on terminal Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK.`enter code here` [10/Jun/2020 08:19:00] "GET / HTTP/1.1" 200 1447 [10/Jun/2020 08:19:05] "GET /user_login HTTP/1.1" 200 3346 [10/Jun/2020 08:19:07] "GET /register HTTP/1.1" 200 3258 <ul class="errorlist"><li>username<ul class="errorlist"><li>This field is required.</li></ul></li></ul> [10/Jun/2020 08:19:20] "POST /register HTTP/1.1" 200 3258 -
After successfull payment I am getting anonymous user error
How to solve this error and due to this I can't update the user as paid after payment. Due this I am unable to update purchased orders also. I have tried this issue by removing current_user in views.py after making this change I was unable to update user as paid. I am a beginner so I don't know much about this. please help me to slove this error and update user as paid in my database. views.py @login_required def initiate_payment(request): transaction = Transaction.objects.create(made_by=request.user, amount=1) transaction.save() merchant_key = settings.PAYTM_SECRET_KEY params = ( ('MID', settings.PAYTM_MERCHANT_ID), ('ORDER_ID', str(transaction.order_id)), ('CUST_ID', str(transaction.made_by.email)), ('TXN_AMOUNT', str(transaction.amount)), ('CHANNEL_ID', settings.PAYTM_CHANNEL_ID), ('WEBSITE', settings.PAYTM_WEBSITE), #('EMAIL', request.user.email), # ('MOBILE_N0', '9911223388'), ('INDUSTRY_TYPE_ID', settings.PAYTM_INDUSTRY_TYPE_ID), ('CALLBACK_URL', 'https://www.presimax.online/callback/'), # ('PAYMENT_MODE_ONLY', 'NO'), ) paytm_params = dict(params) checksum = generate_checksum(paytm_params, merchant_key) transaction.checksum = checksum transaction.save() paytm_params['CHECKSUMHASH'] = checksum print('SENT: ', checksum) return render(request, 'redirect.html', context=paytm_params) @csrf_exempt def callback(request): if request.method == 'POST': received_data = dict(request.POST) paytm_params = {} paytm_checksum = received_data['CHECKSUMHASH'][0] for key, value in received_data.items(): if key == 'CHECKSUMHASH': paytm_checksum = value[0] else: paytm_params[key] = str(value[0]) # Verify checksum is_valid_checksum = verify_checksum(paytm_params, settings.PAYTM_SECRET_KEY, str(paytm_checksum)) if is_valid_checksum: received_data['message'] = "Checksum Matched" current_user = request.user.userprofile current_user.paidmem = True current_user.save() else: received_data['message'] = "Checksum Mismatched" return render(request, 'callback.html', context=received_data) return … -
Django and ajax to update database without page refresh
I want a button click to result in my database being updated without a page refresh. I've researched this a lot, and it seems a jquery ajax call is the way to go. But it's not working. I put a check in to see if the click event is working, and the strange thing is that it only works when I click the first button in the table (the table shows all the user's words with a 'for loop'). But then I get a 404 error, so it makes me think that my mistake is in my views? Nothing happens when I click the other words - no error, no click event, nothing. But everything works (i.e. the database gets updated) without using jquery, but then of course the page updates every time. By clicking the button the word should automatically get added to the user's word list without a page refresh. I'm stuck with this, would really appreciate some help, thanks! So I need to find out: 1) how to get the click event working every time; 2) how to get the url right in js; and 3) how to get my view right. My template (without jquery): <a … -
Model matching query does not exist error while adding friend sistem on django
I have a friend system in my django project in which users can add friends and other users can friend them, well everything seemed good until I realize that when seeing other users profile, the code returned a Friend matching query does not exixst error, but the wierd thing is that it inly happens when seeing other users profile, if the user is watching his profile everything seems fine. I think that I should include an if statement on my views.py file(profile view) but I dont know how to do it. views.py def profile(request, username=None): friend = Friend.objects.get(current_user__username=username) friends = [] if friend: friends = friend.users.all() if username: post_owner = get_object_or_404(User, username=username) user_posts = Profile.objects.filter(user_id=post_owner) else: post_owner = request.user user_posts = Profile.objects.filter(user=request.user) args1 = { 'post_owner': post_owner, 'user_posts': user_posts, 'friends': friends, } return render(request, 'profile.html', args1) def change_friends(request, operation, pk): friend = User.objects.get(pk=pk) if operation == 'add': Friend.make_friend(request.user, friend) elif operation == 'remove': Friend.lose_friend(request.user, friend) return redirect('profile', username=friend.username) models.py class Friend(models.Model): users = models.ManyToManyField(User, default='users', blank=True, related_name='users') current_user = models.ForeignKey(User, related_name='owner', on_delete=models.CASCADE, null=True) @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.add(new_friend) @classmethod def lose_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.remove(new_friend) profile.html {% if … -
Relating Two Tables together in Django Template and Count the Numbers of Entry
I have two Models in my application that are related to each other (Item and ItemGallery). In my Template, I want the user to have the option of Edit Gallery or Add Gallery. Once the User has entered the image gallery belong to an item before the Interface should change to Edit Gallery. If not, the Interface should be Add Gallery. In a short world, I should be able to know if an item has or have a gallery image or not. If it has gallery then, edit Gallery if not Add Gallery {% if mylists.itemgallery.all >= 1 %} <a href="{% url 'add_gallery' mylists.id %}"> <i class="fa fa-pencil"></i>Edit Gallery </a> {% else %} <a href="{% url 'add_gallery' mylists.id %}"> <i class="fa fa-pencil"></i>Add Gallery </a> {% endif %} models.py class Item(models.Model): STATUS = ( ('Used', "Used"), ('New', "New"), ('Fairly Used', 'Fairly Used'), ('Tokunbo', 'Tokunbo'), ) ITEM_TYPE = ( ('Demand', "Demand"), ('Offer', "Offer"), ) SALES_TYPE = ( ('By Dealer', "By Dealer"), ('By Owner', "By Owner"), ) CAR_MAKE = ( ('Toyota', "Toyota"), ('Nissan', "Nissan"), ('Audi', 'Audi'), ('Honda', 'Honda'), ('Volkswagen', 'Volkswagen'), ('Mercedes Benz', 'Mercedes Benz'), ('Land Rover', 'Land Rover'), ('BMW', 'BMW'), ) QUALIFICATION = ( ('PhD', "PhD"), ('BSc', "BSc"), ('HND', "HND"), ("O'Level", "O'level"), ) … -
Email codes from a defined list using Django and dealing with concurrency
I have a simple Django Rest server api that gets a post request by another app (a payment processing client). Every post triggers an email with one access code already defined by this model: class AccessCode(models.Model): code = models.CharField(max_length=64, blank=True) sent = models.BooleanField(blank=True, default = False) The general idea is for my view to query this model, get the top AccessCode, mark it as sent and send the email. Obviously I need to deal with concurrency. I'm thinking on a pessimistic approach, querying the database inside an atomic transaction and using select_for_update. class send_code(APIView): def post(self,request): with transaction.atomic(): code = AccessCode.objects.select_for_update().filter(sent=false).first() code.sent=True account.save() // send email with the code return True The thing is, during one active transaction, I don't really understand how the next requests will wait for the query to be release. Will this approach work with parallel post requests without expecting a lot of them to be rejected?