Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python - Django site admin page is empty after logged in
I'm trying to build a tic tac toe game. My django site admin page is appearing blank and i'm not able to solve it. screenshot of the problem models.py from django.db import models from django.db.models import Q from django.contrib.auth.models import User GAME_STATUS_CHOICES ={ ('F','First Player to move'), ('S', 'Second Player to move'), ('W', 'First Player Wins'), ('L', 'Second player Wins'), ('D', 'Draw') } class GameQuerySet(models.QuerySet): def games_for_user(self, user): return self.filter( Q(first_player = user) | Q(second_player = user) ) def active(self): return self.filter( Q(status='F') | Q(status='S') ) class Game(models.Model): first_player = models.ForeignKey(User, related_name = "game_first_player", on_delete=models.CASCADE) second_player = models.ForeignKey(User, related_name = "game_second_player", on_delete=models.CASCADE) start_time = models.DateTimeField(auto_now_add=True) last_active = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1, default='F', choices=GAME_STATUS_CHOICES) objects = GameQuerySet.as_manager() def __str__(self): return "{0} vs {1}".format( self.first_player, self.second_player) class Move(models.Model): x = models.IntegerField() # X and Y co-ordinates y = models.IntegerField() comment = models.CharField(max_length=300, blank= True) by_first_player = models.BooleanField() admin.py from django.contrib import admin from .models import Game, Move admin.site.register(Move) @admin.register(Game) class GameAdmin(admin.ModelAdmin): list_display = ('id','first_player','second_player','status') list_editable = ('status',) I'm a newbie to django. I have been stuck on this problem for a while now. Couldn't find the answers. Thanks. -
Django redirect back to admin login page using reverse() not working
I'm new to Django version 2.1, In Middleware where if user_logged session is empty i'm redirecting it to admin url I'm getting NoReverseMatch at /demo/list Reverse for '../admin/' not found. '../admin/' is not a valid view function or pattern name. error. project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('demo/', include('demo.urls')), ] setting.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'demosite.middleware.LoginRequiredMiddleWare', ] project middleware.py import re from django.shortcuts import redirect from django.conf import settings from django.urls import reverse class LoginRequiredMiddleWare: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): print(request.session.get('user_logged', None)); if not request.session.get('user_logged', None): return redirect(reverse('admin/')) app urls.py from django.urls import path, include from demo import views urlpatterns = [ path('list', views.demoView.listData, name='list-data') ] FOR REFERENCE BELOW IS SCREEN SHOT OF PROJECT DIRECTORY STRUCTURE THANKS IN ADVANCE -
Django: Access certain attribute of multiple subclasses with inheritance from one superclass
My aim is to access an attribute of a subclass without knowing beforehand which of the two subclasses was choosen (multiple choice classes) Ideally there is an attribute in the SuperClass that changes depending upon which SubClass was choosen. The reason is that I have created Forms directly from the SubClasses and use the SuperClass as the entry point for accessing values. I am aware I can use true or false with hasattr(horse), but ideally I am asking if there is a bit neater solution, such as the SubClass can signal to SuperClass which SubClass was used. e.g. for product 8 on my list subclass = getattr(Product(8), 'subclass', 0) print(subclass) >> Horse or place = Product.location Print(place) >> Stable The whole "problem" stem from the fact that I create Products via SubClass Forms, meanwhile much of the later logic goes top-down, starting with Product class Product(models.Model): product_name = models.Charfield(max_length=20) class Car(Product): engine = models.Charfield(max_length=20) location = models.Charfield(default="Garage", max_length=20, editable=False) product = models.OneToOneField(Product, parent_link=True, on_delete=models.CASCADE) class Horse(Product): saddle_model = models.Charfield(max_length=20) location = models.Charfield(default="Stable", max_length=20, editable=False) product = models.OneToOneField(Product, parent_link=True, on_delete=models.CASCADE) -
Trying to hide button if next step does not exist
I am trying to make the button "next" disappear if there is no next step. I have tried the following and got stuck here. I have tasks with related steps using ForeignKey. I think my method is not working because the PK is not always starting at 1. example task one have steps pk 1,2,3. Task two have steps pk 4,5,6. Is it possible to make the PK always be 1,2,3 for each task? Then this might work? Or is there a better solution? views.py def step_detail(request, task_pk, step_pk): step = get_object_or_404(Step, task_id=task_pk, pk=step_pk) next_step_pk = step_pk + 1 next_step = Step.objects.filter(pk=next_step_pk) if next_step.count() == 0: next_step_pk = None return render(request, 'dailytask/step_detail.html', {'step': step, 'next_step_pk': next_step_pk}) models.py: class Task(models.Model): created_at = models.DateTimeField(auto_now_add=True) user_completed = models.BooleanField(default=False) title = models.CharField(max_length=255) description = models.TextField(blank=True, default="") category = models.CharField(max_length=255, choices=CATEGORIES, default="traffic") done_message = models.TextField(null=True, default="") def __str__(self): return self.title class Step(models.Model): title = models.CharField(max_length=255) description = models.TextField(blank=True, default="") user_completed = models.BooleanField(default=False) content = models.TextField(blank=True, default="") order = models.IntegerField(default=0) step_number = models.IntegerField(default=1) task = models.ForeignKey(Task, on_delete=models.CASCADE) class Meta: ordering = ['order', ] def __str__(self): return self.title step_detail.html I want this button to hide when there are no more steps in the task. {% if next_step_pk … -
problems with nomenclature for queried database table
when saved the form, where it is marked that can be blank field as the pago after saved in the table it shows as False, how can I change False by 0 or any other value Models.py class MovRotativo(models.Model): checkin = models.DateTimeField(default=timezone.now()) checkout = models.DateTimeField(null=True, blank=True) email = models.EmailField(blank=False) placa = models.CharField(max_length=8, blank=False) modelo = models.CharField(max_length=15, blank=False) valor_hora = models.DecimalField( max_digits=5, decimal_places=2, null=False, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) chk = models.CharField(("Situação"), max_length=15, choices=SAIDA_CHOICES, default='Não') -
Tablesorter stickyHeaders widget not working
I'm having trouble making my table header to stick using the tablesorter widget. I have the following for my table page: {% load static %} <link rel="stylesheet" href="{% static 'css/theme.default.css' %}" type="text/css" /> <script type="text/javascript" src="{% static 'js/jquery.js' %}"></script> <script type="text/javascript" src="{% static 'js/jquery.tablesorter.js' %}"></script> <table id="myTable" class="tablesorter"> <caption> ... </caption> <thead> <tr> ... </tr> </thead> <tbody> <tr> ... </tr> </tbody> </table> <script> $(document).ready(function(){ $('#myTable').tablesorter({ sortList: [[0,0], [1,0]], widgets: ['zebra', 'filter', 'stickyHeaders'], }); }); </script> I tried labeling my table tag and also creating a div tag around my table, but nothing seems to work. The jQuery version is v1.11.2, and the tablesorter version is v2.31.1. -
How to filter NeoModel Nodes by Relationships in Python
I have the 2 StructuredNodes User and Token as a one to one relationship. Coming from using Django for relational databases, if I want to get the User given a token, I'd simply do User.objects.get(token__key=token). But using Neo4j with NeoModel, I'm struggling to find a way to do this simple query. Also, when I have the User instance, I can do user.token.single() to get the Token instance, but the same doesn't work the other way around. token.user.single() returns CardinalityViolation: Expected: one relationship in a outgoing direction of type FOR_USER on node (49) of class 'Token', got: none. and token.user returns a neomodel.cardinality.One object. class User(DjangoNode): uid = UniqueIdProperty() firstname = StringProperty(index=True, required=True) lastname = StringProperty(index=True, required=True) email = EmailProperty(unique_index=True, required=True) password = StringProperty(requried=True) token = RelationshipFrom('Token', 'OWNS_TOKEN', cardinality=One) def post_create(self): token = Token().save() self.token.connect(token) class Token(DjangoNode): user = RelationshipTo('Token', 'FOR_USER', cardinality=One) key = StringProperty(unique_index=True, default=generate_key) created = DateTimeProperty(default_now=True) -
Is it possible to query database using a variable as the model name?
I have a lot of models in one app. I need to iterate over them based on a corresponding value. So for example: for x in dictionary: q = x.objects.get() Where x is the string variable name of the model and q is the desired query set -
Saving values set in Frontend to Django Database
I have a website which allows Users to pick a few hobbies they enjoy. Currently the website loads these hobbies from a Model and lists them with a Checkbox. What I want to do is when a User saves the form, it should also save these Checkbox values to the database - i.e if they tick Football, the database should save the fact that this User enjoys football. I am new to Django and Python so not too sure how to accomplish this. Here is the code I am using. This is the Models.py file for the Hobbies: TYPES = ( ("Football", "Football"), ("Cricket", "Cricket"), ("Swimming", "Swimming"), ("Cycling", "Cycling") ) class Hobby(models.Model): myfield = models.CharField(max_length=50, choices = TYPES, default=TYPES[0], null=True) football = models.BooleanField(default = False) cricket = models.BooleanField(default = False) swimming = models.BooleanField(default = False) cycling = models.BooleanField(default = False) This is the relevant views.py file: def profile(request, user): # use this for debugging: # import pdb; pdb.set_trace() if 'email' in request.POST: email = request.POST['email'] gender = request.POST['gender'] dob = request.POST['dob'] ## hobby = request.POST['hobby'] if user.profile: user.profile.email = email user.profile.gender = gender user.profile.dob = dob ## user.profile.hobby = hobby user.profile.save() else: profile = Profile(email=email, gender=gender, dob=dob) profile.save() user.profile = … -
From java spring to python django
I have many years of experience writing backend applications using Java (in past years was focused more on JEE but recent years mainly springboot applications). Lately I started cooperating with several friends working on some project and everyone has some passion to python, I also have good memories from python development I did back then during my university days but also small projects I used python throughout my work. However, I mainly used python for short programs and not as a whole service exposing REST APIs. I started playing with Django to build a REST API service, but I find many different concepts I would expect when writing spring application. There are some minor things like having all my models in a models.py file and not having 1 file for module, and what bothers me even more is the lack of a business layer (@Service like in spring) and general separation between the client layer (that accepts the REST requests), service layer and data layer which uses the models. I would expect my client not to have models but rather DTOs. I tried to google how people overcome this messy architecture, but maybe I am missing something and the "hello … -
Import existing db to Django app container
I'm developing a new feature for our mobile app, but I'm working with a recently cloned local instance of our backend. I'm looking for a way to somehow import an existing .sql file to the Django docker container. It's a perfectly fitting db, the only issue is that I couldn't figure out how could I import it into the container/dev shell, currently it's outside the container. -
Django Chart.js ajax javascript "string data parsing error"
I am creating chart web page through Django and Chart.js (in the views.py of Django) class ChartView(TemplateView): template_name = 'graph.html' def get_context_data(self, **kwargs): context = super(ChartView, self).get_context_data(**kwargs) context['labels'] = ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"] context['datas'] = [12, 19, 3, 5, 2, 3] return context in the html file (template file) <script> $( document ).ready(function() { var data = { labels: {{ labels }}, datasets: [ { label: "Site Registrations in the Last 30 Days", fillColor: "rgba(220,220,220,0.2)", strokeColor: "rgba(220,220,220,1)", pointColor: "rgba(220,220,220,1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(220,220,220,1)", data: {{ datas }} } ] }; var ctx = document.getElementById("myChart").getContext("2d"); var myLineChart = new Chart(ctx).Line(data); }); </script> The html page rendering is having error. (The page source looks like this) <script> $( document ).ready(function() { var data = { labels: [u&#39;Red&#39;, u&#39;Blue&#39;, u&#39;Yellow&#39;, u&#39;Green&#39;, u&#39;Purple&#39;, u&#39;Orange&#39;], datasets: [ { label: "Site Registrations in the Last 30 Days", fillColor: "rgba(220,220,220,0.2)", strokeColor: "rgba(220,220,220,1)", pointColor: "rgba(220,220,220,1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(220,220,220,1)", data: [12, 19, 3, 5, 2, 3] } ] }; var ctx = document.getElementById("myChart").getContext("2d"); var myLineChart = new Chart(ctx).Line(data); }); </script> Clearly, you can see that {{ datas }} are getting correct value. However, {{ labels }} are getting wrong values. I do … -
Django crazy URL rewrites
i'm currently facing a issue that i realy don't understand at all, i search trough the hole code and was not able to find any reffereces here, i delted all caches, databases, venv etc. With no effects at all. It's all about the 'login' url pattern urls.py from Project_Accounts import views as Project_Accounts .... url(r'^admin/', admin.site.urls), # Reg and Auth url(r'^login/$', Project_Accounts.login, name='login'), url(r'^signup/$', Project_Accounts.signup, name='signup'), .... urlpatterns += [ path('Project_Accounts/', include('django.contrib.auth.urls')), ] base.html {% if user.is_anonymous %} <a href="{% url 'signup' %}" class="top-menu"> <button type="button" class="btn btn-success">Sign-Up</button> </a> <a href="{% url 'login' %}" class="top-menu"> <button type="button" class="btn btn-primary">Login</button> </a> {% endif %} views.py (Project_Accounts) def login(request): if request.method == 'POST': form = LoginForm(request.POST, request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: request.session.flush() if user.pubpgp: if user.pubpgp_enabled: request.session['userID'] = user.pk return redirect(reverse('login_2fa')) else: hybridlogin(request, user) return redirect(reverse('home')) else: hybridlogin(request, user) # Redirect to a success page. return redirect(reverse('home')) else: return render(request, 'Project_Accounts/login.html', {'form': form}) else: return render(request, 'Project_Accounts/login.html', {'form': LoginForm()}) If my base.html gets displayd signup view works fine, and every other also execpt the login. The URL i get back for login is "127.0.0.1:8000/Project_Accounts/login" but it use to … -
What would be the most efficient way of creating charts/graphs with data from a Django backend
I built an application using Django and I was wondering what would the most efficient way of creating charts and graphs for my data (for personal viewing). I was thinking of having the charts/graphs in a dashboard with the ability to create and delete records in the database(perhaps in a different tab). Originally I was thinking of having this in the Django admin panel since I already use it a lot for looking at/deleting/creating small data. I researched various custom django admin libraries but a lot of them just seems like a UI improvement. Another small feature that I wanted was to regroup various models in different applications into one listing as opposed to the default layout where the main heading is the various django application and under each is the models for the application. I have a couple ideas about how to go about doing this: Create custom django admin template for what I need. This would include graphs/charts but I'm not sure about the regrouping. Maybe create a front-end application to do the graphs and make the groupings myself. This would communicate to the backend via GET/POST/DELETE requests. I would write something in the backend to transform the … -
How to model a one to many relationship in Django
in my current Django project I have list of players and a list of games and I'm looking for a Django field to store the information in which games the player participate. To give an example: User 1 played Game 1, 2, 3, and User 2 played 2, 3... Since not all players of a game are registered, I'm not looking for the relation game to player. So, I'm looking for something like an one-to-may field (player to several games). So far, I found the ForeignKey field. However, when I add this to game, I can only store one player not several player ids. Or do I missed something? How do I express my problem in Django model fields? -
Django: reset a specific field of a model every hour
I have a field in one of my models in django which I want to be reset every hour. (i.e. at each o'clock its value becomes zero) How can I do this task? Can I schedule a function in django? As you know we can define EVENTs and TRIGGERs in mysql and other database backend. Also I am familiar with signals in django but those can not fit in my needs. (because database event is somewhat outside of django and have problems; with signals although it seems this is impossible!) -
Error in function "int() argument must be a string"
I have issues with the following code in my Django project. Anyone one have a clue what's wrong? Exception Type: TypeError at /tasks/2/3/ Exception Value: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' (Django 2.1) def step_detail(request, task_pk, step_pk): user = request.user steps = Step.objects.filter(task_id=task_pk) step = get_object_or_404(Step, task_id=task_pk, pk=step_pk) next = "" if int(Step.step_number) < len(steps): next = "/%s/%s/" % (task_pk, int(step_pk) + 1) user.userprofile.current_step.update(step_pk) else: next = "/task_done/" user.userprofile.current_step.update(step_pk) user.userprofile.daily_task_done_time(datetime.datetime.now()) if request.POST: if "nextstep" in request.POST: return redirect(request.POST.get('next')) return render(request, 'dailytask/step_detail.html', {'step': step}) Environment: Request Method: GET Request URL: http://127.0.0.1:8000/tasks/2/3/ Django Version: 2.1.1 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dailytask', 'account'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Users/iamsuccessful/eb-virt/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Users/iamsuccessful/eb-virt/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/Users/iamsuccessful/eb-virt/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/iamsuccessful/eb-virt/lib/python3.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/Users/iamsuccessful/ebdjango/dailytask/views.py" in step_detail 60. if int(Step.step_number) < int(len(steps)): Exception Type: TypeError at /tasks/2/3/ Exception Value: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' -
Running Django on server with remote interpreter - Prevent Django from creating a test database
I'm trying to use PyCharm's remote interpreter capability to debug my Django app on our dev server. The connection is working, but when I try to run or debug using the remote interpreter I get this error from the run console: Creating test database for alias 'default'... Failed (ORA-01031: insufficient privileges) Got an error creating the test database: ORA-01031: insufficient privileges As far as I can tell, Django is trying to create a test database to use with my test cases. I don't have any test cases on our server yet and don't need them right now. I'm also using my personal schema of which I am the owner. How can I prevent Django from trying to create this database so that I can run my code? -
Django: Could someone help me convert a function based view into a class based view?
I'm having a lot of difficulty in converting the following function based view into a class based version. I need to display clickable boxes on a webpage that show the 'projects' that are in the database. The function based view that I have works perfectly but I cannot now translate it to a CBV. I'm hoping someone might be able to have a look at it and help structure my approach. I've been stuck for a long time on this. def assets_by_project(request): project_data = project.objects.all() query = request.GET.get('q') if query: results = box.objects.filter(Q(project_assigned_to__icontains=query)) else: results = "NA" return render(request, 'main_app/assets_by_project.html', { "project_data":project_data }) -
Django multilingual site
I am trying to create a multilingual website, which would get content from DB based on selected language. I can get the selected language easily using get_language() in the view. Right now, my models look like this (simplified): class Article(models.Model): author = models.CharField("Author", max_length=255) class ArticleText(models.Model): id = models.OneToOneField(Article, on_delete=models.CASCADE, primary_key=True) en = models.TextField("English") fr = models.TextField("French") My idea (based on research here on SO) was that I would store the article's text content elsewhere, linking it's primary key to the actual Article object's primary key. The Article model contains just general info (publish date, author, etc.), which is the same for all languages. However, I am not really sure how to access the data from my template. Right now I use: context["articles"] = models.Content.objects.select_related("id") I can then access the various fields in my template using {% for article in articles %} <h3>{{ article.author }} - {{ article.fr }}</h3> {% endfor %} However, I want the language ({{ article.$LANGUAGE }}) to change based on the selected language. Something like {{ article.$get_current_language }} --> {{ article.fr }} I guess I could do the following in the template: {% if get_current_language == en %} {{ article.en }} {% elif get_current_language == fr … -
Calling a foreign key relationship in an "if" statement in Django template
I have two models, Booking and Confirmation that are related via a ForeignKey relationship through "booking." I want to only display bookings in my detail view that have an attribute value of is_confirmed ==True. I don't really want a queryset, I just want to display the booking information from the "Booking" model if the confirmation is True in the template. models.py: class Booking(models.Model): user = models.ForeignKey(CustomUser, null=True, default='', on_delete=models.CASCADE) expert = models.ForeignKey(CustomUser, null=True, default='',on_delete=models.CASCADE, related_name='bookings') title = models.CharField(max_length=200, default='Video call with ..', null=True) start_time = models.DateTimeField('Start time', null=True) end_time = models.DateTimeField('End time', null=True) notes = models.TextField('Notes', blank=True, null=True) class Meta: verbose_name = 'Booking' verbose_name_plural = 'Bookings' def get_absolute_url(self): return reverse('booking:booking_detail', kwargs={"pk": self.pk}) class Confirmation(models.Model): booking = models.ForeignKey(Booking, on_delete=models.CASCADE) expert_confirming = models.ForeignKey(CustomUser, on_delete=models.CASCADE) is_confirmed = models.BooleanField(default=False) def get_absolute_url(self): return reverse('booking:booking_detail', kwargs={"pk": self.booking_id}) views.py: class BookingDetailView(DetailView): model = Booking template = 'templates/booking_detail.html' booking_detail.html: <div class="container" id="booking_content"> <p>{{ booking.title }}</p> <p>{{ booking.start_time }}</p> <p>Booking request by: {{ booking.user }}</p> <p>Expert requested: {{ booking.expert }}</p></div> I'm not sure how the if statement in the template should reference these related models to display what I want. -
Django: Modify Class Based View Context (with **kwargs)
I've a Function definition that works perfect, but I need to update to a Class Based View. function def: def ProdCatDetail(request, c_slug, product_slug): try: product = Product.objects.get(category__slug=c_slug, slug = product_slug) except Exception as e: raise e return render(request, 'shop/product.html', {'product':product}) So far, I've read that to modify the context of a Class Based View (CBV) I need to overwrite the def get_context_data(self, **kwargs) in the CBV. So, I've done this: Class Based View: class ProdCatDetailView(FormView): form_class = ProdCatDetailForm template_name = 'shop/product.html' success_url = 'shop/subir-arte' def get_initials(self): # pre-populate form if someone goes back and forth between forms initial = super(StepOneView, self).get_initial() initial['tamanios'] = self.request.session.get('tamanios', None) initial['cantidades'] = self.request.session.get('cantidades', None) return initial # pre-populate form if someone goes back and forth between forms def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['product'] = Product.objects.get(category__slug=c_slug, slug = product_slug) return context def form_valid(self, form): # In form_valid method we can access the form data in dict format # and will store it in django session self.request.session['tamanios'] = form.cleaned_data.get('tamanios') self.request.session['cantidades'] = form.cleaned_data.get('cantidades') return HttpResponseRedirect(self.get_success_url()) How should I pass the arguments c_slug, product_slug to the get_context_data definition for this CBV to work as the Function definition? -
Django DB editing
import json from django.http import Http404, HttpResponse from main.models import Personnages def store_data(request): if request.is_ajax() and request.POST: value = request.POST.get("value") toChange = request.POST.get("name") id = request.POST.get("id") #A IMPORTER perso = Personnages.objects.get(id=id) perso.toChange = value perso.save() return HttpResponse(value+toChange) else : raise Http404 I have written this code (sorry for the french words) but the problem is that I don't find solution for the part perso.toChange = value Who actually doesn't work because I try to put the string extract from ajax instead of the field. But I haven't find a solution :x Thanks ! (Sorry for my poor english, I really try to improve it ^^) -
Is it possible to sort ManyToManyField in Django in an added order?
I'm using Django grappelli admin and its "Related lookup fields" like the image below. Fist, I store it in the below order. After submitting it, the order changes like the below. I need to keep the order that I pick one by one, however every time submitting it, the system changes the order. I tried to use ordering attribute in Meta class, but it doens't work. How can I keep the order that I pick one by one in Django admin's ManyToManyField? index.html {% for store in article.similarstores.all %} {{ store.businessName }} {% endfor %} models.py class Store(models.Model): class Meta: ordering = ['-created_by'] businessName = CharField(unique=True, max_length=40) ... def __str__(self): return str(self.id) + ". " + self.businessName ... class Article(models.Model): ... similarstores = ManyToManyField(Store, blank=True) ... -
Modify value in data table UserProfile using function
I am trying to run .save() to change the value of a user model field. Here is my code: Views.py: def traffic_task(request): tasks_traffic = Task.objects.filter(category="traffic") random_task = random.choice(tasks_traffic) task_id = random_task.pk user = request.user user.userprofile.daily_task = task_id user.save() return task_detail(request=request, pk=task_id) Models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) daily_task = models.IntegerField(default=0) daily_task_done = models.BooleanField(default=False) daily_task_done_time = models.DateTimeField(default=datetime.now() - timedelta(days=2)) They are in two different apps so maybe it's an import missing?