Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Model inheritance with a dynamic form
i am pretty new to django and i am having issues atm with model inheritance combined with a dynamic form class ConstructionVehicle (models.Model): name = models.CharField(max_length=100, null=False, blank=False) class Meta: db_table="constructionvehicle " class Crane(ConstructionVehicle): consturcion_year = models.PositiveIntegerField(validators=[MaxValueValidator(9999), MinValueValidator(1900)]) class Meta: db_table="crane" class Excavator(ConstructionVehicle): weight = models.PositiveIntegerField() class Meta: db_table="excavator" So, for example, i have the datastructure above. Now i want to create a dynamic form, where i can select the typ of construction vehicle and it displays me the fields of the model. After that i should be able to save the model to the database. Is that possible? -
How to can I work with multiple select options and make these options selected to stay selected?
Form widget value not selected after saving data options using CheckboxSelectMultiple() widget forms.py class Client_ProcessForm(forms.Form): process = forms.ModelChoiceField(queryset= Process.objects.all(), widget=forms.CheckboxSelectMultiple) Views.py def Edit_Client(request, id): form = Client_ProcessForm(request.POST) edit_record = Client.objects.get(pk=id) obj = Client.objects.all() cp = Client_Process.objects.filter(client_id=edit_record) cp1 = cp.values_list('process') obj1 = {} for i in range(len(cp1)): ps = Process.objects.filter(id__in=cp1[i]) print(ps) obj1[cp1[i][0]] = list(ps) return redirect('/client_list/') return render(request, 'edit_client.html',{'edit_record': edit_record, 'form' : form, 'obj' : obj, 'cp' : obj1}) html <select name="process"> {% for entry in form %} <option value="{{ entry }}">{{ entry.process }}</option> {% endfor %} </select> -
Error 'Reverse for 'password_reset_confirm' not found.' In Django
So, I was trying to build a blog website in which the user can reset his password by sending an email to his email address, I was mostly using Django Build In functionality for that. I was trying to make the confirm URL path in which the user can reset his password but was getting an error even when I included the path for password reset confirm. Error: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. My urls.py for password-reset from django.conf.urls import url from django.contrib.auth import views as auth_view from django.urls import path app_name = "blog" urlpatterns = [ # for /blog/password-reset/ path('password-reset/', auth_view.PasswordResetView.as_view(template_name='blog/password_reset.html'), name="password_reset"), # for /blog/password-reset/done/ path('password-reset/done/', auth_view.PasswordResetDoneView.as_view(template_name='blog/password_reset_done.html'), name="password_reset_done"), # for /blog/password-reset/confirm/<uidb64>/token> path('password-reset-confirm/<uidb64>/<token>', auth_view.PasswordResetConfirmView.as_view(template_name='blog/password_reset_confirm.html'), name="password_reset_confirm"), ] Note: I'm not including all the urls cause it's kinda big My blog/password_reset_confirm.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block body %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Reset Password</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Reset Password</button> </div> </form> </div> {% endblock body %} I expect the output to be a connection error which by the way is what I want to … -
“Is there an R function for finding the index of an element in a vector?”
“I’m setting up a new server, and want to support UTF-8 fully in my web application. Where do I need to set the encoding/charsets?” “This is for a new Linux server, running MySQL 5, PHP 5 and Apache 2. In the past, I’ve tried on existing servers and always seem to end up having to fall back to ISO-8859-1.” Use code fences and syntax highlighting to format your code properly and provide context def function(foo): print(foo) “I expect the output of 5/2 to be 2.5, but the actual output is 2.” -
Can I Perform All Django Queries in a dicitionay?
Firstly I Have More than 1 Million Data In my database , while i want to perform aggregation or annotation or filter it took huge time , i have to show all data at a time,,, i use select_related() for foreign key but i want to optimize database hitting , like i want to fetch all data from database in first database hit and convert them into dictionary or list and perform another queries into dictionary or list without hitting database i hope it can optimize database hit Example : In Laravel I Fetch All data from database and convert it into Array while i have to perform queries into it i convert them into collect() and perform queries , and it dont hit the database . [a link ]:(https://laravel.com/docs/5.8/collections) ! I Can perform this in Django ??? -
How to update css/scss files with NGINX
I am running a Digital Ocean droplet with Gunicorn and NGINX. I am able to view my web pages but I am not able to update html/css/scss. I have added include /etc/nginx/mime.types; in /etc/nginx/nginx.conf as suggested in another post. Also tried python manage.py collectstatic and received the following: 0 static files copied to '/home/ubuntuadmin/pyapps/nomad/static', 177 unmodified sudo nano /etc/nginx/sites-available/nomad >>> server { listen 80; server_name 157.245.0.153; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntuadmin/pyapps/nomad; } location /media/ { root /home/ubuntuadmin/pyapps/nomad/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; include /etc/nginx/mime.types; } }``` -
The current path, home/, didn't match any of these
I have two apps on my project- one is accounts and home home app url - http://localhost:8000/home/ is rising an error that the current path, home/, didn't match any of these. I'm using django version 2.2.4 and i'm using regular expression on my home url pattern My home url from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name='home') ] My home view from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse('It worked !..') **My project url** urlpatterns = [ path(r'^admin/', admin.site.urls), url(r'^$', views.login_redirect, name='login_redirect'), # automatically takes to login page path(r'^account/', include(('accounts.urls','accounts'), namespace='accounts')), path(r'^home/', include(('home.urls','home'), namespace='home')), path('', include('django.contrib.auth.urls')), ] i'm expecting simple message on the browser that is 'It worked!..' -
Django form submission & CSRF (403 Forbidden)
Upon providing valid data and submitting a form, I get the following: Forbidden (CSRF cookie not set.): /membership/success/. I have a {% csrf_token %} in my template and my settings.py middleware is configured for CSRF. #urls.py from django.contrib import admin from django.urls import path, include from membership import views as ms_views membership_patterns = ([ path("", ms_views.RegistrationPage.as_view(), name="register"), path("success/", ms_views.SuccessPage.as_view(), name="success") ], 'membership') urlpatterns = [ path('admin/', admin.site.urls), path('membership/', include(membership_patterns, namespace="new_members")) ] # membership/views.py from django.shortcuts import render from django.template.loader import get_template from django.views import View from django.http import HttpResponse, HttpResponseRedirect from membership.forms import RegisterForm from django.urls import reverse # Create your views here. class RegistrationPage(View): def get(self, request): register_page = get_template('membership/signup.html') register_form = RegisterForm() return HttpResponse(register_page.render({'form' : register_form})) def post(self, request): submitted_form = RegisterForm(request.POST) if submitted_form.is_valid(): return HttpResponseRedirect(reverse('membership:success')) return HttpResponse(reverse('membership:register')) class SuccessPage(View): def get(self, request): return HttpResponse("Success") # signup.html {% extends 'index.html' %} {% block content %} <form action="{% url 'membership:success' %}" method='post'> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} Once the form is submitted and valid, I'm expecting a 302 to occur. Like I said though I get 403 forbidden. -
How to implement 'follow' functionality on a blog author
I have a blog app that works pretty well. However I want to expand its functionality to include an option for users to follow authors. I created a class FeedListView has a get_queryset function but i dont know how to use this to return the authors the logined in user follows. my FeedListView looks like this: class FeedListView(ListView): model = Post template_name = 'blog/feed_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 6 def get_queryset(self): queryset = Post.objects.filter(author__followers=user) return queryset # self.user = self.get_object() # return Post.objects.filter(author__followers=user) The model (User) like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False) def __str__(self): return f'{self.user.username} Profile' the url.py is: path('feed/', FeedListView.as_view(), name='feed_posts'), If i can get it to the state where when i navigate to the url the posts only by the followed users are displayed I would be overjoyed. But I need some guidance on how this query set works as im a bit lot here. -
Linode/Django Can't see site when I runserver at ip:8000
I had started a fresh linode running ubuntu 19.04 and the first time I used the directions at: https://www.rosehosting.com/blog/how-to-install-mezzanine-cms-on-ubuntu-18-04/ To install Mezzanine CMS it worked just fine, I could run the runserver command and see the django website. Eventually it started giving me a problem after trying 50 ways to deploy the site using apache and mod_wsgi. I gave up and rebuilt the server and then still couldn't see the new install at the IP when I ran run server. I figured maybe it was because I accidentally installed some things using "python" and others with "python3" so I rebuilt the server. This third time I followed the direction perfectly, the only difference is I didn't install a mysql server just kept the default SQLlite server and created a DB and Django Superuser. I have added my ip as a host in settings.py and local_settings.py I have already ran makemigrations and migrate I did check to see if maybe the IP had changed when I rebuilt, it hadn't My local environment on my laptop works fine, just not the linode Any suggestions on anything I'm missing? -
some advices on deploying Django app to product locally
I want to deploy (production not testing) Django app with PostgreSQL database for my company, however, for security reason I want the app to be on local network and not accessible through the internet. I need some recommendations and advices to achieve that on setup and tools. Suppose I know python3 manage.py runserver myip:8000 EDIT: I wanted to be accessible by different machine on the same network. -
Is it possible to set the enctype="multipart/form-data" for a form in the backend?
I'm working on Ticketing System using Django framework. I want to implement a functionality where tickets can be created via email so far the recipient email is tied to a user. I used mailgun to create a route which redirect the mail data to a URL. I've been able to handle the mail content successfully except the attachment and i think this because i'm not setting the enctype attribute which is mandatory when uploading a file. The form isn't validating. Is it possible to set the enctype="multipart/form-data" in the bankend? model.py from django.db import models from .utils import * from django.db.models.signals import pre_save class Ticket(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) subject = models.CharField(max_length=50, blank=False, null=False) message = models.TextField() task = models.ForeignKey(Task, on_delete=models.CASCADE, null=True, blank=True) status = models.CharField(max_length=50, choices=STATUS_CHOICES, default='open') request_time = models.DateTimeField(auto_now_add=True) response_time = models.DateTimeField(auto_now=True) priority = models.CharField(max_length=50, choices=PRIORITY_CHOICES, default='mid') is_active = models.BooleanField(_('active'), default=True) objects = GeneralManager() def __str__(self): return self.subject def get_absolute_url(self): return reverse('ticket_detail', kwargs={'pk': self.pk}) def req_ticket_create_update_receiver(sender, instance, *args, **kwargs): # reciever function for ticket model from_email = config('from_email') if Ticket.objects.filter(id=instance.id).exists(): if instance.status == 'close': subject = f'Ticket With ID {instance.id} Has Been Closed' message = f'Hello {instance.user.get_short_name()}, \nYour ticket with ID {instance.id} has been closed. We hope the … -
Django-taggit, tag slug is not linking to the correct ListView
I installed django-taggit and django-taggit-templatetags2 and included in all the models that I needed. On the app name blog with model Post the tags work perfect as the code bellow. '''blog/views.py''' def tutorialpage(request): tutorial_list = Post.objects.all() context = { 'tutorial_list': queryset, } return render(request, "tutorialpage.html", context) class TagMixin(object): def get_context_data(self, **kwargs): context = super(TagMixin, self).get_context_data(**kwargs) context['tags'] = Tag.objects.all() return context class TagIndexView(TagMixin, ListView): template_name = 'tutorialpage.html' model = Post context_object_name = 'tutorial_list' def get_queryset(self): return Post.objects.filter(tags__slug=self.kwargs.get('slug')) '''blog/urls.py''' path('tag/<slug:slug>/', views.TagIndexView.as_view(), name='tagged'), '''tutorialpage.html''' {% load taggit_templatetags2_tags %} {% for tutorial in tutorial_list %} <a href="/tutorialdetail/{{tutorial.slug}}">{{ tutorial.title }}</a> {% endfor %} {% get_taglist as tags for 'blog.Post' %} {% for tag in tags %} <a href="{% url 'tagged' tag.slug %}">{{ tag.name }}</a> {% endfor %} Now on a different app name articles with model ArticlePost. I applied the same idea and the tags display correct from the ArticlePost, but when I click on one of them it links to the blog Post ListView template and blank, and it has the correct slug, here is the code. '''articles/view.py''' def articlepost(request): article_list = ArticlePost.objects.all() context = { 'article_list': article_list, } return render(request, "articlepost.html", context) class TagMixin(object): def get_context_data(self, **kwargs): context = super(TagMixin, self).get_context_data(**kwargs) context['tags'] = … -
Django Listing Users with specific object in template
I want to display the list of users with some objects in 2 apps created. these are the models. first model: class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) indirizzo = models.CharField(max_length=50) citta = models.CharField(max_length=50) paese = models.CharField(max_length=50) ecap = models.CharField(max_length=4) descrizione = models.CharField(max_length=100, default='') image = models.ImageField(upload_to='profile_image', blank=True,null=True) second model: class Ore(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ore",null=True,) data = models.DateField(default=timezone.now) oret = models.CharField(max_length=3,) contrattiok = models.PositiveSmallIntegerField() contrattiko = models.PositiveSmallIntegerField(default=0,) nomecognome = models.CharField(max_length=100,blank=True) my view: def inizio(request): users = User.objects.all() return render (request, "base.html", {"users":users}) my template: {% for users in users %} <tbody> <tr> <td> <img src="{{ users.userprofile.image.url }}"class="thumbnail"> <h4 class="small font-weight-bold">{{users}}</h4> </td> <td><h4 class="small font-weight-bold">{{users.last_name}}</h4></td> <td class="text-center"> <h4 class="small font-weight-bold" class="btn btn-primary btn-circle">{{ users.ore.contrattiok }}</h4> <<<<<(does not work) </td> </tr> {% endfor %} -
How to fix double result date range in django queryset
I have a three model, that looks something like this: class BuildingCell(models.Model): building_name = models.CharField(max_length=100, blank=True, null=True) publish = models.DateField(auto_now=False) cell_name = models.CharField(max_length=100, blank=True, null=True) ... class InputCutSew(models.Model): user = models.ForeignKey(Profile, blank=True, null=True, on_delete=models.SET_NULL) cell = models.ForeignKey(BuildingCell, blank=True, null=True, on_delete=models.SET_NULL) publish = models.DateField(auto_now=False) ... class Absent(models.Model): cell = models.ForeignKey(BuildingCell, blank=True, null=True, on_delete=models.SET_NULL) building_name = models.CharField(max_length=12, blank=True, null=True) publish = models.DateField(auto_now=False) ... #my queryset q1 = BuildingCell.objects.filter(inputcutsew__publish__range=[get_publish_start, get_publish_end], absent__publish__range=[get_publish_start, get_publish_end], absent__building_name='f1', absent__bagian='CUT', inputtcutsew__user='1').exclude(inputcutsew__cell_name__isnull=True)/ .exclude(inputcutsew__cell_name__exact='')/ .order_by('inputcutsew__cell')/ .values('inputcutsew__cell', 'inputcutsew__model', 'absent__cell', 'inputcutsew__output') #my error result: 'inputcutsew__cell', 'inputcutsew__model', 'absent__cell', 'inputcutsew__output 1a aa 1a 122 1b as 1b 100 1a aa 1a 122 1b as 1b 100 I want to query to get some field from three model, but the result is still double. Could you please have your suggestions on this??, any help will be appreciated. -
How to pass payment gateway parmament to an api in json in django
How do i get Collect data with the parameters below and send as a json payload to an api in djnago . https://test.theteller.net/checkout/initiate merchant_id transaction_id desc amount redirect_url email API_Key apiuser -
Editing dynamic choice fields in Django
I have a standard Django blog with a Post model, only on the model I have added a ManyToManyField for approvers, the idea being that the backend passes the post to 2 or more approvers to confirm the content before it is published. class Post(models.Model): author = models.ForeignKey( get_user_model(), null=True, on_delete=models.SET_NULL) title = models.CharField(max_length=30) content = models.CharField(max_length=30) approvers = models.ManyToManyField(Approvers) I will probably learn towards something like django-fsm to create a finite state machine for the Post model to govern whether it is draft/in approval/published, but I would like to be able to change the approvers field so that the number and order of approvers (users) can be changed dynamically by the user. What is the best way to do this? I thought I could try and change the approvers field to a JSONField so that users can add / delete / change the order of approvers and then handle the interpretation in the frontend and write some function to interface with django-fsm, but this feels like it conflates things too much. Am I missing a simpler route? -
Using Value From One View in Another View Django
In View 1's form their is a field called 'reference'. I need to access whatever value is submitted in that field in View 2 and set a variable equal to it. Right now I am just getting an error "orders matching query does not exist". This is what I'm trying (I've commented the code in view2 to indicate where im getting the error). views.py def view1(request, pk): item = get_object_or_404(Manifests, pk=pk) if request.method == "POST": form = CreateManifestForm(request.POST, instance=item) if form.is_valid(): form.save() return redirect('view2') else: form = CreateManifestForm(instance=item) return render(request, 'edit_manifest_frombrowse.html', {'form': form}) def view2(request): form = CreateManifestForm(request.POST) if request.method == "POST": if form.is_valid(): form.save() ... reference_id = request.POST.get('reference') #this is how Im trying to get reference from the previos view data = Manifests.objects.all().filter(reference__reference=reference_id) form = CreateManifestForm(initial={ 'reference': Orders.objects.get(reference=reference_id), #this is where im getting "does not exist" }) total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases')) context = { 'reference_id': reference_id, 'form': form, 'data': data, 'total_cases': total_cases['cases__sum'], } return render(request, 'manifest_readonly.html', context) forms.py class CreateManifestForm(forms.ModelForm): class Meta: model = Manifests fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB') I just want to be able to use whatever value is submitted in the 'reference' field in view1 in view2 and assign it equal to reference_id -
Django form vs template
My project can register user and set permission in custom page. not in admin page I used custom permission. Implementing with form is best way or Implement with template is best way? I want to know what is the best way to implement this system. If I should use form. How implement this permission list easily? template.html <h2>Register</h2> <form method="post" action=""> {% csrf_token %} {{ form.as_p }} <ul> {% for permission in permissions %} <h1>{{ permission.name }}</h1> {% for pr in permission.list %} <label for="{{ pr.0 }}"> {{ pr.1 }}</label> <input id="{{ pr.0 }}" name="{{ pr.0 }}" type="checkbox"/> {% endfor %} {% endfor %} </ul> <input type="submit" value="submit" /> </form> forms.py class UserPermissoinForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'password'] view.py class PermissionTestView(View): form_class = UserPermissoinForm template_name = 'permission_test.html' def get(self, request): modelList = [Company, AccountManagement,] permissions = [] for model in modelList: tmp = {} tmp["name"] = model._meta.verbose_name.title() tmp["list"] = model._meta.permissions permissions.append(tmp) form = UserPermissoinForm() return render(request, 'permission_test.html', {'form': form, "permissions": permissions}) def post(self, request): form = UserPermissoinForm(request.POST) if form.is_valid(): codenames = (x for x in request.POST if 'can_' in x) new_user = User.objects.create_user(**form.cleaned_data) for codename in codenames: permission = Permission.objects.get(codename=codename) new_user.user_permissions.add(permission) return render(request, 'permission_test.html', {}) … -
Djanogo - Python Social Auth for social media login
I am trying to use python-social-auth to have users login with their facebook or google accounts. After the user gets the google login page and logs in to their account, I have trouble redirecting back to my site. It says This site can’t be reached 127.0.0.1 took too long to respond. I followed the documentation: https://python-social-auth.readthedocs.io/en/latest/configuration/django.html The following is in settings.py: SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "xxxxxxxxxxxxxxxxx" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "xxxxxxxxxxxxxxxxx" INSTALLED_APPS = [ ... ... 'social_django', ... ] MIDDLEWARE = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ { ... 'context_processors': [ ... 'social_django.context_processors.backends', # <-- 'social_django.context_processors.login_redirect', # <-- ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.twitter.TwitterOAuth', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) In the google OAuth client, under Authorized redirect URIs, I have: https://127.0.0.1:8000/oauth/complete/google-oauth2/ -
Update onChange event and fire onChange event javascript
I have a select element with several options like this: <select onChange="foo(this)"> <option value="ok" selected>..</option> .... <option value="no">..</option> I'm working with django (don't know if that matters honestly..) and in my onChange event of the select tag I should put window.location.href=this.value but it's not what I want since i need to make some changes to this.value.. My idea was to create a foo function passing the select item and then modify the onChange event and fire it afterwards. I searched for some help and I found several options.. 1) How can I trigger an onchange event manually? 2) Trigger "onchange" event and other examples as well that I don't remember but I use down in the example. None of them are working for me. This is what I tried so far in my foo function: <script> function foo(obj) { if (condition) { obj.onChange = "window.location.href="+ obj.value; //obj.onChange(); //1 option I found on the net was to call onChange this way } else { obj.onChange = "window.location.href="+ obj.value.replace('/A/', '/R/'); // this is the update I need to apply based on the condition //obj.fireEvent("onChange"); // another solution // another solution if ("createEvent" in document) { var evt = document.createEvent("HTMLEvents"); evt.initEvent("change", false, true); … -
How to return a id of a external APi in Django urls?
i need one solution to my little "problem" , actually i have a view to list all my events and I got all IDS collected by a 'for' I need to pass to my URLs to handle all the details of each. I'm beginner in Python , if all of you can help me i'll be grateful. I've tried to create a function to set the id, i'm beginner in python Global to Request url = 'https://api.sympla.com.br/public/v3/events' h = SYMPLA_TOKEN r = requests.get(url, headers=h) json_data = r.json() Here's my view: def detalhar_evento(request): template_name = 'evento_detalhe.html' evento_data = dict() ids = [ids['id'] for ids in json_data['data']] for id in ids: endpoint = url+"/%s" % id response = requests.get(endpoint, headers=h, params=params) detalhes = response.json() #id event detail evento = { 'nome': detalhes['data']['name'], 'detalhe': detalhes['data']['detail'], 'criado': detalhes['data']['start_date'], 'final': detalhes['data']['end_date'], 'endereco_nome': detalhes['data']['address']['name'], 'endereco': detalhes['data']['address']['name'], 'num': detalhes['data']['address']['address_num'], 'comple': detalhes['data']['address']['address_alt'], 'cidade': detalhes['data']['address']['city'], 'estado': detalhes['data']['address']['state'], 'cep': detalhes['data']['address']['zip_code'], 'pais': detalhes['data']['address']['country'], 'propietario': detalhes['data']['host']['name'], 'p_descricao': detalhes['data']['host']['description'], 'categoria': detalhes['data']['category_prim']['name'], 'categoria2': detalhes['data']['category_sec']['name'], } context = { 'evento': evento } return render(request, template_name, context) Url path('detalhes/', views.detalhar_evento, name='detalhes'), Ps. I need to pass the external api id belong the view to url like : path('detalhes/int:id', views.detalhar_evento, name='detalhes'), url_example : 'https://api.sympla.com.br/public/v3/events/12345' Actual Error : -
Django 2.2: MySQL full-text search support – where did it go, and how to replace it?
It seems that the __search capability (fulltext search ...) was removed after Django 1.9. Well, I need to be able to do MySQL full-text searches and I really don't want to have to build SQL strings in order to do it. "This facility must still be around here somewhere ..." But, where? (My question is specific to Django 2.2 or later.) -
Displaying fields other than pk in a Django Form with a ModelChoiceField
I am building a website where users can upload files and can attach uploads to projects that they created beforehand. The upload is done with a django form where the user can specify the title, comments, etc... There is also a dropdown list where the user can choose from the existing projects that he created (list of projects is dependent on user) As of now the dropdown only shows the (autogenerated) project id which is the pk of the model Project I want the dropdown to show the names of the projects and not the project ID which is not very meaningful for the user. I have already tried to_field_name='name' but that didn't work I have also tried Project.objects.filter(user=user).values_list('name') or Project.objects.filter(user=user).values('name') the last two options show the project name in {'projectname} but when I select them and submit the form the error "Select a valid choice. That choice is not one of the available choices." This is my code: models.py class Upload(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) upload_date = models.DateTimeField(default=timezone.now) comments = models.CharField(max_length=10000, null=True) title = models.CharField(max_length=10000, null=True) project = models.CharField(max_length=99, default='--None--') forms.py class UploadForm(ModelForm): project = ModelChoiceField(label='Select Project', queryset=Project.objects.all(), to_field_name='name', empty_label='--Select Project--') def __init__(self, *args, **kwargs): user = kwargs.pop('user', … -
I want to read excel file and save excel file data into models in django-rest-framework using pandas(management parsing scripts)
"I want to read excel file and save the excel file data into models in django-rest-framework using pandas(management parser script) with json response".