Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to call javascript function using widgets in django form
Hi i want to call js function when a field in form is clicked or typed in I have used this code: class ProviderSugForm(forms.ModelForm): class Meta: model = ProviderSug fields = ['due_date', 'price', 'description', 'discount'] widgets = { 'due_date': forms.DateInput(attrs={'class': 'datepicker'}), 'price': forms.NumberInput(attrs={'onclick': 'numberWithCommas()'}), } but the js function is gray in my html template and not working -
Django Server No output
Hi, I tried to run the server using python mange.py runserver.In return I get no output in terminal -
Logging in Customers via the shopify API
Logging in Customers via the shopify API Hi, The Shopify API is new to me, so I apologize in advance if it has already been answered. I manage a store shopify and I also want to create a python and django application allowing users to connect via Twitter. I have already connected the application to shopify (through a shopify partner and a development store). I also know how to connect a twitter account to my application (using requests_oauthlib for python). Now, I'm trying to integrate the auto login feature between the shopify store and my Django app. The app would be on www.myapp.com and the shopify store on www.shop.myapp.com. ; How can I make sure that the user is logged in during their visit to the shopify store if they connect to my Django application (via Twitter)? In this case, what should the user's password be or should I invite him to create a password when logging in via Twitter? Has anyone tried something similar with shopify? Any orientation would be great! Thank you so much! I give you all my Django code. There are many amelioration point but it's still in development. The two firsts function perform the installation … -
Django sum on query set
I have a queryset in django with condition as follows: query_set = (MyModel.objects.annotate(TWWByRuns=( Case( When(Q(toss_winner=F('winner'))&Q(win_by_runs=0), then=1), output_field=FloatField(), default=0))).values('TWWByRuns')) I would like to use django built-in sum function to add whenever the value in the query_set equals to 1 as in when then=1. I know to use the sum function without conditionals but here since I have condition where should I use the sum function in this query_set? -
How to increment a variable in a template Django
here is my views.py file in which i have delcared function subhead that load account objects to view def subhead(request): subheads=Account.objects.all() return render(request,'my/test.html',{'accounts':subheads}) here is my template {% for subhead in subheads %} {% with i=0 %} {% if subhead.parent == None and subhead.type == 'As' %} {% if i == 0 %} <tr> <td>Assets</td> <td>{{ subhead.name }}</td> </tr> {% else %} <tr> <td></td> <td>{{ subhead.name }}</td> </tr> {% endif %} {% endif %} {% set i=i+1 %} {% endwith %} {% endfor %} Now simply i want to increment a variable value But i don't know, how i can achieve this task.I have delcared a variable i =0 and also tried to set its values.But it returns an error Invalid block tag on line 419: 'set', expected 'endwith'. Did you forget to register or load this tag? -
Django automatic login after user registration (2.1.4)
The automatic login of newly registered users is not working in the case of a "class-based" registration view. I followed the example from this tutorial, which proposes the following registration view: # myapp/views.py from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.views import generic class SignUp(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' I tried including the class-based solution from this answer, but after successfully registering a new user, the login doesn't happen as expected. Are there changes in Django 2.1.4 which might cause this to malfunction? myapp.users.views: from django.views import generic from django.contrib.auth import authenticate, login from .forms import CustomUserCreationForm class SignUp(generic.CreateView): form_class = CustomUserCreationForm success_url = '/index' template_name = 'signup.html' #auto login after register: def form_valid(self, form): #save the new user first form.save() #get the username and password username = self.request.POST['username'] password = self.request.POST['password1'] #authenticate user then login user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'],) login(self.request, user) return super(SignUp, self).form_valid(form) -
Wagtail custom template at route
How would I add a custom template to a page when using RoutablePageMixin? @route(r'^tag/(?P<tag>[-\w]+)/$') def post_by_tag(self, request, tag, *args, **kwargs): self.search_type = 'tag' self.search_term = tag self.posts = self.get_posts().filter(tags__slug=tag) return Page.serve(self, request, *args, **kwargs) -
How automatically add info, specified during registration, to "Profile"?
I matched "Profile" with "User" by OneToOne with signals. I created SignUpForm with additional fields ('location', 'email', 'firstname' etc) and email confirmation. How make the this info ('location', 'email', 'first_name' etc) automacally added to "Profile"? I think, this really make with user.refresh_from_db() user.profile.<...>=form.cleaned_data.get('<...>') but I don't know how. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, blank=True, default='', null=True) location = models.CharField(max_length=30, blank=True, default='') email = models.EmailField(max_length=30, blank=True, default='', null=True) class Meta: ordering = ["location"] def get_absolute_url(self): return reverse('profile-detail', args=[str(self.id)]) def __str__(self): return self.user.username forms.py class SignupForm(UserCreationForm): email = forms.EmailField() location = forms.CharField() class Meta: model = User fields = ('username', 'email', 'location', 'password1', 'password2') class ProfileForm(forms.ModelForm): class Meta: model = Profile exclude = ('user', ) signals.py @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) admin.py class ProfileAdmin(admin.ModelAdmin): list_display = ('user', 'location', 'email', 'first_name') views.py def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: form … -
Django formsets __init__() got an unexpected keyword argument 'extra'
I have created two models w_orders(workorders) and tobjects. I have two templates, one is only for creating a workorder and this works fine and one other template which contains data of both workorders and objects. tobjects is related to the table w_orders and I want to be able to create x number of objects for a workorder. For every workorder an object is created automatically. So far I have created the template and I can't quite figure how to display only the related objects for a certain workorder. For example for workorder no 1 I get the objects that are created for other workorders. As well I cannot add or edit an object related to the workorder. This is my code: workorder_edit.html {% extends 'workorders/base.html' %} {% block jumbotron2 %} <div class="jumbotron"> <h1>Navbar example</h1> <p class="lead">This example is a quick exercise to illustrate how the top-aligned navbar works. As you scroll, this navbar remains in its original position and moves with the rest of the page.</p> <a class="btn btn-lg btn-primary" href="../../components/navbar/" role="button">View navbar docs &raquo;</a> </div> {% endblock %} {% load static %} {% block content %} <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} {{ formset.management_form }} … -
Django ORM values() and select_related() raise TypeError
In my django project i have to do an ORM query like this: ordered = t_threads.objects.values('thread_stag').filter(thread_status='DEAD',id_test__test_main__descr__contains= 'Hello').distinct().select_related().order_by('id')[1:10] i need to group result for value 'thread_stag' filtered for status and test description, having all values from related tables, but when i execute the above query system return: raise TypeError("Cannot call select_related() after .values() or .values_lis t()") if i remove the "select_related()" option i don't have values from related tables. How can i achieve my result in django ORM? So many thanks in advance -
Python callback testing
Dears, I want to test the callbacks of my code which written in python, but in my case, I need to test the callbacks without using Mock. Any ideas? Thanks, -
Is it possible to make migrations from db not from model?
Suppose, we have a db's backup and a django program. The program do not have any migrations. First we restore db, that has created table and data. Now we want to make migrations from available db. Is it possible or not? -
how to rereive the foreign key fields in only get request using django
I have my model like this: class Image(models.Model): name=models.CharField(max_length=40,unique=False) image=models.ImageField(upload_to='photos/%Y/%m/%d') class Resized_image(models.Model): image = models.ForeignKey(Image, related_name='resized_images', on_delete=models.CASCADE) rendition = models.ForeignKey(Rendition,related_name='rendition_id',on_delete=models.CASCADE) path = models.CharField(max_length=256,unique=False) I am specifying imagefield of Image table as foreign key in Resized_image model,so if do a get request i should get the path present in Resized_image table also,how can i do that? -
How to implement complex Django permissions
In my app a user can be a member of multiple companies. Each company has permissions (e.g. to manage the company or to add members) permission groups (a collection of permissions) which can be defined and assigned by company admins Now I'm looking for a practical solution to implement this. The default permission system of Django only supports Model-wide permissions. For object level permissions django-guardian seems to be the way to go, but django-guardian doesn't support groups as far as I understand. How would you go about that? -
Serving static files from CDN in django on IIS Windows Server 2012 R2
I am trying to deploy a django application on Windows server 2012 R2. The application works fine except from the fact the it isn't serving static files(javascript and bootstrap) from the CDN I am utilizing. It just leaves my pages looking lifeless. I already ran collectstatic but apparently this doesn't work for static files from content delivery networks.Everything works fine when i run the application locally. But running it on the windows server doesnt serve static files from CDN. Please help. Code for Using CDN: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/particlesjs/2.2.3/particles.min.js"></script> -
Django: How can I organize common form submisson part into a function?
I'm creating a website. For my website, user can edit their profile on every page because there's a navbar and from edit profile section, form on modal appears. So I'd like to organize this part into a function. But it seems difficult. def index(request): if request.method != 'POST': profile_form = ProfileForm(instance=request.user) elif 'profile_form' in request.POST: profile_form = ProfileForm(instance=request.user, data=request.POST) if profile_form.is_valid(): profile_form.save() messages.success(request, 'Your profile has been changed successfully.') return HttpResponseRedirect(request.path_info) context = { 'profile_form': profile_form, #there are other contexts here } return render(request, 'site/index.html', context) My current code is like this. This is supposed to be a common behavior on every page so I'd like to organanize this into other function. def edit_profile(request): if request.method != 'POST': profile_form = ProfileForm(instance=request.user) elif 'profile_form' in request.POST: profile_form = ProfileForm(instance=request.user, data=request.POST) if profile_form.is_valid(): profile_form.save() return HttpResponseRedirect(request.path_info) I created utils.py and created this function inside it. And I tried like def index(request): edit_profile(request) ... context = { 'profile_form':profile_form, # However this view doesn't know what profile_form is But ofc there is error because profile_form is not defined inside index How can I organize code in this case? -
how to submit a form and add record to the sqlite 3 database using django and jqyery with ajax
i have a form that request user input in order to save the records into the sqlite 3 database. the problem is that before i tried to add the upload image field to the form the data was saved correctly. but now the system first request that i add blank and null to num filed , date field , issent filed. then it display the below error : File "C:\Users\LT GM\Desktop\Final new\djangoWeb\views.py", line 160, in post_new id=form.te2chira_id added picture field to the model added picture element in the form added the input tag in the html send the data through AJAX to the view getting the data from ajax request and added to the view function models.py class te2chira(models.Model): te2chira_id = models.AutoField( primary_key=True) num = models.IntegerField(blank=True, null=True) te2chira_date = models.DateField(blank=True, null=True) title = models.CharField(max_length=250,default='DEFAULT VALUE', blank=True, null=True) description = models.CharField(max_length=500,default='DEFAULT VALUE', blank=True, null=True) is_sent=models.IntegerField(blank=True, null=True) picture = models.ImageField(upload_to = 'pictures/%d/%m/%Y/',null=True, blank=True) def __str__(self): return str(self.te2chira_id) form.py from django import forms from blog.models import te2chira, destination class SaveTe2chira(forms.ModelForm): class Meta: model = te2chira fields = ['num','title', 'description','picture' ] html <form method="POST" class="form-style-9" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <li> <input type="file" id="img" name="img"/> </li> <li> <input type="submit" class="field-style field-full align-none" … -
why mssql resolve host address using dns service without using hosts file
I am using localhost as the host for my Django database, but I can't connect to it, it will run correctly when I use '127.0.0.1' as my database host. If I ping localhost.localhost will resolve to 127.0.0.1. But if I run nslookup localhost, my dns server will resolve localhost to another ip address. My pip freeze: Django==2.1.5 django-pyodbc-azure==2.1.0.0 djangorestframework==3.9.0 pyodbc==4.0.25 pytz==2018.9 my setting: DATABASES = { 'default': { 'NAME': 'my_database', 'ENGINE': 'sql_server.pyodbc', 'USER': 'SA', 'PASSWORD': 'test2019!', 'HOST': 'localhost', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } } # holegots @ HolegotsMBP in ~/cute_cat on git:master x [15:11:37] $ sqlcmd -S localhost,1433 -U SA -P 'test2019!' Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : Login timeout expired. Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : TCP Provider: Error code 0x2AF9. Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.. # holegots @ HolegotsMBP in ~/cute_cat on … -
I want to solve Django NoReverseMatch
There is a problem here. I don't know how to solve this. Please help me. error source Code results.html <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'polls:detail' question_id %}">Vote again?</a> views.py-polls from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from polls.models import Question, Choice # Create your views here. def index(request): latest_question_list = Question.objects.all().order_by('-pub_date')[:5] context = {'latest_question_list':latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html',{ 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question}) Somehow there seems to be an error here. I don't think the reverse is the polls:results. Of course this is conjecture. urls.py-fistsite from django.contrib import admin from django.urls import path, include from polls import views urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), path('', views.index, name='index'), ] urls.py-polls from django.urls import path from . import views … -
Filtered Dropdown Select Menu in Django
I want to create filtered dropdown select menu for job_users when user select a job_group. This means that when a user select a group then users of that group will be displayed in job_users. I want to filter out job_users field because now it is displaying all users. forms.py class JobForm(forms.ModelForm): class Meta: model = Jobs fields = ['job_name', 'job_group', 'job_users'] Jobs Model.py class Jobs(models.Model): job_name = models.CharField(max_length=30) job_group = models.ForeignKey(Groups, on_delete=models.CASCADE) job_users = models.ManyToManyField(User,related_name='user_job') def __str__(self) : return self.job_name Views.py class JobAddView(LoginRequiredMixin, generic.CreateView): template_name = 'admin/jobs/jobs_form.html' form_class = JobForm success_url = '/useradmin/job/' def form_valid(self, form): return super().form_valid(form) Template <form class="forms-sample" action="" method="POST"> {% csrf_token %} {{ form | crispy}} </form> -
How can I fix migrating error while creating a database in models.py in Django?
I've started to learn Django using the No starch Python Crash Course. While going through the steps to code the 'entries', I cannot migrate the database. The error is shown. I'm using python 3.7 and Django 2.0.7 I've tried using python 3.6 but its still not working Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "E:\Users\HCL\AppData\Local\Programs\Python\Python37\lib\site- packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "E:\Users\HCL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "E:\Users\HCL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "E:\Users\HCL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "E:\Users\HCL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "E:\Users\HCL\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "E:\Users\HCL\Desktop\learning_log\learning_logs\models.py", line 10, in <module> class Entry(models.Model): File "E:\Users\HCL\Desktop\learning_log\learning_logs\models.py", line 11, in Entry topic = models.ForeignKey(Topic) TypeError: __init__() missing 1 required positional argument: 'on_delete' -
path expression with slug tag other than using url in django
I want to express path rather than urls but I am not sure the following codes are correct I think it does not work home/blog/posts I have constructed blog web programming using django so I exptected post page to pop up nicely but actually it didn't. I tired several times and searched for it in google but I did not gain what I expected. from django.urls import path from blog.views import * url(r'^post/(?P<slug>[-\w]+)/$', PostDV.as_view(), name='post_detail'), => path('post/(<slug:>[-w]+)/', PostDV.as_view(), name='post_detail'), url('tag/?P<tag>[^/]+(?u)/',PostTOL.as_view(),name='tagged_object_list'), =?path('tag/<tag:>[^/]+(?u)/',PostTOL.as_view(),name='tagged_object_list'), there are no messages on command line on window as below when I ran runserver System check identified no issues (0 silenced). January 15, 2019 - 01:43:13 Django version 2.1.4, using settings 'plateform.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [15/Jan/2019 01:43:24] "GET /admin/blog/post/ HTTP/1.1" 200 6863 [15/Jan/2019 01:43:24] "GET /admin/jsi18n/ HTTP/1.1" 200 3185 -
Posting Image Data to API in Python and Django
I'm trying to upload an image to an API endpoint. It works using the API tester Restlet Client but I can't seem to get it to work in Python and Django. Can anyone see any obvious errors in my code? fh = open('1.jpg', 'rb'); base64img = base64.b64encode(fh.read()) photoAPIURL = "https://example.com" photoAPIRequestData = {"photo": base64img} photoAPIRequest = requests.post(photoAPIURL, data=photoAPIRequestData, headers=APIRequestHeaders) APIRequestHeaders are correct as they work on Restlet Client. It's something to do with how the photo data is being sent. -
Django: Jquery doesn't work suddenly even though nothing changed.. ..is not defined
Jquery stopped working suddenly today even though I didn't change anything. I thought js file cannot be loaded from AWS S3 correctly and moved the part to html file but still doesn't work. here is my html <button class="btn btn-outline-warning" onclick="deleteEntry(this)" data-id="{{ entry.pk }}">Delete</button> ... <script> var csrf_token = '{{ csrf_token }}' function deleteEntry(this) { if (confirm("Are you sure you want to delete this entry?")) { var $this = $(this) $this.closest('tr').remove() var id = $this.data('id') $.ajax({ url:'/feeds/delete/' + id, method: 'DELETE', beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRFToken', csrf_token) }, }) } } </script> SCRIPT1048: SCRIPT1048: The use of a keyword for an identifier is invalid my_feeds (339,22) SCRIPT5009: SCRIPT5009: 'deleteEntry' is not defined How can I fix this? -
how to create a queryset for a multi blogging app where I can get tags for nth post on nth blog by nth user?
I have a couple of django models for my blogging app created for the purpose of learning from online resources. I have searched StackOverflow for similar questions but could not find useful answers. Hence, I am here to ask for help. Here is how my models look like class Blog(models.Model): owner = ForeignKey('auth.User', on_delete=CASCADE, related_name='blog') blog_name = CharField(max_length=100) class Post(models.Model): author = ForeignKey('auth.User', on delete=CASCADE post_title = CharField(max_length=125) post_body = TextField for_blog = ForiegnKey(Blog, on_delete=CASCADE) class Tag(models.Model): tag_name = CharField(max_length=50) class PostTag(models.Model): post_id = ForeignKey(Post, on_delete=CASCADE) tag_id = ForeignKey(Tag, on_delete=CASCADE) class Meta: unique_together = ('post_id', 'tag_id') Any help or direction will be useful.