Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch error with password reset emails
I have been trying to create a system for password reset emails. I have been following this tutorial: https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html I am getting this error when I try to visit /password/reset/ : django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. Here are the relevant url patterns in urls.py: urlpatterns = [ url(r'^$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), url(r'^password/reset/$', auth_views.password_reset, name='reset_password'), url(r'^password/reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^password/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.password_reset_confirm, name='password_reset_confirm'), url(r'^password/reset/complete/$', auth_views.password_reset_complete, name='password_reset_complete'),] How do I make this page render correctly? -
Django url variable catching
I'm having trouble at having Django urlpatterns catch a variable as an variable and instead take it as a set URL. urlpatterns: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^about/', views.about), url(r'^views/available_products/', views.available_products), url(r'^views/productview/<int:product_id>/', views.productview) ] When I host the server and go to /about/, /views/available_products/ or /admin/ they work fine, but trying to go to /views/productview/1/ gives a 404 error whereas going to /views/productview// gives a missing argument -error. I tried to read the documentation and saw no obvious tell as to why my url variable argument wouldn't work, but clearly I'm doing something fundamentally wrong. Here is an example error message from the debug page: Page not found (404) Request Method: GET Request URL: http://localhost:8000/views/productview/12/ Using the URLconf defined in firstdjango.urls, Django tried these URL patterns, in this order: ^admin/ ^about/ ^views/available_products/ ^views/productview/<int:product_id>/ The current path, views/productview/12/, didn't match any of these. And here is the same error message but where the URL I try with is the same as in urlpatterns: TypeError at /views/productview/<int:product_id>/ productview() missing 1 required positional argument: 'product_id' Request Method: GET Request URL: http://localhost:8000/views/productview/%3Cint:product_id%3E/ Django Version: 1.11.8 Exception Type: TypeError Exception Value: productview() missing 1 required positional argument: 'product_id' Server time: Sat, 10 Feb 2018 12:25:21 … -
How to handle inefficiency of Django's Queryset?
I've seen other questions, but unfortunately i couldn't find similar problems yet. The size of information is approximately equal to 1 GB, but the amount of objects that i'm iterating through is very big. (I'm unable to find it out though, shell is automatically killed in minutes after i execute len(model.objects.all()). Considering that the process is killed just by trying to get its length, I knew searching through the objects would be negligible (and even searching through them by utilizing similarity algorithms). But i still tried it, I've used Cosine similarity to find out the best match, this is the code for search: zsim = ("", 0) for qst in Question.objects.all().iterator(): sim = cosine_similarity(qst.question, string) if zenith_sim[1] > 0.75: break elif sim > zenith_sim[1]: zenith_sim = (qst.answer, sim) return str(zenith_sim[0]) The code above searches for the string that is most similar to the string of the user, although to avoid insignificant iteration, if the similarity is above 75%, it breaks the loop. I've also used iterator() method hoping that it would save some memory. As expected, the process was killed few minutes later after its execution. I'm not sure how can this be improved. The machine itself is not slow, … -
Sending not only form input via a POST request but other data as well
I'm trying to "develop" an application that stores todo tasks in a table. These tasks are organised like sub tasks for a "head" task. The problem is that when submitting an input as a sub task via POST I need the name of the head-task as well. I can't figure out how to send the information have stored in my <h1>-label with the information I have in my <input>. Here is my code example: <h1>Taskheader</h1> <form action="/todo/task/" method="post"> <input type="text" name="Taskitem"> <input type="submit" value="Submit" /> </form> Is it possible to send this information off, without using overly complicated code for a beginner? -
i want user enter product name and quantity then using query show whether the stock available or no
please correct my code or guide me ho to do my funtion def productsearch(request): product=request.GET.get('product') quantity=request.GET.get('quantity') product_result=Product.objects.all().filter(product_id=product) if ('quantity') > product_result.quantity_onhand: print('stock is not available') return render(request,'product/productlocation.html',{'product_result' : product_result,'quantity_result':quantity_result, 'product': product,'quantity':quantity}) template... <body> {% if quantity_result %} {% for r in quantity_result %} {{r.quantity_onhand}} {% endfor %} {% else %} <h3>no results</h3> {% endif %} </body> -
Add reverse ForeignKey relation to existing instances from django admin
If I create a new model which is a ForeignKey of another, can I update existing instances of "another" to have the new ForeignKeys as I create them? i.e. without going through the individual edit page of each instance of "another"? Suppose that I have a Car model, and I create a bunch of Car instances filling their details in the django admin: # models.py from django.db import models class Car(models.Model): make = models.CharField(max_length=200) model = models.CharField(max_length=200) color = models.CharField(max_length=200) ... After a year I decide to start renting cars to customers: # models.py from django.db import models class Customer(models.Model): name = models.CharField(max_length=200) ... class Car(models.Model): make = models.CharField(max_length=200) model = models.CharField(max_length=200) color = models.CharField(max_length=200) rented_to = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) ... If I register Customer in the admin site, I can add new customers, edit their attributes and, using inlines, add new cars that are rented to that customer: #admin.py from django.contrib import admin from .models import Car, Customer class CarInline(admin.StackedInline): model = Car extra = 3 class CustomerAdmin(admin.ModelAdmin): inlines = [CarInline] admin.site.register(Customer, CustomerAdmin) Is there a way to add existing Car instances to a Customer from the Customer admin page, instead of clicking through all the cars and selecting … -
Django annotate count value of other class
Im new to Django. Im trying to display a total sum. Portfolio Model: # Create your models here. class Portfolio(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(User, related_name='portfolios', on_delete=models.PROTECT) def get_absolute_url(self): return reverse('portfolio:detail',kwargs={'pk': self.pk}) def __str__(self): return self.name class PortfolioItem(models.Model): portfolio = models.ForeignKey(Portfolio, related_name='items', on_delete=models.CASCADE) trade = models.ForeignKey(Trade, on_delete=models.CASCADE) Trade Model # Create your models here. class Trade(models.Model): quantity = models.FloatField() open_price = models.FloatField() commision = models.FloatField(null=True,blank=True) exchange_rate_usdsek = models.FloatField(null=True,blank=True) stock = models.ForeignKey(Stock, on_delete=models.CASCADE) #portfolio = models.ForeignKey(Portfolio, related_name='trades', on_delete=models.PROTECT) open_date = models.DateTimeField(auto_now_add=True, null=True) def get_absolute_url(self): return reverse('trade:detail',kwargs={'pk': self.pk}) def __str__(self): return self.stock.name @property def profit(self): #(sold - buy) / buy buy = self.open_price * self.quantity now = self.stock.current_price * self.quantity return ((now - buy ) / buy)*100 def net_gain(self): #(sold - buy) / buy buy = self.open_price * self.quantity now = self.stock.current_price * self.quantity return now - buy Portfolio index.html {% extends 'user/layout.html' %} {% block body %} {% for portfolio in all_portfolios %} <h3>{{portfolio.name}}</h3> <p>Total: {{portfolio.total_amount}}</p> <table class="table"> <thead> <tr> <th>Stock</th> <th>Amount</th> <th>Open Price</th> <th>Net P/L %</th> <th>Net P/L</th> </tr> </thead> {% for item in portfolio.items.all %} <tr> <td>{{item.trade.stock.name}}</td> <td>{{item.trade.quantity}}</td> <td>€{{item.trade.open_price}}</td> <td>€{{item.trade.stock.current_price}}</td> <td>{{item.trade.profit|floatformat:"0"}}%</td> <td>€{{item.trade.net_gain|floatformat:"2"}}</td> </tr> {% endfor %} </table> {% endfor %} {% endblock %} Portfolio view class IndexView(generic.ListView): template_name … -
How to upload and read PDF files in Django
I am trying to create a simple django application which takes some PDF files from user and then read its contents. So far I have written the code as mentioned below, But it doesn't seem to work. It's producing an error at this line PyPDF2.PdfFileReader(open(filename)) TypeError: expected str, bytes or os.PathLike object, not TemporaryUploadedFile index.html <input type="file" name="fupload" multiple> view.py if request.method == 'POST': files = request.FILES.getlist('fupload') pdf_data = [] for filename in files: read_pdf = PyPDF2.PdfFileReader(open(filename)) page = read_pdf.getPage(0) page_content = page.extractText() pdf_data.append(page_content) Can any body tell me what I am doing wrong. Thanks in advance -
Django 2 production image upload results in 500 error
I am using Django 2.0.1 within a virtual environment in production mode with Apache 2.4. Whenever I try to upload an image from Django's admin panel I get a server error 500. The specific error is [Sat Feb 10 11:37:42.473376 2018] [mpm_event:notice] [pid 1311:tid 140525266585472] AH00491: caught SIGTERM, shutting down Exception ignored in: <object repr() failed> Traceback (most recent call last): File "/var/www/springspree/server/venv/lib/python3.5/site-packages/PIL/Image.py", line 587, in __del__ NameError: name 'hasattr' is not defined Exception ignored in: <object repr() failed> Traceback (most recent call last): File "/var/www/springspree/server/venv/lib/python3.5/site-packages/PIL/Image.py", line 587, in __del__ NameError: name 'hasattr' is not defined The virtualhost file is <VirtualHost *:8000> ServerAdmin webdev@springspree.in ServerName www.springspree.in:8000 ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/springspree/server/static <Directory /var/www/springspree/server/static> Require all granted </Directory> Alias /media /var/www/springspree/server/media <Directory /var/www/springspree/server/media> Require all granted </Directory> <Directory /var/www/springspree/server/springspree> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django-server python-path=/var/www/springspree/server python-home=/var/www/springspree/server/venv WSGIProcessGroup django-server WSGIScriptAlias / /var/www/springspree/server/springspree/wsgi.py </VirtualHost> The files are in /var/www directory owned by root. I tried uninstalling and installing Pillow but no use. -
How to display an alert/confirmation message in Django views function?
I have written a Django view function to delete a user from AWS DynamoDB. Below is my views python function snippet : def deluser(request): db=boto3.client('dynamodb', region_name='us-west-2') acc=request.GET.get('acc') uid=request.GET.get('uid') aname=request.GET.get('aname') db.delete_item( TableName='User-Account', Key={ 'UserId': {'S': uid}, 'AccountNum': {'S': acc} } ) messages.add_message(request, messages.INFO, 'User '+uid+' successfully removed from '+acc+' : '+aname) return useracc(request) I am deleting a userid based on account number in a DynamoDB table. I have used Django message to display that the user has been removed. However, I would like to include a confirmation message/ alert asking like "Do you really want to remove/delete the user ?" before deleting it. If the user clicks on Yes only then the user will be deleted otherwise No. How can I do this ? Thanks in advance. -
Extra conditional annotation breaks previous annotation
I have the following models in a game app I'm working on:- class Player(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='players') class Game(models.Model): players = models.ManyToManyField(Player, through='GameMembership', related_name='games') class GameMembership(models.Model): game = models.ForeignKey(Game, related_name='memberships') player = models.ForeignKey(Player, related_name='memberships') team = models.ForeignKey(Team, null=True, related_name='memberships') selected = models.BooleanField(default=False) class Team(models.Model): game = models.ForeignKey(Game, related_name='teams') score = models.IntegerField(null=True) I want to get a list of all the Players along with the number of times they were selected, so I annotate the queryset like this:- Player.objects.all().annotate(played=Count(Case(When(memberships__selected=True, then=1)))) which works exactly as expected. However, I also want the total number of goals that were scored in all the games each player was selected, so I annotate like this:- Player.objects.all().annotate(played=Count(Case(When(memberships__selected=True, then=1))), total_goals=Sum(Case(When(memberships__selected=True, then='games__teams__score')))) which gives the right number for total_goals but for some reason, the value of the played count has doubled! All I did was add this annotation:- total_goals=Sum(Case(When(memberships__selected=True, then='games__teams__score'))) So what happened? I strongly suspect I need a distinct() call somewhere but I don't see why the extra annotation has an effect on the first one. Any ideas? -
Best Postgres/DB format for storing an array of strings with a boolean attached to them in Django?
I'm storing an array of URL links in my Postgres database like this: urls = ArrayField( models.CharField(max_length=250, blank=False) ) But I want to track if a URL has been visited or not, as a boolean. What is the best way to do this? -
Cannot redirect when djanog model class is mocked
I have a view here which adds a new List to the database and redirects to the List page. I have get_absolute_url configured in the model class. It seems to works perfectly. def new_list(request): form = ItemForm(request.POST) if form.is_valid(): list_ = List() list_.owner = request.user list_.save() form.save(for_list=list_) return redirect(list_) else: return render(request, 'home.html', {'form': form}) But the problem happens when I try to mock the model class and the form class with patch from unitest.mock class TestMyLists(TestCase): @patch('lists.views.List') @patch('lists.views.ItemForm') def test_list_owner_is_saved_if_user_is_authenticated( self, mockItemFormClass, mockListClass ): user = User.objects.create(email='a@b.com') self.client.force_login(user) self.client.post('/lists/new', data={'text': 'new item'}) mock_list = mockListClass.return_value self.assertEqual(mock_list.owner, user) When I run the test, I get error like this: Traceback (most recent call last): File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/BAC4BB93C4BB4FFD/codes/tdd/superlists/lists/views.py", line 36, in new_list return redirect(list_) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/shortcuts.py", line 58, in redirect return redirect_class(resolve_url(to, *args, **kwargs)) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/http/response.py", line 407, in __init__ self['Location'] = iri_to_uri(redirect_to) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/utils/encoding.py", line 151, in iri_to_uri return quote(iri, safe="/#%[]=:;$&()+,!?*@'~") File "/usr/local/lib/python3.6/urllib/parse.py", line 787, in quote return quote_from_bytes(string, safe) File "/usr/local/lib/python3.6/urllib/parse.py", line 812, in quote_from_bytes raise TypeError("quote_from_bytes() expected bytes") TypeError: quote_from_bytes() … -
Advices for social-networking
I am a high school student and I like computing. I have bases with C#, R, Python and I have been developing a static website with Html5 and CSS. I'd like now to start a new project. A social network like for riders but I don't know at all which framework or language start with. I already heard about Django, Ruby on Rails, Go, that make alot of choices and I wanted to have advices from experts or connoisseurs in the domain. -
django-rest-framwork Got AttributeError when attempting to get a value for field
i want get all prodcut table values with join product_ratings table . i did somthing like this but this code give me AttributeError ... i did product_ratings = ProductRatingSerializer(many=True) in product serializer and used this value in field but it not work: its full error message: Got AttributeError when attempting to get a value for field `product_ratings` on serializer `ProductSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Product` instance. Original exception text was: 'Product' object has no attribute 'product_ratings'. view : class StoreApiView(mixins.CreateModelMixin, generics.ListAPIView): lookup_field = 'pk' serializer_class = ProductSerializer def get_queryset(self): qs = Product.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter( Q(title__icontains=query) | Q(description__icontains=query) ).distinct() return qs its serializer classes: class ProductRatingSerializer(ModelSerializer): class Meta: model = Product_ratings fields = [ 'p_id', 'commenter', 'comment', 'rating', 'created_date', ] read_only_fields = ['p_id'] class ProductSerializer(ModelSerializer): product_ratings = ProductRatingSerializer(many=True) author = serializers.SerializerMethodField() def get_author(self, obj): return obj.author.first_name class Meta: model = Product fields = [ 'product_id', 'author', 'category', 'title', 'description', 'filepath', 'price', 'created_date', 'updated_date', 'product_ratings', ] read_only_fields = ['product_id', 'created_date', 'updated_date', 'author'] related model class : class Product(models.Model): product_id = models.AutoField(primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, to_field='cat_id') … -
Display output with out refresh using Django, Ajax
I am programming a simple basic calculator where I get the input from the user taking the input and do the calculation and display the output back on the same page I have a basic HTML form <form id="html_calc_form" action={%url 'calculation' %} method="post"> {% csrf_token %} First Number:<br> <input type="number" name="first number" value="0"> <br> Second Number:<br> <input type="number" name="second number" value="0"> <br> Operation:<br> <select name="operation" multiple> <option value="Addition">Addition</option> <option value="Subraction">Subraction</option> <option value="Muntiplication">Muntiplication</option> <option value="Division">Division</option> </select> <br><br> <input type="submit" name "submit" value="Submit"> <output name="result" ></output> </form> Ajax logic to prevent from refreshing the page $(document).ready(function(){ $('#html_calc_form').submit(function(event){ console.log(event); event.preventDefault() $.ajax({ url:'calc/', type:'POST', data:$(this).serialize(), success:function(response){ console.log(response); $('form')[0].reset(); } }); }) }) In django I have creates a model class Calculation(models.Model): first_digit = models.DecimalField(max_digits=7, decimal_places=3) second_digit = models.DecimalField(max_digits=7, decimal_places=3) CALCULATION_CHOICE = (('+', 'Addition'), ('-', 'Subraction'), ('*', 'Muntiplication'), ('/', 'Division')) calculate = models.CharField(max_length=1, choices=CALCULATION_CHOICE) And finaly my view def calc(request): if request.method == 'POST': first_number = request.POST['first number'] second_number = request.POST['second number'] operation = request.POST['operation'] result = do_calc(operation, first_number, second_number) # how to pass the result to my tempelate value = Calculation.objects.create( first_digit=first_number, second_digit=second_number, calculate=operation ) return JsonResponse(model_to_dict(value)) def index(request): return render(request, 'calculation/calculator.html') I want to pass the result to my HTML template and display … -
Django Jquery: Link (a-tag) to specific div on a different template does not work when this jQuery function is added
I have a link in a django template with the following characteristics: <a href="{% url 'rates:index' %}#our-services" class="accent-2">list</a> That link worked as intended until I used the JS code underneath in the same page as linked to above. This code lets the user select different tabs to display certain information. I am a novice when it comes to JS and therefore used a code snippet from Bourbon Refills. When I comment out the code the link works fine. Any suggestions on what part of the JS code affects the link? Any help would be greatly appreciated. $(function() { var containerSelector = '[data-tab-wrapper]'; var tabListSelector = '[data-tablist]'; var tabListItemSelector = '[data-tablist] > li'; var tabSelector = '[data-tablist] > li > a'; var tabPanelSelector = '[data-tabpanel]'; $(tabListSelector).attr('role', 'tablist'); $(tabListItemSelector).attr('role', 'presentation'); $(tabPanelSelector).attr('role', 'tabpanel'); // Setup: Wire up the anchors and their target tabPanels $(tabSelector).each(function(_, element) { $(element).attr({ 'role': 'tab', 'tabindex': '-1', 'aria-controls': getAnchor($(element)) }); }); // Setup: Set the tablist $(tabListSelector).attr('role', 'tablist'); // Setup: Select the first tab var firstTabLinkSelector = tabListItemSelector + ':first-child a'; select($(firstTabLinkSelector)); // Setup: Make each tabPanel focusable $(tabPanelSelector + ' > *:first-child').attr({'tabindex' : '0'}); // Setup: Hide all panels besides the first hide($(tabPanelSelector + ':not(:first-of-type)')); // When focused, … -
Check if user is part of a manytomany relationship django
I have this model for a Set: class Set(models.Model): name = CharField(max_length = 25) teacher = ForeignKey(get_user_model(), null = False, on_delete = models.CASCADE) students = ManyToManyField(get_user_model(), related_name= 'set_students') As you can see, the last field is a ManyToMany field. I need a queryset to get all the Sets that the user is part of. How would I do this? -
type char exceed 10485760 limit error still showing after I change the limit to something less than MAX
I have a django app, I'm migrating it's database from sqlite3 to postgres, i get the following error line since i got a field in one of the models set to 500000000 so i changed it to 10485750 and ran: python manage.py makemigrations app python manage.py sqlmigrate app 0001 python manage.py migrate but still got the following error django.db.utils.DataError: length for type varchar cannot exceed 10485760 LINE 1: ...ber" TYPE varchar(500000000) USING ........ how can I make it feel the change I made? -
Is there a way to raise normal Django form validation through ajax?
I found a similar question which is quite a bit outdated. I wonder if it's possible without the use of another library. Currently, the forms.ValidationError will trigger the form_invalid which will only return a JSON response with the error and status code. I have an ajax form and wonder if the usual django field validations can occur on the form field upon an ajax form submit. My form triggering the error: class PublicToggleForm(ModelForm): class Meta: model = Profile fields = [ "public", ] def clean_public(self): public_toggle = self.cleaned_data.get("public") if public_toggle is True: raise forms.ValidationError("ERROR") return public_toggle The corresponding View's mixin for ajax: from django.http import JsonResponse class AjaxFormMixin(object): def form_invalid(self, form): response = super(AjaxFormMixin, self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super(AjaxFormMixin, self).form_valid(form) if self.request.is_ajax(): print(form.cleaned_data) print("VALID") data = { 'message': "Successfully submitted form data." } return JsonResponse(data) else: return response The View: class PublicToggleFormView(AjaxFormMixin, FormView): form_class = PublicToggleForm success_url = '/form-success/' On the browser console, errors will come through as a 400 Bad Request, followed by the responseJSON which has the correct ValidationError message. Any way to get this done server side? -
Django template language extends doesn't work
Hi guys I am studying django framework using "django by example" book. The problem I am facing is that the template language does not work even I copy and pasted source code from book and/or github. A blog application that has post model and is inside the mysite project. You can see the code in picture and the result too: Inside blog\templates\blog . blog\templates\blog\base.html <!-- its base.html --> {% load staticfiles %} <!DOCTYPE HTML> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/blog.css" %}" rel="stylesheet"> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> <div id="sidebar"> <h2>My blog</h2> <p>This is my blog.</p> </div> </body> </html> Its the list that extends base.html and located in blog\template\blog\post: {% extends "blog/base.html" %} {% block title %}My Blog{% endblock %} {% block content %} <h1>My Blog</h1> {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|truncatewords:30|linebreaks }} {% endfor %} {% endblock %} -
How to order initial data in Django-autocomplete-light
I'd like to update many-to-many through model data using Django-autocomplete-light's ModelSelect2Multiple, but when sending data to the form with the get_initial(), the data is not displayed in the order of the data sent; it will be displayed in the database registration order. How should I do to display data in ModelSelect2Multiple in the sorted order in through model? ModelSelect2Multiple works well when new data is registered. Here is my model.py class Writer(models.Model): name = models.CharField() class Event(models.Model): name = models.CharField() writer = models.ManyToManyField(Writer, through="Attend", related_name='attends') class Attend(models.Model): event = models.ForeignKey(Event) writer = models.ForeignKey(Writer) number = models.PositiveSmallIntegerField(default=0) Here is my preview.py class EventUpdateFormPreview(FormPreview): form_template = "app/event_update.html" preview_template = "app/event_update_preview.html" def get_initial(self, request): event = Event.objects.get(id=self.state["event_id"]) return { 'name': event.name, 'writer': [x.pk for x in event.writer.all().order_by('attend__number')], } Here is my forms.py class EventUpdateForm(forms.ModelForm): name = forms.CharField(label='event name') writer = forms.ModelMultipleChoiceField( label='Attends', queryset=Writer.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='app:writer_autocomplete', ) ) Registration order in datababase Writer Mr.A(pk=1) Writer Mr.B(pk=2) Writer Mr.C(pk=3) Writer Mr.D(pk=4) The order of attendees in registered events(It will be successful at the initial registration) Writer Mr.D(pk=4) Writer Mr.A(pk=1) Writer Mr.C(pk=3) The order displayed on the update view Writer Mr.A(pk=1) Writer Mr.C(pk=3) Writer Mr.D(pk=4) Environment: Django==1.11.6 django-autocomplete-light==3.2.10 Please excuse my poor English, Thank you so … -
have issue with foundation dropdown menu in top-bar
I install foundation-sites with yarn or npm. So i have sources in node_modules/foundation-sites. I use django but i have the same issue without it Here is my index.html: {% load static %} {% load sass_tags %} <!DOCTYPE html> <html lang="fr"> <head> <meta charset="utf-8"> <title>short url</title> {% load compress %} {% compress css %} <link href="{% sass_src 'scss/style.scss' %}" rel="stylesheet" type="text/css" /> {% endcompress %} </head> <body> <div class="top-bar"> <div class="top-bar-left"> <ul class="dropdown menu" data-dropdown-menu> <li class="menu-text">shorturl</li> <li><a href="/shorturl">Racine</a></li> <li><a href="/shorturl/url_list">url list</a></li> <li> <a href="http://www.perdu.com">perdu</a> <ul class="menu vertical"> <li><a href="#">Lien 1</a></li> <li><a href="#">Lien 2</a></li> </ul> </li> </ul> </div> </div> {% block content %} {% endblock %} <script src="{% static "js/jquery/dist/jquery.js" %}"></script> <script src="{% static "js/what-input/dist/what-input.js" %}"></script> <script src="{% static "js/foundation-sites/dist/js/foundation.js" %}"></script> <script src="{% static "js/foundation-sites/dist/js/plugins/foundation.core.js" %}"></script> <script src="{% static "js/foundation-sites/dist/js/plugins/foundation.dropdown.js" %}"></script> <script src="{% static "js/foundation-sites/dist/js/plugins/foundation.dropdownMenu.js" %}"></script> <script src="{% static "js/foundation-sites/dist/js/plugins/foundation.util.keyboard.js" %}"></script> <script src="{% static "js/foundation-sites/dist/js/plugins/foundation.util.box.js" %}"></script> <script src="{% static "js/foundation-sites/dist/js/plugins/foundation.util.nest.js" %}"></script> <script src="{% static "js/app.js" %}"></script> </body> </html> When i load the web-page, i have this:issue with dropdown menu Someone has an idea to solve it ? Thx for your help -
Session.request and 'Decimal' is not JSON serializable
I try to improve my Django knowledge (I'm a beginner) by developing a Django ecommerce website. I'd like to have two types of cart, one named cart and this other one named composed_cart. I have an error with the composed_cart. I came accross the following error when I try to display the cart: Object of type 'Decimal' is not JSON serializable For my add to composed_cart class, I use the following code: composed_cart.py: class ComposedCart(object): def __init__(self, request): self.session = request.session composed_cart = self.session.get('composed_cart') if not composed_cart: composed_cart = self.session['composed_cart'] = {} self.composed_cart = composed_cart def add_composed(self, product, quantity=1): product_id = str(product.id) if product_id not in self.composed_cart: self.composed_cart[product_id] = {'quantity': 1,'price': str(product.prix_unitaire), 'tva': str(product.taux_TVA.taux_applicable)} else: self.composed_cart[product_id]['quantity'] += quantity #Ajoute +1 à la quantité et met à jour le dictionnaire contenant la quantité. += signifie ajoute à la valeur initiale de quantité. self.save() def save(self): self.session['composed_cart'] = self.composed_cart self.session.modified = True def remove(self, product): #Supprimer le produit, quelque soit la quantité. product_id = str(product.id) if product_id in self.composed_cart: del self.composed_cart[product_id] self.save() def remove_one(self, product, quantity=1): #Méthode permettant de supprimer une unité du produit. product_id = str(product.id) if product_id in self.composed_cart: #Si le produit est dans le panier if self.composed_cart[product_id]['quantity'] > 1: … -
How Can I Restrict One Vote For One User?
My models.py is this and I have created the user registration form. I want to restrict one vote for one user. How Can I do so? class Choice(models.Model): choice_text = models.CharField(max_length= 200) votes = models.IntegerField(default= 0) image2 = models.ImageField(upload_to="Question_Image2", blank=True) question = models.ForeignKey(Question, on_delete= models.CASCADE) def __str__(self): return self.choice_text def vote_range(self): return range(0, self.votes) My views.py is this for vote def vote(request, question_id): question = get_object_or_404(Question, pk= question_id) try: selected_choice = question.choice_set.get(pk = request.POST['choice']) except: return render(request, 'polls/detail.html', {'question':question, 'error_message':"Please select a choice"}) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results',args = (question.id,)))