Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django2.0,python-version3.6,django-simpl-captcha-5.6,Why is my verification code not appearing?
I tried to practice a html page for user login.I browse the document and follow the steps to try django-simple-captcha to verify my user login.finally... enter image description here I have already makemigrations, migrate and add captcha to the INSTALL_APPS,and Defined the Form , and Defined view function 'views.py' from django.shortcuts import render from django.views.generic.base import View from .froms import UserLoginForm # Create your views here. class LoginView(View): def get(self, request): user_login_form = UserLoginForm() return render(request, 'login.html', {'user_login_form':user_login_form}) 'forms.py' from django import forms from captcha.fields import CaptchaField class UserLoginForm(forms.Form): username = forms.CharField(required=True) password = forms.CharField(required=True, min_length=5) captcha = CaptchaField() <html> <head> <title>login</title> </head> <body> <form action="#" method="post"> <p> Username:<input type="text" name="username" placeholder="Please input you email"> </p> <p> Password:<input type="password" name="password"> </p> <p> <label>code:</label> {{ user_login_form.captcha }} </p> <input type="submit" value="submit"> </form> </body> </html> -
Failed to upload file with the TypeError : expected str, bytes or os.PathLike object, not list
I have a user_post.html page to let user upload their file(gif, mp4) or image, but when i click confirm i will getting error saying - expected str, bytes or os.PathLike object, not listexpected str. i have a media folder in my main project folder, inside the media i have another folder call user_post, and i also join them in the setting.py already: MEDIA_URL = 'media' MEDIA_ROOT = [os.path.join(BASE_DIR,'media')] did i miss anything or syntax error? Thank you! TraceBack: C:\Users\GIAM ZENG KEAT\Anaconda3\lib\ntpath.py in abspath path = os.fspath(path) ... ▶ Local vars models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import FileExtensionValidator # Create your models here. class UserPost(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) cinemagraph = models.FileField(upload_to="user_post/", validators=[FileExtensionValidator(allowed_extensions=['gif','png','jpg'])]) c_description = models.CharField(max_length=500,default='') date_time = models.DateTimeField(auto_now=True) def __str__(self): # Built-in attribute of django.contrib.auth.models.User ! return self.user.username views.py def Post(request): if request.method == 'POST': form_post = UserPostForm(request.POST, request.FILES) if form_post.is_valid(): posted = form_post.save(commit=False) posted.user = request.user posted.save() return reverse('home') else: return HttpResponse('Posting failed') else: form_post = UserPostForm() return render(request,'post/user_post.html',{'form_post':form_post}) forms.py from django import forms from django.forms import ModelForm from post.models import UserPost class UserPostForm(forms.ModelForm): class Meta(): model = UserPost fields= ('cinemagraph','c_description') user_post.html {% extends 'base.html'%} {% load bootstrap3 %} {% load … -
Cannot import http.urlsafe_base64
I use Django Nonrel in my project and it was running normally until today morning. The import from django.utils.http import urlsafe_base64_encode gives the following error: Traceback (most recent call last): File "/home/paulozullu/.virtualenvs/wopik/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 101, in get_response resolver_match = resolver.resolve(request.path_info) File "/home/paulozullu/.virtualenvs/wopik/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 340, in resolve sub_match = pattern.resolve(new_path) File "/home/paulozullu/.virtualenvs/wopik/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 224, in resolve return ResolverMatch(self.callback, args, kwargs, self.name) File "/home/paulozullu/.virtualenvs/wopik/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 231, in callback self._callback = get_callable(self._callback_str) File "/home/paulozullu/.virtualenvs/wopik/local/lib/python2.7/site-packages/django/utils/functional.py", line 31, in wrapper result = func(*args) File "/home/paulozullu/.virtualenvs/wopik/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 98, in get_callable mod = import_module(mod_name) File "/home/paulozullu/.virtualenvs/wopik/local/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/home/paulozullu/dev/workspaces/wopik/pages/views.py", line 11, in <module> from accounts.views import saveExternalUserGraph File "/home/paulozullu/dev/workspaces/wopik/accounts/views.py", line 14, in <module> from accounts.forms import FormChangePassword, FormEditUser, FormUser,\ File "/home/paulozullu/dev/workspaces/wopik/accounts/forms.py", line 11, in <module> from django.utils.http import urlsafe_base64_encode ImportError: cannot import name urlsafe_base64_encode Any idea? -
How to retrieve the data using datefield using django?
I need to retrieve the data from database using Django Date-field. Tried retrieving the data using Datefield. I'm using Django 2.0, Bootstrap 4, PostgreSQL. #forms.py from django import forms class StatusReportForm(forms.Form): created_date=forms.DateField(widget=forms.TextInput(attrs= { 'class':'datepicker' })) #views.py from django.shortcuts import render, get_object_or_404 # Create your views here. from django.views.generic import DetailView from .models import Statusreport from .forms import StatusReportForm def statusreport(request): form = StatusReportForm() context = { form: form } return render(request, "statusreport.html", context) class StatusReportDetailView(DetailView): model = Statusreport template_name = 'statusreport-detail.html' def get_object(self): instance = get_object_or_404(Statusreport, slug=self.kwargs['slug']) return instance #models.py class Statusreport(models.Model): created_date= models.DateField() taskname = models.CharField(max_length=200) slug = models.SlugField(null=True, blank=True) def __str__(self): return self.taskname def get_absolute_url(self): return reverse('statusreport:statusreport-detail', kwargs={'slug': self.slug}) def pre_save_statusreport_receiver(instance, *args, **kwargs): if not instance.slug: instance.slug = instance.created_date pre_save.connect(pre_save_statusreport_receiver, sender= Statusreport) #statusreport.html <main class="container"> <form> <div class="row" style="padding-top: 100px"> <div class="col"> <label class = 'control-label' for="date">Select Date: </label> <input data-date-format="dd/mm/yyyy" id="datepicker"> </br> </br> <a href="#" class="btn btn-info btn-md active" role="button" aria-pressed="true">Get Reports</a> </div> </div> </form> </main> <script type="text/javascript"> $('#datepicker').datepicker({ weekStart: 1, daysOfWeekHighlighted: "6,0", autoclose: true, todayHighlight: true, }); $('#datepicker').datepicker("setDate", new Date()); </script> Note: I need it to work like on-clicking "Get reports" button from there it needs to move to http://localhost:8000/statusreport/{{created_date}}/ -
How to filter out duplicates and increment in a Google table-chart
I want to loop through a list of objects and store that result in a Google-chart table. But before I draw the table, I want to go through the list and see if there are any duplicates. If there are any duplicate I want to remove the it, but want to increment the one that isn't removed. function drawTable() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Teamname'); data.addColumn('number', 'Number of resources'); var number = 1; {% for k, v in teammember %} {% for object in object_list %} data.addRows([['{{ object.team.name }}', number]]); {% endfor %} {% endfor %} var table = new google.visualization.Table(document.getElementById('table-div')); table.draw(data, {showRowNumber: true, width: '100%', height: '100%'}); } As you can see here I have one column for the name of a team and one should contain the number of members associated to that team. So in my for-loop I find all the teams, but how should I build the rest of the code for finding the duplicates, increment, and remove the duplicate. So a example could look like: Name - Team-members Junior Bobcat 3 Team Bobcat 4 Junior Coffe 4 -
django index out of range
Code improvement problems: Since 2 weeks I am after improving the below code and I was able to write the below code but I still have problems and not working as intented. There are 2 main problems I do like this ( j_list = str(hide[1]) ) I want to set a declaration instead I am getting it's value 1 which is not solving my problem. Index out of range error at context[j_list[i]] = j_list[i] context = { 'instance': project, 'user': user, } hide = [0,1] for i in range(10): j_list = "hide" + str(i) fp_list ="fp_list_" + str(i) j_list = str(hide[1]) context[j_list[i]] = j_list[i] messages.add_message(request, messages.INFO, j_list) messages.add_message(request, messages.INFO, fp_list) try: fp_list[i] = FP.objects.filter(id__in=group[i][1]) context[fp_list[i]] = fp_list[i] j_list[i] = hide[0] except IndexError: fp_list[i] == "null" return render(request, 'projects_detail.html', context) Old working code but it's too ugly and I am trying to improve myself as per above code: hide0=1 hide1=1 hide2=1 hide3=1 hide4=1 hide5=1 hide6=1 hide7=1 hide8=1 hide9=1 try: fp_list_0 = FP.objects.filter(id__in=group[0][1]) hide0 = 0 except IndexError: fp_list_0 = "null" try: fp_list_1 = FP.objects.filter(id__in=group[1][1]) hide1 = 0 except IndexError: fp_list_1 = "null" try: fp_list_2 = FP.objects.filter(id__in=group[2][1]) hide2 = 0 except IndexError: fp_list_2 = "null" try: fp_list_3 = FP.objects.filter(id__in=group[3][1]) hide3 = 0 … -
Social login flow with Django backend and ionic frontend
I am trying to integrate social login with my ionic app, which is consuming data from a DRF server. The idea is that an user can login through fb, do some magic, the data will be sent back to the django server, and next time they log in they can retrieve their personal data again. So far I'm using native Cordova Fb plugin on ionic and I have managed to successfully log in with it. The problem now is I'm lost on what to do in the next step or the flow of the entire process. How do I register an user from Facebook to my django server so that the next time the user login I can retrieve the data from that respective user correctly? Let's say after I login with FB, I got an access token, do I pass that token back to django to register the new user and if so what tool should I use? For authentication I plan to have Django passing JWT back to the ionic app, but the part in the middle is where I don't know where to start on. -
Django - How to use update on an annotated queryset instead of using a for loop?
I have to build a field from an annotation, the field is a score which is equal to the division of two other annotations which are based on different Querysets Expressions. annotated_queryset = Influencer.objects.annotate( score_sum=Sum('submission__answer__decisions__score'), submission_count=Count('submission', filter=Q( submission__status__in=Submission.ANSWERED_STATUS ) ) ).annotate(rate=F('score_sum') / F('submission_count')) This snippet shows how i get my annotation. Now i'd love to be able to do the following : annotated_queryset.update(acceptation_rate=F('rate')) But I get a FieldError: Aggregate functions are not allowed in this query My only solutions is to use the ugly and expensive for loop : for each in annotated_queryset: each.acceptation_rate = each.rate each.save() My questions are : Why can't I use the annotate + update form ? Is there any better way than the for loop to do this ? What would it be ? -
Django: Annotate with list/array (for graph)
I have three models, Report, Article, and ArticleInReport - which is an intermediary table between Article and Report, which holds extra info for each appearance of a certain Article in a Report (specfically, the fields are ios_views and android_views). I've successfully annotate each article with data from the last ArticleInReport occurrence: reports_in_time_range = Report.objects.filter(created_date__range=[starting_range, right_now]) xhours_ago_reports = Report.objects.filter(created_date__range=[xhours,right_now]) graph_x_vals = xhours_ago_reports.values_list('created_date', flat=True) last_report = Report.objects.last() articles= Article.objects.filter(articleinreport__report__in=reports_in_time_range)\ .distinct().\ annotate( total_views=Case( When(articleinreport__report=last_report, then=(F("articleinreport__ios_views") + F("articleinreport__android_views"))) , default=0, output_field=IntegerField() ) ) But I also need to draw a graph for each article with the X values being all reports in a certain timeframe, and the Y values being the corresponding ios_views and android_views for that report. How can I do that? -
Heroku - deploy error - STATIC_ROOT not set
I have recently complete a webapp using django and react and now, I am trying to deploy it. I have used the "Production setup" topic in this article to build my react project. Then, I am now following this article to deploy my app now. (I am not really sure if this is compatible with my project or not) After deploying, I got this error: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. Traceback remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 15, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect remote: handler(path, prefixed_path, storage) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 344, in copy_file remote: if not self.delete_file(path, prefixed_path, source_storage): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 250, in delete_file remote: if self.storage.exists(prefixed_path): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 308, in exists remote: return os.path.exists(self.path(name)) remote: … -
Django static files giving 404 error after production in Microsoft Azure
My settings.py consist the following code: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = 'D:/home/site/wwwroot/static' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) After pushing my code into github i deployed the github code in Azure and then i run "manage.py collectstatic --noinput" in Web Console of my Azure resource and when i run my project url the sttatic files still give 404 Error not found, even the admin css gives the same error though the static folder has admin css. Can someone please help me figure out what might be my mistake. -
getting "the field name is required" after uploading the image
after uploading the image to a form when i submit the form it still shows "the field is required" error in models.py: class Members(models.Model): image=models.ImageField(upload_to="images/",default='') in forms.py: class CreateOne(forms.Form): image=forms.ImageField(required=True) in create.html: <form class="form-inline" action="create" method="POST" enctype="multipart/form-data" novalidate>[enter image description here][1] -
Django ModelForm ManyToManyField,html remove ManyToManyField
I want to make a generic page But I want a generic approach because I don't know what fields other models will have. There are other ways to remove ManyToManyField or ForeignKey?? but I do not want permissions fields i know use from django import forms from models import Role class PostForm(forms.ModelForm): class Meta: model=Role exclude=['permission'] models.py class Role(models.Model): """ 权限角色表 """ name = models.CharField(max_length=20, verbose_name='角色名') description = models.CharField(max_length=255, verbose_name='描述', null=True, blank=True) permissions = models.ManyToManyField(verbose_name='拥有权限', to='Permission',null=True, blank=True) class Meta: db_table = 'roles' verbose_name = "权限角色表" verbose_name_plural = "权限角色表" def __str__(self): return self.name views.py class ModelAdmin(): def get_modelform_class(self): ModelFormDemo = self.page_model_form if not self.page_model_form: from django.forms import ModelForm class ModelFormDemo(ModelForm): class Meta: model = self.model fields = "__all__" # 等同于 # _meta = type('Meta', (object,), {'model': self.model_class, "fields": "__all__"}) # model_form_cls = type('DynamicModelForm', (ModelForm,), {'Meta': _meta}) return ModelFormDemo def add_view(self, request): ModelFormDemo = self.get_modelform_class() form = ModelFormDemo() if request.method == "POST": print(request.POST) form = ModelFormDemo(request.POST) if form.is_valid(): obj = form.save() return redirect(self.changelist_view) return render(request, "xadmin/add_view.html", locals()) form.html {% csrf_token %} {% for field in form %} <div class="layui-form-item"> <label for="name" class="layui-form-label"> <span class="x-red"></span>{{ field.label }} </label> <div class="layui-input-inline"> <input type="text" id="name" name="{{ field.name }}" {% if field.field.required %}required="" lay-verify="required"{% endif %} … -
How i can use antiword on heroku like in command line
I find this buildpack antiword on heroku https://github.com/bricel/heroku-buildpack-antiword. I use django(python on my heroku main app). How i can use this buildpack with django and use it in my django scripts? -
django context processing with condition
I have django context where I want to put values conditionally.How can I do that ? I tried as per below, but not working as needed: def get(self, request, *args, **kwargs): context = Context() context['p_list1'] = p_list1 context['p_list2'] = p_list2 context['p_list3'] = p_list3 Here is the context part where I want to put p_list1 values after the "," . When I write inside the context part it's working but I can't do that because I will put there or not depending on calculation i will do prior. context = { 'instance': fp0, 'user': user, } return render(request, 'ts_detail.html', context) -
"No ReverseMatch" while supplying kwargs with arguments that match view in urls.py
I have read through some of the answers already on stackoverflow regarding this, but I cannot see any errors I'm making in the code below. From my point of view there should not be any reason for it not to work, also I checked the documentation that says that this syntax should be the one to use. I am however still getting a "No ReverseMatch" so something is wrong. I have the following urls.py entry: url(r'^portfolio/profile/(?P<profile_id>[0-9]+)$', views.portfolio_view_profile, name='view_investment_profile') Then I have the following class based view: class PortfolioDividendEdit(PortfolioEditBase): model = Dividend form_class = DividendForm template_name = 'plan/portfolio/edit/dividend_edit.html' def form_valid(self, form): if "delete" in self.request.POST: div_obj = Dividend.objects.get(id=self.kwargs['dividend_id']) profile_id = div_obj.profile_id # obj.delete() return HttpResponseRedirect(reverse('plan:view_investment_profile'), kwargs={'profile_id': profile_id}) def get_context_data(self, **kwargs): context = super(PortfolioEditBase, self).get_context_data(**kwargs) dividend_obj = Dividend.objects.get(id=self.kwargs['dividend_id']) profile = Profile.objects.get(id=dividend_obj.profile_id) context['post_req'] = self.post_req context['profile'] = profile context['dividend_id'] = self.kwargs['dividend_id'] return context def get_object(self, queryset=None): obj = Dividend.objects.get(id=self.kwargs['dividend_id']) return obj def get_success_url(self): dividend_obj = Dividend.objects.get(id=self.kwargs['dividend_id']) profile_id = dividend_obj.profile_id return reverse(self.url_name, args=[profile_id]) I was originally going to reverse it to a DeleteView, but then its only like four lines of code to delete the object so why then bother with creating an additional view for that. That being said I had created the … -
Django - Creating or extending the default QuerySet filters
I'm currently building a city search lookup programme using Django. Of course Django includes some out-the-box field lookups such as 'icontains', 'in', 'gte', etc; however for my specific use-case, I'm looking for something more advanced than icontains, that would yield more accurate matches between a query string and the corresponding results that the database would retrieve (see example below!). I figured that it might be best to 'create' my own lookup or extend/implement one of the existing, more advanced lookups like finding the standard deviation of the city title from the query (in Django Docs here) Example of how this would function: Database might include cities that have similar names such as 'Bangkok' and 'Bangalore' User searches for 'bang' Result would be biased towards city matching Bangkok since a majority (>50%) of the letters in Bangkok (case-insensitively) match the string 'bang', but Bangalore would not be returned since the string doesn't really make up much of the city name The StdDev aggregation function also looks useful here however I'm not sure how this might work for words instead of numbers. Note: I've purposely made this scenario quite generic just so that other people who stumble across any of the answers … -
is there a way to only get one of the duplicates in a queryste? django
I am not trying to get all duplicate querysets and I am not trying to compare two queryset results and see of the two comparison are the same. Somehow, I have no idea how this happened yet but sometimes there are records being saved twice and some not. So when I do querying my result would sometimes have duplicates. For example, I am just doing Model.objects.filter(user='myname') I would get maybe 50 querysets back, all of them should be different. But somehow maybe id 11 and 12 have the exact same values then 23 and 24 has the same values and the others are totally fine. So actually within those 50 querysets, there are 2 duplicates which means I should only have 48 querysets instead of 50 to be accurrate. Is there a way to check the queryset and return only one of the duplicates with other querysets if the values are totally the same? -
Edit and Limit choices of a ForeignKey Field in a Form
I am trying to control the choices of a ForeignKey in a form. I want to be able to control the displayed name in the form and which options are available. I managed to limit the choices but I can't figure out how to change the displayed name: The Model: from django.db import models # Create your models here. class Group(models.Model): created_by = models.ForeignKey('auth.User', on_delete=models.PROTECT, related_name='group_author') last_edited_by = models.ForeignKey('auth.User', on_delete=models.PROTECT, related_name='group_editor') name_de = models.CharField(max_length = 100, unique=True) name_en = models.CharField(max_length = 100, unique=True) privacy = models.ForeignKey('auth.Group', on_delete=models.PROTECT, blank=True, null=True) def __str__(self): return str(self.name_de) + '/' + (self.name_en) The Form: from django import forms from .models import * class GroupForm(forms.ModelForm): class Meta: model = Group exclude = ('created_by', 'last_edited_by',) The View: from django.contrib.auth.models import Group as DjangoGroup from django.db.models import Q from django.shortcuts import render from .forms import * from .models import * def category_new(request): context = {} if request.method == 'POST': form = GroupForm(request.POST) if form.is_valid(): group = form.save(commit=False) group.created_by = request.user group.last_edited_by = request.user group.save() return redirect('index') else: context['form'] = form else: form = GroupForm() privacyOptions = DjangoGroup.objects.filter(Q(name='Privacy - Private') | Q(name='Privacy - Submods')) form.fields['privacy'].queryset = privacyOptions context['form'] = form return render(request, 'new_category.html', context) Now this works so that … -
Read Description list in selenium python
How can I read text of <dd> tag which has <dt> like Commodity code. `<dl class="dl"> <dt>Trading Screen Product Name</dt> <dd>Biodiesel Futures (balmo)</dd> <dt>Trading Screen Hub Name</dt> <dd>Soybean Oil Pen 1st Line</dd> <dt>Commodity Code</dt> <dd><div>S25-S2Z</div></dd> <dt>Contract Size</dt> <dd><div>100 metric tonnes (220,462 pounds)</div></dd> </dl>` from selenium import webdriver driver = webdriver.Chrome("C:\\Python36-32\\selenium\\webdriver\\chromedriver.exe") link_list = ["http://www.theice.com/products/31500922","http://www.theice.com/products/243"] driver.maximize_window() for link in link_list: driver.get(link) desc_list = driver.find_elements_by_class_name("dl") -
Django session error: get() got an unexpected keyword argument 'session_key'
I am new to python an django. I have an app and want to use session in login and other page, I have add "django.contrib.sessions" in my INSTALLED_APPS and "django.contrib.sessions.middleware.SessionMiddleware" in my MIDDLEWARE_CLASSES. after checking username and password, I create session like this: if not request.session.session_key: request.session.create() request.session['session_data']=username request.session.modified = True No error in Login page, but when I go to other page which has other def in my view, I get this erro: get() got an unexpected keyword argument 'session_key' and this: 'SessionStore' object has no attribute '_session_cache' can any one help me? I use django 1.9.7 and python 3.6.5 -
How can I style django forms with bootstrap CSS?
I've written a form class in django, and while trying to output it, found that it is not beautiful to look at. class AddAppointmentForm(forms.Form): docchoices = [] for doc in doctor.objects.all(): docst = [doc.docid, doc.name] docchoices.append(docst) # CHOICES = [('select1', 'select 1'), # ('select2', 'select 2')] name = forms.CharField(label='Name', max_length=100) gender = forms.ChoiceField( required=True, widget=forms.RadioSelect, choices=[('male', 'Male'), ('female', 'Female')] ) age = forms.IntegerField(max_value=100,min_value=1, required=True) phone = forms.CharField(label='Phone', max_length=14, required=True) email = forms.CharField(label='Email', max_length=25, required=False) address = forms.CharField(label='Address', max_length=60, required=False) city = forms.CharField(label='City', max_length=20, required=False) doctors = forms.ChoiceField( required=True, widget=forms.Select, choices=docchoices, ) {# Load the tag library #} {% extends "appointments/base.html" %} {% block title %}Create appointment{% endblock %} {% block content %} <div class="container"> <form class="needs-validation" novalidate="" action="/appointments/appointmentcreated" method="post"> {% csrf_token %} <div class="row"> <div class="col-md-12 mb-6"> <label for="Name">Name</label> {{ form.name }} </div> </div> <div class="row py-2 "> <div class="input-group col-md-6 mb-3"> <span class="input-group-addon">Age</span> {{ form.age }} </div> <div class="input-group col-md-6 mb-3"> <span class="input-group-addon">Gender</span> {{ form.gender }} </div> </div> <div class="row py-2 "> <div class="mb-3"> <label for="email">Phone <span class="text-muted">(Required)</span> </label> {{ form.phone }} </div> </div> <div class="row py-2 "> <div class="mb-3"> <label for="email">Email <span class="text-muted">(Optional)</span> </label> {{ form.email }} </div> </div> <div class="mb-3"> <label for="address">Address</label> {{ form.address }} </div> <div … -
Django reverse match error for keyword arguments
I am a newbie in python and I' training to make an app in Django to keep track of my clients problems in a personal training center. I'm stuck in resolving a reverse match error for keyword arguments that is not passed. Honestly I am trying to understand how django manage this keyword arguments with no success. The error that django throws me is: NoReverseMatch at /persone/1/post Reverse for 'cliente_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['persone\\/(?P<pk>[0-9]+)\\/$'] Request Method: GET Request URL: http://localhost:8000/persone/1/post Django Version: 2.0.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'cliente_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['persone\\/(?P<pk>[0-9]+)\\/$'] Exception Location: C:\Users\perso\Envs\djangodev\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 636 Python Executable: C:\Users\perso\Envs\djangodev\Scripts\python.exe Python Version: 3.6.4 Python Path: ['C:\\Users\\perso\\Dropbox\\Django\\Frame\\filo_project', 'C:\\Users\\perso\\Envs\\djangodev\\Scripts\\python36.zip', 'C:\\Users\\perso\\Envs\\djangodev\\DLLs', 'C:\\Users\\perso\\Envs\\djangodev\\lib', 'C:\\Users\\perso\\Envs\\djangodev\\Scripts', 'c:\\users\\perso\\appdata\\local\\programs\\python\\python36-32\\Lib', 'c:\\users\\perso\\appdata\\local\\programs\\python\\python36-32\\DLLs', 'C:\\Users\\perso\\Envs\\djangodev', 'C:\\Users\\perso\\Envs\\djangodev\\lib\\site-packages'] Server time: Mar, 31 Lug 2018 11:58:32 +0200 My views.py: import json from django.http import HttpResponse from django.shortcuts import get_object_or_404, redirect, render from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.edit import UpdateView, CreateView, DeleteView, FormView #Qui importo la classe per essere sicuro che se l'user non è loggato lo deve far loggare from django.contrib.auth.decorators import login_required #Ricordarsi di importare anche i … -
Django nginx+uwsgi *1 connect() to unix:/run/uwsgi/firstsitecd.sock failed (111: Connection refused) while connecting to upstream
I'm trying to deploy a Django application on Ubuntu 16.4. I referred a document to deploy my application and here this is the URL which I have followed server-django-nginx-with-uwsgi. Everything went good until I faced this issued. *1 connect() to unix:/run/uwsgi/firstsitecd.sock failed (111: Connection refused) while connecting to upstream My socket file location /run/uwsgi/firstsitecd permission provided for the socket file f: /run/uwsgi/firstsitecd.sock drwxr-xr-x root root / drwxr-xr-x root root run drwxr-xr-x iradmin www-data uwsgi srwxrwxrwx root root firstsitecd.sock /etc/uwsgi/sites/firstsitecd.ini [uwsgi] project = firstsitecd uid = ****** base = /home/%(uid) chdir = %(base)/%(project) home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = 5 socket = /run/uwsgi/%(project).sock chown-socket = %(uid):www-data chmod-socket = 660 vacuum = true In .ini I have tried with chmod-socket = 660 & chmod-socket = 666 but nothing helps me. /etc/nginx/site-available/firsitecd server { listen 92; server_name my_ubuntu_ip_address; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/******/firstsitecd; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/firstsitecd.sock; } } I tired with plethora of suggestion but nothing helps. Thanks -
Django HttpResponseRedirect doesn't work in form_valid
I have a custom button in an admin changelist template that opens a jQuery dialog containing a form inside an iframe. After submission, the dialog closes and I want to redirect to the same admin changelist page. I have something like this: class UploadSeqDataQcView(CreateView): template_name = 'fantoddcc/frmUploadSeqDataQc.html' form_class = UploadSeqDataQcForm success_url = reverse_lazy('admin:myapp_seqdata_changelist' # ... def form_valid(self, form): # A 'success' message must appear after submission is processed successfully: messages.add_message(self.request, messages.INFO, 'The QC parameters were successfully imported.') return HttpResponseRedirect(self.get_success_url()) The problem is that the HttResponseRedirect seems to do nothing. After submission, I cannot see the successfulmessage. However, if I press 'F5' to refresh the page on the browser the message appears. I would appreciate any hint.