Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to build a survey HTML form using DJANGO querysets. please hep urgently. Guide me with steps required
I want to build a HTML form for a simple survey. the survey has three models -: 1. Question(Within that there is a class attribute which has recursive relation in Foreign Key) 2. choices 3. Answers(The data should be saved in JSONField) -
How do I check if a user is in a certain group? Django
I did not understand this solution: In Django, how do I check if a user is in a certain group? Where i should write that solution? in views.py? And what should i write in html template to use it?? Can someone explain me that? Also that(Check Django User Group) is not working too (Invalid filter: 'is_group'). -
The best way to use full-text search in django-filters' FilterSet?
My app uses rest-framework and django-filter. I use this FilterSet to provide filtering list of articles (ModelViewSet) by date: from django_filters import rest_framework as filters class ArticleFilter(filters.FilterSet): start_date = filters.DateTimeFilter(field_name='pub_date', lookup_expr='gte') end_date = filters.DateTimeFilter(field_name='pub_date', lookup_expr='lte') class Meta: model = Article fields = ['pub_date'] I want to add search box to my app, so I need another filter, that will use full-text search at my Article model. Fields I would to search are title and description. I decided to add search field with method parameter like that: from django_filters import rest_framework as filters from django.contrib.postgres.search import SearchVector class ArticleFilter(filters.FilterSet): start_date = filters.DateTimeFilter(field_name='pub_date', lookup_expr='gte') end_date = filters.DateTimeFilter(field_name='pub_date', lookup_expr='lte') search = filters.CharFilter(method='filter_search') def filter_search(self, queryset, name, value): return queryset.annotate(search=SearchVector('title', 'description')).filter(search=value) class Meta: model = Article fields = ['pub_date'] It works, but I'm not sure that it's the best way of using full-text search filtering. Am I missing something or this approach is ok? -
Filtering another model field count for each item from object_list (List View, Django)
I am learining Django trying to create a blog. I have a ListView of Post model on Homepage. I am trying to add new context data (number of comments from separate model Comment for each item from ListView). However I wasn't able to correctly filter number of Comments for each Post by using __in (it just shows same total number of Comments on each Post item of ListView). Could you please help me with how to get a correct filter to show for each ListView Post item how many Comments does it have? Thanks! Post Model: class Post(models.Model): class Meta: verbose_name = 'запись' verbose_name_plural = 'записи' title = models.CharField('название', max_length=300, help_text='Не более 300 знаков') content = models.TextField('текст записи') date_posted = models.DateTimeField('дата публикации', default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='автор') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) Comment model: class Comment(models.Model): class Meta: verbose_name = 'комментарий' verbose_name_plural = 'комментарии' content = models.CharField('текст комментария', max_length=500, help_text='Не более 500 знаков') date_posted = models.DateTimeField('дата публикации', default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name = 'автор') postid = models.ForeignKey(Post, on_delete=models.CASCADE) ListView in views.py: class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self, **kwargs): context = … -
How to autosave Foreignkey value inside my second Model with the id of my first model object.??
I have two models . Appname and Adspace ,I have a Foreignkey object in second model which connects to my first model. Here is the Code models.py class Appname(models.Model): name=models.CharField(max_length=150,blank=False,null=False,help_text='Add your new App') def __str__(self): return self.name def get_absolute_url(self): return reverse("dashapp:space",kwargs={'pk':self.pk}) class Adspace(models.Model): ad_space=models.CharField(max_length=150,blank=False,null=False) app=models.ForeignKey('Appname', related_name='appnames',default=None, on_delete=models.CASCADE) PID_TYPE = ( ('FN','FORMAT_NATIVE'), ('FNB','FORMAT_NATIVE_BANNER'), ('FI','FORMAT_INTERSTITIAL'), ('FB','FORMAT_BANNER'), ('FMR','FORMAT_MEDIUM,RECT'), ('FRV','FORMAT_REWARDED_VIDEO'), ) format_type=models.CharField(max_length=3,choices=PID_TYPE,default='FN',blank=False, null=False) def __str__(self): return self.ad_space def get_absolute_url(self): return reverse("dashapp:view") modelForm class AdspaceForm(forms.ModelForm): class Meta: model=Adspace fields=('ad_space',) Views.py class space(LoginRequiredMixin,CreateView): form_class=forms.AdspaceForm model=Adspace Now I.m unable to fill my form as it says it app_id cannot be null and i'm allowing user to input it. I want that the app which got clicked has its ID in the url (As I'm passing it through there). What should i do that it gets autosave with the same id number by itself that is being passed in the url. -
Django rest framework basic auth for api store in api_credentials table
I want to use Basic Auth for a api which receive JSON data and store in the database table. The problem I faced is to setup Basic Auth for the API. The API username and password store in api_credentials table in 2 separate column. Its has no relation with user table. In my api.py class EventDataViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): queryset = models.EventData.objects.all() serializer_class = serializers.EventDataSerializer authentication_classes = (eventdataapiauth,) # I write this class permission_classes = (permissions.IsAuthenticated,) eventdataapiauth is my auth class. How can I write my authentication code in that class. Or is there any other better way to do this? -
How to read multiple files in django
I have created command in django that reads a csv file and seeds data to the database. Currently, I can only read one file , how can I read multiple files in a directory with the following implementation below. I think I should have some sort of a list of directories and then for each file I will do the seeding. from __future__ import unicode_literals import csv from django.core.management.base import BaseCommand from elite_schedule.models import Match SILENT, NORMAL, VERBOSE, VERY_VERBOSE = 0, 1, 2, 3 import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) x=os.path.join(BASE_DIR, 'matches.csv') class Command(BaseCommand): help = ("Imports movies from a local CSV file. " "Expects title, URL, and release year.") # def add_arguments(self, parser): # # Positional arguments # parser.add_argument("file_path",nargs=1,type=str,) def handle(self, *args, **options): verbosity = options.get("verbosity", NORMAL) file_path = x print(file_path) if verbosity >= NORMAL: self.stdout.write("=== Matches imported ===") with open(file_path) as f: reader = csv.reader(f) # Dont upload header froom csv next(reader) for game in reader: division = game[0] date=game[1] home_team = game[2] away_team = game[3] home_goal = game[4] away_goal = game[5] print(home_goal) home_odd = game[23] draw_odd = game[24] away_odd = game[25] # let's skip the column captions # continue """Assign country based on division. to get divisions code … -
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)