Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
no search results Django 2.1 Solr 6.5
I implemented solr 6.5 for django 2.1 with haystack 2.5 and i succesfully built index but theres still no search results q*:* returns { "responseHeader":{ "status":0, "QTime":0, "params":{ "q":"*:*", "indent":"on", "wt":"json", "_":"1543140724323"}}, "response":{"numFound":5,"start":0,"docs":[ { "id":"blog.post.1", "django_ct":["blog.post"], "publish":["2019-05-26T04:46:00+00:00Z"], "text":["Chwalmy wodza\nsanacja, wódz, historia, sumienie\nBo jeden jest wódz\n\n"], "django_id":[1], "_version_":1618099571920994304}, { "id":"blog.post.3", "django_ct":["blog.post"], "publish":["2018-11-15T20:59:39+00:00Z"], "text":["Trwoga Krzyk Gardłowy\nwódz\nsome\n\n"], "django_id":[3], "_version_":1618099571923091456}, { "id":"blog.post.4", "django_ct":["blog.post"], "publish":["2018-11-15T21:24:01+00:00Z"], "text":["Jeszcze jeden post\nsanacja, wódz\nChwalmy wodza\n\n"], "django_id":[4], "_version_":1618099571924140032}, { "id":"blog.post.5", "django_ct":["blog.post"], "publish":["2018-11-21T14:41:25+00:00Z"], "text":["Yep\nsanacja, wódz\nffff\n\n"], "django_id":[5], "_version_":1618099571925188608}, { "id":"blog.post.7", "django_ct":["blog.post"], "publish":["2018-11-21T21:30:30+00:00Z"], "text":["Markdown\nhistoria, sanacja, wódz\n*wyróżnienie* **pogrubienie**\nlistę:\n\n\n\n\nSometimes you want bullet points:\n\n* Start a line with a star\n* Profit!\n* Start a line with a star\n* Else\n\nTutaj jest [sabaton](https://www.youtube.com/watch?v=_HLNMfCBUb0)\n\n"], "django_id":[7], "_version_":1618099571925188609}] So core is populated My view: def post_search(request): form = SearchForm() if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): cd = form.cleaned_data results = SearchQuerySet().models(Post)\ .filter(content=cd['query']).load_all() # Obliczenie całkowitej liczby wyników. total_results = results.count() return render(request, 'blog/post/search.html', {'form': form, 'cd': cd, 'results': results, 'total_results': total_results}) else: return render(request, 'blog/post/search.html', {'form': form}) And my form class SearchForm(forms.Form): query = forms.CharField() I tried procedure proposed by haystack itself >>> from haystack.query import SearchQuerySet >>> sqs = SearchQuerySet().all() >>> sqs.count() But I only recived AttributeError: 'list' object has no attribute 'split' So here's the problem, posts are … -
Django - Authenticate with custom User model returns None
I'm following a tutorial (https://thinkster.io/tutorials/django-json-api/authentication) on setting up authentication. I've got to the point where I'm registering users and receiving the tokens back. I can drop into the shell and do; >>> user = Users.objects.first() >>> user.email >>> test@outlook.com >>> user.password >>> 12345678 This shows that the user exists in the database. But when calling my login endpoint; /users/login/ the authenticate method returns None. user = authenticate(username=email, password=password) I'm printing the email and password just before and it shows the correct data passed in. I've also set my USERNAME_FIELD to email in my model. USERNAME_FIELD = 'email' I've updated my model in my settings to be AUTH_USER_MODEL = 'aemauthentication.User' I've had a look around and the above line in the settings file seems to be the approved answer for most people with this issue. GitHub link to project - https://github.com/Daniel-sims/aem_1 -
how to get a queryset not a dictionary in django using Queryset.values()
I know that Queryset.values() return a dictionary but I want a queryset as Queryset.all() return. I want to use Queryset.values() because I want my database to only return limited fields using optional arguments of *fields in values. let us say I have a model Person as: class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) def __str__(self): return self.first_name When I query database with: Person.objects.values('first_name') I get: <QuerySet [{'first_name': 'Hello'}]> But I want as below, which I get it using Queryset.all() but with all fields: <QuerySet [<Person: Hello>]> So, is there any way to do this. -
Manually populating modelformset Django for testing
I have a problem with the error django.forms.utils.ValidationError: ['ManagementForm data is missing or has been tampered with'], but it only occurs in testing my code. When rendering the actual webpage with a real POST-request it does not throw this error. I have a model called Position and the formset consists of its Candidate-objects. So for a particular position, I may have 4 candidates. models.py class Candidate(models.Model): user = models.ForeignKey(User, related_name="candidate") votes = models.PositiveIntegerField(verbose_name="Antall stemmer", blank=True, default=0) class Position(models.Model): # Candidates running for position candidates = models.ManyToManyField(Candidate, blank=True, related_name="positions") # Number of people voting number_of_voters = models.PositiveIntegerField(default=0, verbose_name="Antall stemmesedler avgitt") forms.py class AddPrevoteForm(forms.ModelForm): class Meta: model = Position fields = ['number_of_voters'] class AddPreVoteToCandidateForm(forms.ModelForm): class Meta: model = Candidate fields = ['votes'] def __init__(self, *args, **kwargs): super(AddPreVoteToCandidateForm, self).__init__(*args, **kwargs) self.fields['votes'].label = self.instance.user.get_full_name() views.py @permission_required('elections.add_election') @login_required def admin_register_prevotes(request, pk): # Fetch position position = get_object_or_404(Position, pk=pk) # For for editing total number of people prevoting prevote_form = AddPrevoteForm(request.POST or None, instance=position) # Form for adjusting individual candidate's votes CandidateFormSet = modelformset_factory( Candidate, form=AddPreVoteToCandidateForm, extra=0 ) formset = CandidateFormSet( request.POST or None, queryset=position.candidates.all() ) if request.method == 'POST': if formset.is_valid() and prevote_form.is_valid(): for form in formset: # Increment both candidate and positions votes candidate_pk … -
how to add form with generic list view in django
i want to add form in my home view which is a Generic list view but i couldn't . here is my code... views.py class home_view(ListView): model = home_blog_model template_name = "home.html" context_object_name = "posts" paginate_by = 6 ordering = ['-date'] def get_context_data(self , **kwargs): context = super(home_view , self).get_context_data(**kwargs) context.update({"snippets":snippet_form_model.objects.all()}) return context i already added one snippet view in the same list view and i want to add another form into that. Here is my form... forms.py class feedback_form(forms.ModelForm): name = forms.CharField(required=True) email = forms.EmailField(required=True) message = forms.CharField(required=True , widget=forms.Textarea(attrs={"placeholder":"what do you want to say"})) class Meta: model = feedback_form_model fields = ["name" , "email" , "message"] i also created function based view for that form here... def feedback_view(request): if request.method == "POST": form = feedback_form(request.POST) if form.is_valid(): form.save() return redirect("/home/") else: form = feedback_form() return render(request , "base.html" , {"form":form}) this function based view didn't worked though. what should i do ? -
Unable to Start Celery worker instance : Syntax error
I am trying to run a task in django view asynchronously. For that i am using celery and rabbitmq. By following the guide for small scale context i have defined task in my module(servicenow.py) as - app = Celery('servicenow',broker='amqp://username:password@localhost:15672') . . @app.task def get_ITARAS_dump(self): . . self.update_state(state='PROGRESS',meta={'current':i,'total':len(taskList)}) My rabbitmq server is running within brew services Rabbitmq management on safari After this i tried to start a worker instance with celery -A servicenow worker -l info then i the error message as - Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/bin/celery", line 11, in <module> sys.exit(main()) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/celery/__main__.py", line 30, in main main() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/celery/bin/celery.py", line 81, in main cmd.execute_from_commandline(argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/celery/bin/celery.py", line 793, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/celery/bin/base.py", line 311, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/celery/bin/celery.py", line 785, in handle_argv return self.execute(command, argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/celery/bin/celery.py", line 717, in execute ).run_from_argv(self.prog_name, argv[1:], command=argv[0]) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/celery/bin/worker.py", line 179, in run_from_argv return self(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/celery/bin/base.py", line 274, in __call__ ret = self.run(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/celery/bin/worker.py", line 194, in run pool_cls = (concurrency.get_implementation(pool_cls) or File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/celery/concurrency/__init__.py", line 29, in get_implementation return symbol_by_name(cls, ALIASES) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/kombu/utils/__init__.py", line 96, in symbol_by_name module = imp(module_name, package=package, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], … -
what is the best practice to add an action that update a field in models, within django class based view?
im build a blog with django and i have a DetailView for a blog post and i want every time someone access the post its the has been seen field is increase by 1, i already do my code but i doubt this is not the best way to do it, what is the best practice that should i implement in my code? this is my view.py class InformasiView(generic.DetailView): model = Berita template_name = 'berita/detail.html' def get_context_data(self, **kwargs): pk = self.kwargs.get('pk') // this is where its update the counter postingan = Berita.objects.get(pk=pk) postingan.dibaca = F('dibaca') + 1 postingan.save() tglku = Berita.objects.get(pk=pk).tgl_publish context = super(InformasiView, self).get_context_data(**kwargs) context['kategori_list'] = Berita.objects.values('kategori__judul','kategori__id').annotate(hasil=Count('kategori')) # context['next'] = Berita.objects.filter(tgl_publish__lte=timezone.now()).order_by('-tgl_publish') context['populer'] = Berita.objects.filter(tgl_publish__lte=timezone.now()).order_by('-dibaca')[:5] context['selanjutnya'] = Berita.objects.filter(tgl_publish__lte=timezone.now()).filter(tgl_publish__gt=tglku).order_by('tgl_publish')[:1] context['sebelumnya'] = Berita.objects.filter(tgl_publish__lte=timezone.now()).filter(tgl_publish__lt=tglku).order_by('-tgl_publish')[:1] return context def get_queryset(self): return Berita.objects.filter(tgl_publish__lte=timezone.now()).order_by('-tgl_publish') -
System architecture of notification system for a website
I want to design a notification system for my website based on some events the user performs like sharing a post or adding a post. I want to display only first 10 notifications of the user in the website. I am not clear about the system architecture that has to be implemented. How to implement my notification system backend for efficient and faster results. Like, should I use database for storing all the notifications and elastic search for storing first 10 notifications of the users ? Could you suggest me with multiple ways of implementing the notification system Thank you. -
django how to use a html tag attribute in views.py?
I'm trying to create a view that change a boolean and switch images from it, i already done it but i need to iterate between 12 values (asiento) and i only can point to one of them this is my django code. models.py class Asientos(models.Model): asiento = models.CharField(max_length=2) status = models.BooleanField() mesa = models.ForeignKey(Reserva) def __str__(self): template = 'Asiento {0.asiento} de la mesa {0.mesa}' return template.format(self) views.py def reservacion(request): estatus = Asientos.objects.get(asiento='asiento') if request.method == "POST": if estatus.status == True: estatus.status = False estatus.status.save() else: estatus.status = True estatus.status.save() return render(request,"first_app/reservacion.html", {'estatus': estatus}) html <form enctype="multipart/form-data" method="post"> {% csrf_token %} <div class="row"> {% for asiento in estatus %} {% if estatus.status == True%} <div class="col"><input class="d-block w-100" type="image" src="{%static "/img/s6.jpg" %}" name="asiento" value=""></div> {% else %} <div class="col"><input class="d-block w-100" type="image" src="{%static "/img/sn6.jpg" %}" name="asiento" value=""></div> {% endif %} {% endfor %} </div> </form> this sends me an error: Asientos matching query does not exist. estatus = Asientos.objects.get(asiento=** how can i give this the value that every div tag have?? **) -
ordering in listview of django
i am in django 2 and facing some issues here. Let me give you my files first views.py class home_view(ListView): model = home_blog_model template_name = "home.html" context_object_name = "posts" paginate_by = 6 ordering = ['-date'] def get_context_data(self , **kwargs): context = super(home_view , self).get_context_data(**kwargs) context.update({"snippets":snippet_form_model.objects.all()}) return context models.py class snippet_form_model(models.Model): title = models.CharField(max_length=500) language = models.CharField(max_length=50) code = models.TextField() describe = models.TextField() class Meta: ordering = ['-created'] def __str__(self): return self.title problem is i want to order the elements of {{ snippet_form_model }} into reverse order but i didnt specified date in that model to order by. Is there any sort of different way to set the order ? -
Create a crosstabular Django form based on a database table
Using Python 3 and Django 2, I have a project connected to an Amazon RDS MySQL database containing a table as such: region | date | date_type | revenue ----------------------------------- East | Oct | Actual | 150 East | Nov | Actual | 180 East | Dec | Forecast | NULL West | Oct | Actual | 120 West | Nov | Actual | 125 West | Dec | Forecast | NULL I would like this table pivoted on the month column to create a form that resembles the following, with revenue loaded into 'Actual' columns and input fields in 'Forecast' columns: region | Oct | Nov | Dec | Total | ------------------------------------------ East | 150 | 180 | <usr input> | SUM() | -Submit- West | 120 | 125 | <usr input> | SUM() | -Submit- When the user clicks 'Submit', that row should be inserted into a different table in MySQL. The 'Total' column should sum the values in the row but doesn't need to be inserted. It's important that the form(s) be dynamic so that one row (or one form) for each unique 'region' is returned. As you have probably inferred, I'm not an experienced developer so … -
How access JSON object serialized by Django
I'm not able to access primary key of an object serialized by Django in JSON. My JavaScript looks like: function makeLink() { recorder && recorder.exportWAV(function (blob) { let fd = new FormData; fd.append("audio", blob); let csrftoken = getCookie('csrftoken'); let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var obj = JSON.parse(this.responseText); /*console.log(obj[0].pk);*/ document.getElementById("result").innerHTML = obj.data[0]['pk']; } } xhr.open('POST', uploadAudio_url , true) //alert(uploadAudio_url) xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.onload = function () { // __log("Audio Uploaded to server succesfully"); }; xhr.onerror = function (e) { // __log("Error Uploading audio" + e) }; xhr.send(fd); }); } I send the blob data which it is an audio file in order to process speech in the backend. The backend process the audio file and filter the objects properly. Then it response to the client with a queryset in JSON. I have interested in get the objects PK and show images in a gallery grid. This is my Views.py: def process_speech(recognized_audio): speech = recognized_audio url = '' # Is the URL where the user will be redirected once speech is proccessed keylist = [] for key in Keyword.objects.all(): if(speech.find(key.keyword.lower()) != -1): keylist.append(key.keyword) print('Identificado Keyword: ', keylist) if (speech.find('fotos') != … -
How to authenticate user with Django AllAuth using either email or username in one field?
Is there any way in Django AllAuth with configuration ACCOUNT_AUTHENTICATION_METHOD = 'username_email' to send text from input "USERNAME OR EMAIL" and authenticate it automatically? I don't mean frontend logic, just AllAuth authentication. So it would get a JSON with fields for instance "username_email" : "myusername", "password" : "password" or "username_email" : "myemail@gmail.com", "password" : "password" and it would automatically check whether a user with nick or email myusername exists and his password is password. In the second case it would also check whether a user with nick or email myemail@gmail.com exists and his password is password. If so the user would be authenticated. Any ideas? -
Django custom ChoiceField cohoices for each model instance
I'm trying to create a form that has a choice field with choices unique for each model instance. Is there a way to do this easily? My current code looks like this: class Character(Model): ... class MyUser(AbstractUser): main_id = IntegerField(Character) # might be better with ForeignKey, but i need the id only ... class CharacterOwnership(Model): owner = ForeignKey(User) character = ForeignKey(Character) begin = DateField() end = DateField() Now I want to create a form field which will allow each user to select one of the characters he owns as their main. I've tried something like this, but this does not even change the widget. class MyUserForm(ModelForm): def __init__(self, *args, **kwargs): super(MyUserForm, self).__init__(*args, **kwargs) self.fields['main_id'] = ChoiceField(choices=current_characters_choices(self.instance)) class Meta: model = MyUser fields = ['main_id', ...] Is there a way to do this the simple way in the models or do I really need to go all the way to manually code the form in the template and view? -
how can i use a variable from my view on a if statement in django
Im trying to change a boolean value in django when I click an input image I think I already done it but now when I try to compare this boolean in my html it doesnt bring the correct value it always brings its as False (sn6.jpg) View.py def reservacion(request): if request.method == "POST": estatus = Asientos.objects.get(asiento=1) if estatus.status == True: estatus.status = False estatus.save() else: estatus.status = True estatus.save() return render(request,"reservacion.html") Models.py class Reserva(models.Model): mesa = models.CharField(max_length=2,primary_key=True) asiento = models.ForeignKey(Asientos) def __str__(self): return self.mesa html-- in here my if statements change the value of the boolean on my DB but it always shows the image in False (sn6.jpg) <form enctype="multipart/form-data" method="post"> {% csrf_token %} <div class="row"> {% if estatus.status == True%} <div class="col"><input class="d-block w-100" type="image" src="{%static "/img/s6.jpg" %}" name="1" value=""></div> {% else %} <div class="col"><input class="d-block w-100" type="image" src="{%static "/img/sn6.jpg" %}" name="1" value=""></div> {% endif %} </form> Am I missing something?, how can i get the other oimage when i click and submit the value? -
Why can't I open() and parse() this JSON file in Javascript?
I am using Django to build a web serivce in Python and one of my tasks is to parse a .json file within my project. The code compiles but the var json_data trying to hold the data becomes null when I try to access the json file. <head> <meta charset="UTF-8"> <title>Network Graph3</title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <script> // import json; window.onload = function () { var arr = []; var json_data = open("{% static 'static/json/graphData.json' %}"); var obj = JSON.parse(json_data); var i; console.log(json_data) if (obj == null){ return } for (i = 0; i < obj.documents; i++){ point = obj.documents[i]; arr[point.id].y = point.score; } var chart = new CanvasJS.Chart("chartContainer", { animationEnabled: true, theme: "light2", title:{ text: "Dialog Sentiment Analysis" }, axisY:{ includeZero: false }, data: [{ type: "line", dataPoints: arr // [ // { y: 450 }, // { y: 414}, // { y: 520, indexLabel: "highest",markerColor: "red", markerType: "triangle" }, // { y: 460 }, // { y: 450 }, // { y: 500 }, // { y: 480 }, // { y: 480 }, // { y: 410 , indexLabel: "lowest",markerColor: "DarkSlateGrey", markerType: "cross" }, // { y: 500 }, // { y: 480 }, // … -
Return proxied class in many to many relation
From another installed app, I have models like this class Organization(model.Model): name = models.CharField(max_length=255, blank=True) class Person(model.Model): name = models.CharField(max_length=255, blank=True) class Membership(model.Model): organization = models.ForeignKey( Organization, related_name='memberships', # memberships will go away if the org does on_delete=models.CASCADE, help_text="A link to the Organization in which the Person is a member.") person = models.ForeignKey( Person, related_name='memberships', null=True, # Membership will just unlink if the person goes away on_delete=models.SET_NULL, help_text="A link to the Person that is a member of the Organization.") In my app, I need to add some method to some of the models. So I have a model like class ProxiedPerson(other_app.models.Person): class Meta: proxy = True def special_method(self): print('I do something special') When I get the memberships from an organization, they are of type other_app.Person. > type(org.memberships[o].person) <class 'other_app.models.Person'> but, I'd like them to be my instances of my proxy class > type(org.memberships[o].person) <class 'my_app.models.ProxiedPerson'> Is there a good way of doing this? Is this the kind of thing that I can do with a query manager? -
Django framework: function runs in console but it does not work when I run from browser
from console I can get the user by filtering the id and I can edit the information and save to database exactly the same as each step in my function, but when I run the code and I edit from browser nothing change in database. the function redirect to the final_parent_profile I also have no error. i really need to know why this function doesn't work? xml @csrf_exempt def insert_parent_profile_to_db(request): lv_last_name = request.POST.get('parentLastName').strip() lv_phone_number = request.POST.get('phoneNumber').strip() lv_country_of_residence = request.POST.get('parentCountryOfResidence').strip() lv_country_of_birth = request.POST.get('parentCountryOfBirth').strip() lv_postal_code = request.POST.get('postalCode').strip() lv_city = request.POST.get('city').strip() lv_province = request.POST.get('province').strip() lv_address = request.POST.get('address').strip() if is_empty(lv_last_name) or is_empty(lv_country_of_residence) or \ is_empty(lv_postal_code) or is_empty(lv_city) or is_empty(lv_province): HttpResponse("Please fill all the * fields!") # Need to validate the postal code based on country parent = Parents.objects.get(id=request.session['user_id']) parent.parentLastName = lv_last_name parent.phoneNumber = lv_phone_number parent.parentCountryOfResidence = lv_country_of_residence parent.parentCountryOfBirth = lv_country_of_birth parent.postalCode = lv_postal_code parent.city = lv_city parent.province = lv_province parent.address = lv_address parent.save() return redirect(final_parent_profile) -
check if matching query does not exist return empty string
when i try to check if an object exist return it to in excel file if not return to me an empty 'string' but i have error in the if sentence price_date_all = PackagePricesAndDates.objects.filter(package=pkg) if price_date_all.get(territory=ter.pk).sales: list.append(str(price_date_all.get(territory=ter.pk).sales)) -
Django Models - Field Syntax
Quick question regarding some syntax when creating django models. If you take a look at the example models.py file below, you'll see that each of the four fields contain a repeat of the field name as a string in parentheses preceded my an underscore. I assume this is some kind of visual representation for when this is encountered in a form, but that seems to happen automatically in admin with out the _('field name'). class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) -
Display purchase history from Django Admin
I am trying to show the purchase history per user on the each users dashboard. I have made some dummy orders in Stripe which are working but I am having difficulty displaying the orders in the order history section of the page. I am also not sure the order is linking correctly to the registered user in the first place as I seem to be confusing myself with this method Can somebody help me or point me in the right direction please? <div class="container"> <div class="row"> <div class="col-sm-12 col-md-12 col-lg-12"> <table class="table table-striped"> <h3>Your order history</h3> <hr> <tr> <th>Date</th> <th>Invoice ID</th> <th>Description</th> <th>Total</th> </tr> {% for orders in orders %} <tr> <td scope="row">{{ order.quantity }}</td> <td>xxx</td> <td>xxx</td> <td>xxx</td> </tr> {% endfor %} </table> </div> My checkout views.py from django.contrib import messages, auth from django.contrib.auth.decorators import login_required from checkout.forms import MakePaymentForm from django.shortcuts import render, get_object_or_404, redirect, reverse from django.template.context_processors import csrf from django.conf import settings from babysitters.models import Babysitter import stripe # stripe.api_key = settings.STRIPE_SECRET @login_required(login_url="/accounts/login") def buy_now(request, id): if request.method == 'POST': form = MakePaymentForm(request.POST) if form.is_valid(): try: babysitter = get_object_or_404(Babysitter, pk=id) customer = stripe.Charge.create( amount= int(babysitter.price * 100), currency="EUR", description=babysitter.firstName, card=form.cleaned_data['stripe_id'], ) except (stripe.error.CardError): messages.error(request, "Your card was … -
Django AttributeError: 'int' object has no attribute 'save'
I have 2 models Profiles and Events. I want to save the number of events created by the user to the users profile, such that even if the events are deleted the record stays in the users profile class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) total_events = models.IntegerField(default=0) class Event(models.Model): user = models.ForeignKey(User, related_name='seller') ... Below are my views class CreateEvent(IsVerifiedMixin, CreateView): model = Event form_class = EventForm template_name = 'event/event_form.html' def form_valid(self, form, *args, **kwargs): self.object = form.save(commit=False) self.object.user = self.request.user print(self.object.user.profile.total_events) #This prints 0 self.object.user.profile.total_events += 1 print(self.object.user.profile.total_events) # This prints 1 self.object.user.profile.total_events.save() # If I don't use this statement it does not save to database. But It gives me the above error self.object.save() return super().form_valid(form) This line self.object.user.profile.total_events.save() gives me the error How do I fix this error. I tried adding a variable and saving the variable but I still get the same error -
django restframework how to count object and get since(timestamp)?
guys. Im trying to make a notifications system through django restframework, my problem is that i don't know how to get a count of notifications unread and either make a format of the timestamp to since(timestamp) through django restframework because in a normal view i know perfectly how to do that. Well this is my model: class Notificaciones(models.Model): user_a_notificar = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) komentario = models.OneToOneField(Post,on_delete=models.CASCADE, blank=True, related_name="komentario") estado = models.ManyToManyField('Evento', blank=True) def __str__(self): return self.user_a_notificar.username class Evento(models.Model): creadores = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="generadores") status = models.CharField(default="Unread", max_length=10) mensaje = models.CharField(max_length=200) event = models.CharField(max_length=15) noti_de_evento = models.ForeignKey(Notificaciones, on_delete=models.CASCADE) timestampe = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.mensaje my view: class Notifi(APIView): serializer = notizerializer def get(self, request, format=None): noti = Notificaciones.objects.filter(user_a_notificar=request.user.id) lista_noti = Evento.objects.filter(noti_de_evento__in=noti) lista_noticount = Evento.objects.filter(noti_de_evento__in=noti, status="Unread").count() response = self.serializer(lista_noti, many=True) return HttpResponse(json.dumps(response.data)) and finally my serializer: class notizerializer(ModelSerializer): class Meta: model = Evento fields = ('status', 'mensaje', 'event', 'timestampe', 'id') -
Django auth model: combine multiple fields into one username_field
I have multiple fields users have to specify on signup: date_of_birth, first_name, last_name. What I now want is to combine these fields to one for USERNAME_FIELD, like so: John_Doe_01011988 The following obviously doesn't work: USERNAME_FIELD='%s-%s' % ('first_name', 'last_name') -
Django Serializer Nested Creation: How to avoid N+1 queries on relations
There are dozens of posts about n+1 queries in nested relations in Django, but I can't seem to find the answer to my question. Here's the context: The Models class Book(models.Model): title = models.CharField(max_length=255) class Tag(models.Model): book = models.ForeignKey('app.Book', on_delete=models.CASCADE, related_name='tags') category = models.ForeignKey('app.TagCategory', on_delete=models.PROTECT) page = models.PositiveIntegerField() class TagCategory(models.Model): title = models.CharField(max_length=255) key = models.CharField(max_length=255) A book has many tags, each tag belongs to a tag category. The Serializers class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag exclude = ['id', 'book'] class BookSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True, required=False) class Meta: model = Book fields = ['title', 'tags'] def create(self, validated_data): with transaction.atomic(): tags = validated_data.pop('tags') book = Book.objects.create(**validated_data) Tag.objects.bulk_create([Tag(book=book, **tag) for tag in tags]) return book The Problem I am trying to POST to the BookViewSet with the following example data: { "title": "The Jungle Book" "tags": [ { "page": 1, "category": 36 }, // plot intro { "page": 2, "category": 37 }, // character intro { "page": 4, "category": 37 }, // character intro // ... up to 1000 tags ] } This all works, however during the post, the serializer proceeds to make a call for each tag to check if the category_id is a valid one. See the …