Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CreateWithInlineView - get id from the inline before
I use "django-extra-views" to make it possible to use multiple models in one CreateView. So I want to set all things about an article like article number (first step), then all informations about the article like text, images, documents and more with one post/submit. All informations about the article are in different models with a relationship to the model "article_number". example: models.py class article_number(models.Model): article_no = models.CharField( _('article_no') ,blank=False, null=False, max_length=30) description = models.TextField( _('description') ,blank=True ,null=True, default='') class article_document(models.Model): article_no = models.ForeignKey(article_number, on_delete=models.CASCADE, related_name = 'ad_article_number', verbose_name='article no') file_type = models.ForeignKey(file_type, on_delete=models.CASCADE, related_name = 'ad_file_type', verbose_name='file type') file_name = models.CharField(_('file Name'),max_length=100, blank=False) file = models.FileField(_('file'),upload_to="product/document/", blank=True, null=True) file_created = models.DateTimeField(_('file created'),auto_now_add=True) language_code = models.ManyToManyField(language_code, blank=True) example: views.py class article_documentInline(InlineFormSetFactory): model = article_document fields = ['file_type', 'file_name', 'file', 'language_code'] class ArticleNumberCreateView(SuccessMessageMixin, CreateWithInlinesView): model = article_number inlines = [article_documentInline, ...] fields = ['article_no', 'description'] template_name = 'to_template.html' success_message = _('Article successfully created') -
Django- Clear user cache when user logged out
I am using django.core.cache to store user roles related data in the cache. The user roles are stored as keys roles_<user.id> in the cache. I want to delete the roles_<user.id> key from the cache whenever theuser logs out from the system. I used the user_logged_out auth signal for this but somehow this signal is not working(not deleting the cache data). I have created a receiver in signals.py as: def clear_user_cache(sender, user, request, **kwargs): cache.delete('roles_{}'.format(user.id)) user_logged_out.connect(clear_user_cache) My logout url is: url(r'^accounts/logout/', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='auth_logout'), Logout in template: <a class="dropdown-item" href="{% url 'auth_logout' %}"><i class="la la-sign-out"></i>{% trans 'Logout' %}</a> When I hit the logout button, the user is logged out but the cache is not being cleared. If I try printing some statements in the signal receiver, they are not getting printed. I though the url in the template might have caused this problem so I tried changing it to: <a class="dropdown-item" href="/logout"><i class="la la-sign-out"></i>{% trans 'Logout' %}</a> But still nothing happened. How can I make the logout signal to fire when the user is logged out? I am using Django==1.8.18 and python2.7 -
Here is a link . How is the random string f6909.... Generated?
I got an email for verification . http://xyz.pythonanywhere.com/record/upload/f690928d034d27ebb943b3f9bc9e3ae9/12. How is the string f6909..... Generated and is there a way to find out the pattern ? Is there any function which is generating the random string for different email addresses ? -
Django admin panel list_display show none even after fetching data
I am displaying data in django admin panel for many to many relationship table. I got None instead of list of names. I am using python: 3.6 and django: 2.2 List_display for ManytoMany fields in Admin panel I had also already asked question related with this and change my model too as no one answer over there. models: class Assessment(models.Model): name = models.CharField(max_length=255) class Participant(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) first_name = models.CharField(max_length=255,blank=True,null=True) class Seminar(models.Model): topic = models.CharField(max_length=255) assessment = models.ManyToManyField(Assessment,blank=True) participant = models.ManyToManyField(Participant,blank=True,through='SeminarParticipant',through_fields=('seminar','participant')) class SeminarParticipant(models.Model): seminar = models.ForeignKey(Seminar,blank=True,on_delete=models.CASCADE) participant = models.ForeignKey(Participant,blank=True,on_delete=models.CASCADE) request_time = models.PositiveIntegerField(default=0,validators=[MinValueValidator(0),]) is_survey_completed = models.BooleanField(default=False) admin: @admin.register(Seminar) class SeminarAdmin(admin.ModelAdmin): list_display = ('topic''assessment') def assessment(self,obj): return "\n".join([item for item in obj.assessment.all()]) I was expecting name of assessment in list_display of seminar admin but got assessments.Assessment.None in list_display of admin panel. NEED HELP!!! Already had asked. No one answer. I changed my model and again it is messed up. Please advice me If I am making my models incorrect. This is my first project in django. -
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.