Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get data from model in view
I have two tables Category and book My Category table with the book table has one-to- many links,that's mean one category can have several books Now I want to display 6 books from each category on my homepage How should I get the information? -
How would I display "New account is created" message after new user have registered
My concern is I want after a user is registered a message should display indicating that a user is registered, I have already added a script but when I click a sign up button a message pop up even I have not registered a user. I am not sure where and how should I place my scripts but I guess if function is required. Help!! views.py def register(request): if request.method == "POST": user_form = UserCreationForm(request.POST) if user_form.is_valid(): user = user_form.save() username = user_form.cleaned_data.get('username') messages.success(request, f"New account created:{username}") login(request, user) return redirect("loststuffapp:IndexView") else: for msg in user_form.error_messages: messages.error(request, f"{msg}:{form.error_messages[msg]}") return render(request = request, template_name = "loststuffapp/register.html", context={"user_form":user_form}) user_form = UserCreationForm return render(request = request, template_name = "loststuffapp/register.html", context={"user_form":user_form}) register.html {% extends "loststuffapp/base.html" %} {% block content %} <form method="POST"> {% csrf_token %} {{user_form.as_p}} <p><button class="btn" type="submit">Register</button></p> <script>M.toast({html: "New account is created", classes: 'blue rounded', displayLength:2000});</script> </form> <p>If you already have an account, <a href="/Register">login</a> instead</p> {% endblock %} -
How to create a dynamic dropdownlist from a model field that is declared as CharField not a Foriegn key in django
I want to create a dynamic dropdownList from model(for eg: list of Author details, that is neither a forign key nor manytomany field) -
Ckeditor in django not working in production
Django-ckeditor works fine on local server but does not works in production. Not Found: /static/ckeditor/ckeditor-init.js -
"The view didn't return an HttpResponse object. It returned None instead."
"The view didn't return an HttpResponse object. It returned None instead." "i am working on exam-app using python django ,but getting error in loginview function while running on localhost,how do i solve this?" in views.py this the following loginview class where it's showingerror class LoginView(FormView): form_class = AuthenticationForm template_name = 'exam/login.html' def form_valid(self, form): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username = username, password = password) if user is not None and user.is_active: login(self.request, user) if user.role == 2: return redirect("student") elif user.role == 3: return redirect("index") else: return self.form_invalid(form)` error showing is: ValueError at /login/ The view exam.views.LoginView didn't return an HttpResponse object. It returned None instead. -
CSRF token missing or incorrect while csrf_token added in form
I have just started on a project involving Django and unfortunately got the error CSRF token missing or incorrect. This is my file in the views directory. from django.shortcuts import render_to_response from django.template import RequestContext @require_http_methods(("POST",)) def feedback_from_user(request): """Submit an email and slack message to support based on in-app feedback. POST Args: message (str) """ print('POST executed!') context = RequestContext(request) feedback = SpotFeedback.objects.create( message=request.data["message"].strip(), token=TOKEN ) feedback.process() feedback.save() return render_to_response('client/success.html', RequestContext(request)) Following is my form in my template: <form method="post"> {% csrf_token %} <div class="form-group purple-border shadow-textarea"> <label for="feedbackTextarea">Rückmeldung</label> <textarea class="form-control z-depth-1" id="feedbackTextarea" rows="4" placeholder="Ihre Rückmeldung!"></textarea> </div> <input class="btn btn-primary btn-success" type="submit" value="Submit"> </form> I already have tried the suggestions on multiple posts on stackoverflow but could not achieve success. Can someone help me fixing this? -
How to attach a python file to each row(i.e. each data entry) in database formed using Django?
Ive used default django superuser to create an admin and created a DB using it. But now in that i want to add a python script to each data entry i.e. row. How do i do this??? Nothing special. Used basic Django. -
Django | how to select_for_update() to edit and save changes only, force lock timeout?
There's hourly production plan data people might have to edit every hour 24/7. If someone edits a plan, no one should be able to edit the plan. When plan edit is complete, system should save corrections only. If someone has forgoten browser window in edit mode and his shift is over, other people should see who locked the table and be able to override database lock. There's a model class PlanData(models.Model): plan_type = models.ForeignKey(PlanType, on_delete = models.CASCADE) plan_ident = models.ForeignKey(ObjectConfig, on_delete = models.CASCADE) active_from = models.DateTimeField() hour = models.IntegerField() val = models.FloatField(blank = True, null = True) Where plan_type = 1 is current plan and plan type = 2 is corrected values I plan to lock it for edit by .select_for_update(nowait=True,of='self') I was going to set .plan_type = 2 and .pk = None for entire QuerySet when processing form data before doing save() changes. Using 'with transaction.atomic', of course. What happens if someone enters 'edit' mode, locks PC and goes home? How do I let people override locks? -
Django Admin super slow selecting single record
I have Pick model which when I select a record within Django Admin takes an age (about 20 seconds) to retrieve the record (there are about 70k). However, it is quick when I try and create/save a record. I have added the indexes to try and speed up retrieval but don't really know what I should be doing class Pick (models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, db_index=True) contest_entry=models.ForeignKey(ContestEntry, on_delete=models.CASCADE, db_index=True) game_round=models.ForeignKey(GameRound, on_delete=models.CASCADE, db_index=True) objects = DataFrameManager() def __str__(self): return f'%s %s' % (self.contest_entry, self.game_round) class Meta: unique_together = ['user', 'contest_entry', 'game_round'] ordering = ['contest_entry','game_round','user','team'] index_together = [["user", "contest_entry", 'game_round'],] indexes = [ models.Index(fields=['user', 'contest_entry', 'game_round']), models.Index(fields=['game_round'], name='game_round_idx'), models.Index(fields=['contest_entry'], name='contest_entry_idx'), ] class PickAdmin(admin.ModelAdmin): list_filter= ( ('user', RelatedDropdownFilter), ('contest_entry__contest', RelatedDropdownFilter), ('game_round', RelatedDropdownFilter) ) admin.site.register(Pick, PickAdmin) How can I improve performance here? -
How to post array data in DRF
When I post to array json like {"productId":[1, 2, 3]}. I got errors Cannot assign "[<Product: Short Sleeve>, <Product: Short Sleeve>, <Product: Short Sleeve>]": "FittingCartItem.productId" must be a "Product" instance. I already try add many=True argument in get_serializer function. I don't know how solve this problem... serializers.py class ItemListSerializer(serializers.ModelSerializer): product = ProductSerializer(source='productId', read_only=True) memberId = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), write_only=True, required=False) productId = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all(), write_only=True, many=True) is_live = serializers.BooleanField(default=True) class Meta: model = FittingCartItem fields = '__all__' views.py class ItemListView(generics.ListCreateAPIView): serializer_class = ItemListSerializer queryest= FittingCartItem.objects.all() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): serializer.save() headers = self.get_success_headers(serializer.data, many=True) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Accessing two apps in one view in Django
I have a Django project with two apps. The first one, market/models.py, includes a Market class and a Share class, where the latter keeps track of all shares bought or sold on any given market, as follows: class Market(models.Model): title = models.CharField(max_length=50, default="") current_price = models.DecimalField(max_digits=5, decimal_places=2) description = models.TextField(default="") shares_yes = models.IntegerField(default=0) shares_no = models.IntegerField(default=0) b = models.IntegerField(default=100) cost_function = models.IntegerField(default=0) open = models.BooleanField(default=True) def __str__(self): return self.title[:50] def get_absolute_url(self): return reverse('market_detail', args=[str(self.id)]) class Share(models.Model): user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, related_name='user_shares', default=None) market = models.ForeignKey( Market, on_delete=models.CASCADE, related_name='market_shares', default=None) share = models.IntegerField(default=0) def __str__(self): return str(self.share) def get_absolute_url(self): return reverse('market_list') The second app, user/models.py, is to create custom users, as follows: class CustomUser(AbstractUser): points = models.IntegerField(default=1000) What I want to do is this: on clicking a button on a template for a specific market, the code will loop through all users with shares in that market to add/subtract the value of each share in their possession from their total points (subtraction would happen when users own negative shares, meaning they owe shares on account of short-selling). The value of each share at that point is simply the current market price. Here is what I have at the moment, in markets/views.py … -
Creating a table which consist of all the deleted content from my crud table
So I finished my crud operations and it works. Now I just need to create a table where all my table contents which have been deleted go to a separate table(maybe in a seperate URL). I tried using boolean in my destroy function where all the deleted items are True and the rest are False and created a separate URL for all the deleted content. But it keeps on saying the Employee is not defined from django.shortcuts import render, redirect from employee.forms import EmployeeForm from employee.models import Employee # Create your views here. def emp(request): if request.method == "POST": form = EmployeeForm(request.POST) if form.is_valid(): try: form.save() return redirect('/show') except: pass else: form = EmployeeForm() return render(request,'index.html',{'form':form}) def show(request): employees = Employee.objects.filter(False) return render(request,"show.html",{'employees':employees}) def destroy(request,id): employee = Employee.objects.get(id=id) employee.deleted=True employee.save() return redirect("/show") def deleted_list(request): employees=Employee.object.filter(True) -
Context Highlighting in Django Form
I have created a Django app that connects to an API and returns JSON response back to the Django app. The JSON response is returned on a Django template. The template where the JSON response surfaces has two boxes- the first box displays the few of the important attributes from the JSON response like UUID, emp_ID, etc while the second box displays the complete raw JSON returned. I would like to add a functionality that can help me select, let say UUID in the first box. As soon as I select it, the JSON contained in the second box gets highlighted automatically to show the selected UUID and the entire content of that particular UUID. The raw response may run into 10000 lines so I want to find a neat way to display the selected content for users. Note: The JSON is not being stored in DB and the content is lost as soon as I refresh the page. How do I achieve this? I tried checking out Haystack, Solr, etc but they seem to be DB based. I need something lightweight to achieve this. -
What is the purporse of using Authtokenserializer in Rest framework
I am creating a login API in Django rest framework but i donot understand why we are using Authtokenserializer as a serializer class. class loginViewSet(viewsets.ViewSet): serializer_class=Authtokenserializer -
model overwrites another model
I have made a table "Offenses" in my database which works fine, it has a primary key named "id" Now i want to create another table with name offense_category. and want to create a foreign key that points to "id" in table "offenses" however when i made migrations my "Offenses" table is being overwritten by offense_category table... All the fields in offense are now gone. it shows the fields of offense_category under same name "Offenses" and no offense_category table is reflected in the database. I am using mySQL with xampp server models.py from django.db import models from django.contrib.auth.models import UserManager from django.core.validators import int_list_validator # Create your models here. class Offenses(models.Model): id = models.IntegerField(primary_key=True) description = models.CharField(null=False, max_length=200) assigned_to = models.CharField(null=True, max_length=100) categories = models.TextField(null=True) category_count = models.IntegerField(null=True) policy_category_count = models.IntegerField(null=True) security_category_count = models.IntegerField(null=True) close_time = models.TimeField(null=True) closing_user = models.IntegerField(null=True) closing_reason_id = models.IntegerField(null=True) credibility = models.IntegerField(null=True) relevance = models.IntegerField(null=True) severity = models.IntegerField(null=True) magnitude = models.IntegerField(null=True) destination_networks = models.TextField(null=True) source_network = models.CharField(null=True, max_length=100) device_count = models.IntegerField(null=True) event_count = models.IntegerField(null=True) flow_count = models.IntegerField(null=True) inactive = models.BooleanField(null=True) last_updated_time = models.DateTimeField(null=True) local_destination_count = models.IntegerField(null=True) offense_source = models.IntegerField(null=True) offense_type = models.IntegerField(null=True) protected = models.BooleanField(null=True) follow_up = models.BooleanField(null=True) remote_destination_count = models.IntegerField(null=True) source_count = models.IntegerField(null=True) start_time = … -
Rest API calls for Django Crm?
Am doing a Crm project so am planning to use open source django crm .so i need a link of django crm with restapi calls.when am searching for django crm project all getting generic view code -
how to return and display on template the username and group in django
i have a login system using django i want to be able to display the logged in user and the group that belong to it in the base template that include the navigation bar. until now i am able to return the username and the group and printed out in the console. and its showing the username in the template but without the group views.py def login_request(request): if request.method == "POST": username = request.POST['lognName'] password = request.POST['lognCode'] user = authenticate(username = username,password = password) if user.is_authenticated: print("user is authenticated", {username}) else: print("user is NOT authenticated", {username}) currentU = User.objects.filter(username=username).first() currentID = currentU.id print('current user is : ',currentID) groupName=User.objects.all().get(pk=currentID).groups.get().name print('set done ') print('the Groups Name {0}'.format(groupName)) if user is not None: login(request,user) messages.info(request,f"You are now logged in as {username}") return redirect("create") else: messages.error(request,"invalid username or password") print("invalid username or password") return render(request,'login.html') base.html <!DOCTYPE html> {% load static %} <html> <head> <script type="text/javascript" src="{% static '/js/jquery-3.1.1.min.js' %}"></script> <link rel= "icon" type= "image/png" href="{% static 'img/logo_title/icon-AddressBar.png'%}"> <link rel="stylesheet" type="text/css" href="{% static '/css/search.css'%}"> <link rel="stylesheet" type="text/css" href="{% static '/css/style.css'%}"> </head> <body> <!-- <div class="Horizontal-scale"> --> <label for="toggle">&#9776;</label> <input type="checkbox" id="toggle"/> <div id="container" class="Horizontal-menu"> <ul> <li><a href="#">{{ user }} || {{ groupName }}</a></li> <li><a … -
Store a reference to the user that makes a modification of data through Django-admin
I want to store a reference to the user that makes a modification of the information through Django Admin. Basically, i want to know who did a change: For example: class Calibrations(models.Model): code = models.CharField(max_length=30) #Some reference to the user that made the change has to be stored responsable_user = models.PositiveIntegerField() #An id? def save(self, *args, **kwargs): self.responsable_user = get_current_loggedin_user().id super().save() Is there a way to store this user reference on a model? Or maybe i better way of solving this? -
Django. How to put posts in a for loop where each post has a like button and show a dislike button if the user already liked the post?
I am trying to print out blog posts in a for loop and allow users to like the post. How do I show a dislike button if the user already liked the post? When I try put the like section template into the for loop every button is set to "Like" even if the user already liked the post. ''' views.py def view_post(request, id=None): post = get_object_or_404(Post, id=id) user = User.objects.get(id=post.author.id) userProfile = UserProfile.objects.get(pk=user.pk) is_liked = False if post.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'post': post, 'userProfile': userProfile, 'is_liked': is_liked, } return render(request, "post/post.html", context) def like_post(request, id=None): post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True context = { 'post': post, 'is_liked': is_liked, } if request.is_ajax(): html = render_to_string('like_section.html', context, request=request) return JsonResponse({'form': html}) ''' ''' like template {% if request.user.is_authenticated %} <form action="" method="POST"> {% csrf_token %} {% if is_liked %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-danger">Dislike</button> {% else %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-primary">Like</button> {% endif %} </form> {% endif %} ''' ''' <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click', '#like', function(event){ console.log("i'm clicked"); event.preventDefault(); var pk = $(this).attr('value'); var url = "/post/like/"; … -
Get value from template to views
I have a Weather API function that exists in weather/views.py And I have there a variable for a town of weather. (From which town I want to get weather values) I pass this value to function to get a weather information. After that I use return JsonResponse(base) to get the weather info to a static page, from where I'm taking it to a template with this javascript code $(document).ready(function(){ $.getJSON("http://192.168.71.152:8000/weather/", function(result){ $.each(result, function(i, field){ $("#weather").append(i+ " : " + field + "<br>"); }); }); }); It all works fine but I also have a users from another town. This users have a city column in profile and DB. It looks like this user.Profile.city. And I would like to access that city for the current user in my template and pass it to that variable town in views.py. So there will be a Weather with current location for the current user. Is it possible??? Im getting a weather info this way def weathere(*args, **kwargs): #read json data url = api.format(city = city_name, key = API_KEY) response = requests.get(url) data = response.json() jsonText = json.dumps(data, indent=4) python_obj = json.loads(jsonText) And returning as JSON to urls.py urlpatterns = [ path('', views.weathere, name='weather'), ] -
How can I retrieve user IP Address, City, Country upon sign up with Django?
I am wondering how I can get a user's location upon sign up using django. May I have an example in code doing this in a form? GeoIP likely does what I need but I am confused as to how to implement it. -
Set Django X-CSRFToken Using Axios in Django
I am using Django + ReactJS for my latest web apps. I have csrf enabled for my django backend. In this case, I need to set headers["X-CSRFToken"] = csrfToken for my POST requests. The current way I am using is Using {% csrf_token %} tag in django template which will generate a hidden input with value=csrfToken and before every axios calls add: let csrf = document.querySelector("[name=csrfmiddlewaretoken]").value; axios.interceptors.request.use(function (config) { config.headers["X-CSRFToken"] = csrf; return config; }, function (error) { return Promise.reject(error); }); However, I want to set the csrf header to global axios settings, so I can avoid setting it every time I want to call. Can I know how can I do it? If I set it in the base index.js of react, it will return me Uncaught TypeError: Cannot read property 'value' of null Because the csrf input element is not rendered yet. I also tried to put it into the React Component's componentDidMount method, still, the same error. -
Pycharm does not warn about unresolved references
I'm using Pycharm Community to develop a project using the Django Framework. I have recently created a new project and it's working perfectly. The only problem is that Pycharm doesn't complain about unresolved references on python code. In my other django projects, when i call a funtion that has not been imported like "get_user_model()" django underlines the function call with a red line and it asks if i want to import that function. But in this project, it doesn't even complain about that. I only see the error once i hit run. There is no real-time checking, no graphical debbuger. Some configuration is missing. Could you give me some tips? -
How to get push-notification in django when database has been updated with a new entry?
I want to generate a push-notification whenever the database entry is updated if the current ID is 2 and a new tuple is added the id would be 3. so how can i be notified if that new id has been added to the database? The data entry is done on the back-end by some python script no data has been added to the MySQL database by the user. So every time a new tuple is added to the database I want my application to give me notification. I am posting everything that might be relevant for your ease. please hep me with the code. models.py creates table Offenses in the database models.py class Offenses(models.Model): oid = models.IntegerField(primary_key=True) description = models.CharField(null=False, max_length=200) objects = UserManager() class Meta: db_table = "offenses" from views.py i am adding entries to the database that has been retrieved from an API and stored in the database.here is the snippet of my views.py response_body = json.loads(response.read().decode('utf-8')) for j in response_body: obj, created = Offenses.objects.get_or_create(oid=j['id'], defaults={'description': j['description'], 'assigned_to': j['assigned_to']}) return render(request, 'table.html') -
How to access class attribute from within Meta class
I'm adding field-level permissions to my model. I want to keep them separate from the other object-level permissions so my code can check to see if a permission has been defined for any given field, but then I still want to combine them so the field-level permissions get created in the auth_permission table. I first tried creating field_permissions inside the Meta class, but got the "class Meta got invalid attribute(s)" error. I then moved field_permissions out of the Meta class, as a model class attribute, and tried to append it to "permissions" (defined in the Meta class), but I get an "unresolved reference" on field_permissions inside the Meta class. I also tried self.field_permissions, but that doesn't work either. Here's my model: class Client(AddressPhoneModelMixin, DateFieldsModelMixin, models.Model): name = models.CharField( verbose_name=_('Client'), max_length=100, ) status = models.CharField( verbose_name=_('Status'), max_length=25, ) field_permissions = ( ('view_client_id', 'Can view client ID'), ('view_client_name', 'Can view client name'), ('view_client_address', 'Can view client address'), ('view_client_country', 'Can view client country'), ('view_client_status', 'Can view client status'), ('view_client_phone_number', 'Can view client phone number'), ('view_client_mobile_number', 'Can view client mobile number'), ('view_client_fax_number', 'Can view client fax number'), ('view_client_created', 'Can view client created'), ('view_client_updated', 'Can view client updated'), ('view_client_deleted', 'Can view client deleted'), ('change_client_id', 'Can …