Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should `_base_manager` or `_default_manager` be preferred over `objects` in Django?
From the docs : If you’re writing some code that must handle an unknown model, for example, in a third-party app that implements a generic view, use this manager (or _base_manager) rather than assuming the model has an objects manager. Then isn't it a "good practice" to use _base_manager or _default_manager over using objects always? That way we need not worry in the code if the objects manager exists or not or if has been changed, etc? -
Django: Why KeyError: 'pk'
I'm using Django 2.1 I think I have correctly described pk, but an error occurs. Could you tell me why an error occurs and the solution? KeyError at /create/ 'pk' According to the error, there seems to be a problem with "get_success_url", but I do not know why. #views.py class MemoCreateView(LoginRequiredMixin, CreateView): model = Memo form_class = MemoForm def form_valid(self, form): obj = form.save(commit=False) obj.created_by = self.request.user return super(MemoCreateView, self).form_valid(form) def get_success_url(self): return reverse_lazy('detail', kwargs={"pk": self.kwargs['pk']}) #urls.py urlpatterns = [ path('<int:pk>', MemoDetailView.as_view(), name="detail"), path('create/', MemoCreateView.as_view(), name="create"), ] please tell me. thank you for reading. -
how to show django messages without reloading the page?
i was building a pop up signup form. and don't want to reload the page when it go to some error or success message. because then pop up form will get closed. i just want to show the message just there without reloading page. this is what i am doing so far views.py def signup(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"].lower() password = request.POST["password"] password2 = request.POST["password2"] try: if password2 != password: messages.error(request, "password didn't match") elif len(password) < 6: messages.error(request, "password is too small.") elif User.objects.get(email=email): messages.error(request, "user with this email already exists") except: if not (User.objects.filter(username=username).exists()): user = User.objects.create_user(username=username, email=email) user.set_password(password) user.save() messages.success(request, "User Created") else: messages.error(request, "Looks like username already exists") django_messages = [] for message in messages.get_messages(request): django_messages.append({ "level": message.level, "message": message.message, "tags": message.tags, }) data = {} data['messages'] = django_messages return HttpResponse(json.dumps(data), content_type="application/json") return redirect(request.META['HTTP_REFERER']) ajax code <script type="text/javascript"> $(document).on('submit','#signup_form',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:"{% url 'auth_signup' %}", data:{ 'username':$('#signup_username').val() 'email':$('#signup_email').val(), 'password':$('#signup_password').val(), 'password2':$('#signup_password2').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success:function(data){ update_messages(data.messages);; $(".message").show(); }, error:function(data){ update_messages(data.messages); (".message").show(); } }); }); <script type="text/javascript"> function update_messages(messages){ $("#msgs").html(""); $.each(messages, function (i, m) { $("#msgs").append("<div class='alert "+m.tags+"''><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>"+m.message+"</div>");});}</script> when i press submit button. it should … -
How to add custom action to django admin
how can i send email to the selected choices in reply action? settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'admin@gmail.com' EMAIL_HOST_PASSWORD = 'admin' EMAIL_PORT = '587' admin.py class ContactAdmin(admin.ModelAdmin): list_display = ['full_name','email','comment','time'] list_filter = ['time'] search_fields = ['name','comment'] readonly_fields = ['full_name','email','comment','time'] ordering = ['time'] actions = ['reply'] def reply(self): pass # I got no idea what logic should i have to write here to send email to the selected choices admin.site.register(Contact,ContactAdmin) -
Python TypeError: Required argument 'offset' (pos 1) not found
I get an error TypeError: Required argument 'offset' (pos 1) not found when i instantiated an object form models class: users like a = users() this class has dynamic attributes created from a list service_data using vars() function. class users(models.Model): for i, j in zip(config.service_data[0], config.service_data[1]): vars()[i] = CrudAPI.create_db_field(j) And this is create_db_field method code: def create_db_field(test): if (test == "char50"): return models.CharField(max_length=50, blank=True) if (test == "text"): return models.TextField(blank=True) if (test == "date"): return models.DateField(blank=True) if (test == "datetime"): return models.DateTimeField(default=datetime.timezone, blank=True) if (test == "number"): return models.FloatField(blank=True) and this is my list used to create those attributes dynamically: service_data=[["username","password"],[],["email","password"]] I don't understand what the wrong with it -
How to retain images folder while publishing on elastic-bean?
The uploaded images are getting overridden every time when a new version of the application is deployed on to elastic-bean. I am deploying Django application and I think I need to do something with the YAML config files but not sure about it. My application has an Image upload feature for the client. Whenever I publish the new version of the application the old one is overwritten along with the removal of the images under the image folder. -
django.db.utils.NotSupportedError: FOR UPDATE cannot be applied to the nullable side of an outer join
I've found this error in server log. Can't replicate the problem. File "/home/futilestudio/.venvs/36venv/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __len__ self._fetch_all() File "/home/futilestudio/.venvs/36venv/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/futilestudio/.venvs/36venv/lib/python3.6/site-packages/django/db/models/query.py", line 54, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/futilestudio/.venvs/36venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1065, in execute_sql cursor.execute(sql, params) File "/home/futilestudio/.venvs/36venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/home/futilestudio/.venvs/36venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/futilestudio/.venvs/36venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/futilestudio/.venvs/36venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/futilestudio/.venvs/36venv/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/futilestudio/.venvs/36venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) django.db.utils.NotSupportedError: FOR UPDATE cannot be applied to the nullable side of an outer join I think that it happens only on PostgreSQL database. I tried Sqlite before and it worked. The problem is here: match, created = Match.objects.update_or_create(match_id=draft_match.match_id, defaults={ field.name: getattr(temp_match, field.name, None) for field in Match._meta.fields if not field.name in ['id', 'pk']}) Is there a problem in attributes or do I must not use update_or_create and do it another way? -
Can I test the contents of a view in Django?
I have a view that gets contents from the fields of my models. Data from one field may appear numerous times in my view. If I need to edit the view such that data in field1 which appears many times need to be replaced by data in field2, I need to look for all those instances and can lead to me missing some fields to be replaced. The question is I want to automate my testing so that I dont need to run the view anymore when I do such changes and instead just run a test if I missed something. Field1 may appear somewhere else in the same view or other views but all the previous field1 in the view I am working on should be field2 data so Find and Replace All wont do it. Is it possible to do unittesting for this? How do I ensure that all field1 have been replaced by field2 data? -
Django Rest Framework receiving a simple Json Array whose model does not exist
I am receiving this json body { "skills" : [ "First skill", "Second skills", "Third skills" ] } I do not have a model for it and I am doing something like this. I have read from other posts that in this case I could inherit from views.APIView which I am trying to do. class SkillsSubscription(serializers.Serializer): skills = serializers.CharField(required=True,) and in the view I am doing something like this class CreateUpdateEmployeeSkillsSubscription_APIView(views.APIView): permission_classes = [] def post(self, request): results = SkillsSubscription(request.data,many=True).data return Response(xxx) I get an exception when I use that serializer. This is the exception. AttributeError: Got AttributeError when attempting to get a value for field `skills` on serializer `SkillsSubscription`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'skills'. Any suggestions on how I could obtain the contents in the skills array ? -
Models conflict in APITestCase Django
I'm trying to setup tests for my DRF API. I've got 2 models: class Project(models.Model): name = models.CharField(max_length=300, unique=True) description = models.CharField( max_length=2000, blank=True, null=True, default=None ) created_at = models.DateTimeField(auto_now_add=True) class TemporaryUser(models.Model): username = models.CharField(max_length=400) hash_id = models.URLField(default=_generate_unique_hash, unique=True) project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='users' ) I've decided to separate setUp methods for every test file, so my 2 test files look like this: test_projects.py class ProjectViewsTest(APITestCase): client = APIClient() @classmethod def setUpClass(cls): project = Project.objects.create(name="Test Project") cls.project_creation_date = datetime.now().strftime( '%Y-%m-%d %H:%M:%S' ) Project.objects.create( name="Test Project #2", description='Testing Project Number 2' ) session = QuestionSession.objects.create(project=project) cls.session_creation_date = datetime.now().strftime( '%Y-%m-%d %H:%M:%S' ) Question.objects.create( description='Test Question #1', question_type='TEXT', answers_to_close=50, question_session=session ) Question.objects.create( description='Test Question #2', question_type='TEXT', answers_to_close=50, question_session=session ) Question.objects.create( description='Test Question #3', question_type='TEXT', answers_to_close=50, question_session=session ) @classmethod def tearDownClass(cls): Project.objects.all().delete() def test_projects_fetched_with_sessions_number(self): """Test multiple projects are fetched with sessions counter""" self.maxDiff = None response = self.client.get( 'http://testserver/api/projects/', format='json' ) self.assertEqual(response.status_code, 200) self.assertJSONEqual( response.content, { "projects": [ { "id": 1, "name": "Test Project", "description": None, "sessions_number": 1, "created_at": self.project_creation_date }, { "id": 2, "name": "Test Project #2", "description": "Testing Project Number 2", "sessions_number": 0, "created_at": self.project_creation_date } ] } ) def test_project_fetched_with_minified_sessions(self): """Test a project is fetched with minified sessions""" response = … -
how to send email to the admin by user using the contact page in django
I want to allow users to send email to the admin by using contact form.Which will saves the contact form request.post data in the database table and receives the user's email message in admin email inbox. This following code saves the request.Post data in the database as i wanted and also sends the email successfully but the email sent was from recipients(EMAIL_HOST_USER) to recipients itself instead of taking request.post from_email address.In the admin email inbox there is admin sending email to admin himself. I want to send email from request.post from_email address to the admin email address. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'admin@admin.com' EMAIL_HOST_PASSWORD = 'admin mailpassword' EMAIL_PORT = '587' views.py def homepage(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): contact = form.save(commit=False) full_name = form.cleaned_data['full_name'] comment = form.cleaned_data['comment'] from_email = form.cleaned_data['email'] recipients = [settings.EMAIL_HOST_USER] if full_name and comment and email: try: send_mail(full_name, comment, from_email, [recipients]) except BadHeaderError: return HttpResponse('Invalid header found.') contact.save() messages.success(request,'Your Message Sent.') else: messages.error(request,'Error in Form.') else: form = ContactForm() return render(request,'company/index.html',{'form':form}) -
Render a select box as radios buttons in Django Admin
I want to show select box options as raido buttons in Django Admin change model view. I don't want to write custom model forms. I'm looking for a way to render some select boxes as radio buttons while keeping auto generated model forms of the Django admin. I'm using django v 1.11. -
Double quotes Miss Matching in Html fie While adding Django template keys on Visual studio Code
For the following html code , in img tag while adding a image path as template key , the double quotes are wrongly taken by the visual studio </h2> <img src="{% static "images\image.jpg" %}" alt="not available"> </body> -
How to keep files in the formset after page reload? . Django
Having spent few days trying to figure it out. Maybe it is a simply question for you, but, anyway… I have a view for the form within inline formset that receives and saves files + few text fields in a primary model form itself. Problem is when form + formset are filled with text data for the main form and files for the formset, in case if main form is not valid, page gets reloaded and files from formset would get lost and I have to attach them again. I would like to have this situation fixed in a way that files after re rendering of the page would be present as well, but, unfortunatelli i can not find the solution. My view is as following: # only the portion that in charge for the above-mentioned logic # files are getting lost in form2. With form 1 everything is OK def viewname(request): if request.method == 'POST': form1 = MainForm(request.POST, request.FILES, prefix="form1") if form1.is_valid(): prim = form1.save(commit=False) prim.author = request.user form2 = inline_formset(request.POST, request.FILES, prefix="form2", instance=prim) else: form2 = inline_formset(request.POST, request.FILES, prefix="form2") context = {"form1": form1, "form2": form2} return render(request, "create.html", context) … … … reload of the page is caused … -
how to render my contact form within a index/home page
I have a contact page attached within a index/home page. It does not have any contact.html page. How can i give url to the contact in my navigation bar so that it slides down to the contact page in the same home page. index.html <div class="nav-container"> <ul> <li><a href="{% url 'company:home' %}">Home</a></li> <li><a href="{% url 'company:about' %}">About</a></li> <li><a href="{% url 'company:services' %}">Services</a></li> <li><a href="">Portfolio</a></li> <li><a href="{% url 'company:blog' %}">Blog</a></li> <li><a href="">Contact</a></li> # what url should i have to give here so that it gives the contact page within this index page </ul> </div> <!-- Contact Section --> <section id="contact"> <div class="container"> <h1 class="title">Contact Us <p>HOW TO CONNECT WITH US ?</p> <span class="underline"></span> </h1> <div class="row"> <div class="col-md-6"> <div class="map"> <iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d7066.152739935275!2d85.3461636!3d27.6840344!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x39eb19a18187378f%3A0x8ba2460dd7896e64!2sOnline+Zeal!5e0!3m2!1sen!2snp!4v1553841516009!5m2!1sen!2snp" width="100%" height="450" frameborder="0" style="border:0" allowfullscreen></iframe> </div> </div> <div class="col-md-6"> <form action="{% url 'company:contact' %}" method="post"> {% csrf_token %} <label for="full-name">Full Name *</label> <input id="name" type="text" name="full_name" class="form-control"> <label for="full-name">Email Address *</label> <input id="full-name" type="email" name="email" class="form-control"> <label for="full-name">Comment (if any)</label> <textarea name="comment" rows="3" class="form-control" ></textarea> <button type="submit" class="btn btn-alternate">Submit</button> </form> </div> </div> </div> </section> views.py def homepage(request): services = Service.objects.filter(active=True) if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): contact = form.save(commit=False) contact.save() else: messages.error(request,'Error in Form.') else: form … -
TemplateSyntaxError at / 'pages_extras' is not a registered tag library. Must be one of in Django 2
TemplateSyntaxError at / 'pages_extras' is not a registered tag library. Must be one of: I am sorry, I have a question: TemplateSyntaxError at / 'pages_extras' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache i18n l10n log static staticfiles tz -
django mssql server partitioning by rownumber and getting row 1 only
I'm using django-pyodbc-azure to connect to mssql server. I have a model where I want to partition the rows by RowNumber and get rows with row number 1 only. I'm succesfully adding a row number to the queryset using annotate and window function, TicketActivity.objects.annotate(row_number=Window(expression=RowNumber(), partition_by=[F('ticket_id'), F('ticket_status')], order_by=F('activity_date').asc(),),) How do I filter this? using .filter(row_number=1) give me an error Window is disallowed in the filter clause. -
DRY calling serializer.data does not return updated instance of model
I'm working on the update section of BlogSerializer. The instance passed to serializer gets updated in the database of when I call blog_serializer.data returns old data instead of new data but when I refresh browser than the latest data will be displayed. I have checked that their are not errors while updation. So how can I get the latest updated data to be displayed in my browsable API Serializer.py class BlogSerializer(ModelSerializer): blog_files = serializers.SerializerMethodField() uploaded_files = serializers.FileField(write_only=True, required=True) blog_created_at = serializers.SerializerMethodField(read_only=False) class Meta: model = BlogModel fields = ('blog_id', 'user', 'title', 'content', 'status', 'blog_files', 'blog_created_at', 'uploaded_files', ) extra_kwargs = { 'title': { 'error_messages': { 'blank': 'Title field must not be left blank..' }, 'label': 'Enter Blog Title', 'help_text': 'This is help text of title field' } } def update(self, instance, validated_data): file_list = validated_data.pop('uploaded_files', None) instance.title = validated_data.get('title', instance.title) instance.content = validated_data.get('content', instance.content) instance.user = validated_data.get('user', instance.user) instance.status = validated_data.get('status', instance.status) instance.save() if not isinstance(file_list, (list)): file_list = [file_list] print("\n file_list data : {} \n".format(file_list)) info = [] for i in file_list: row = { 'blog': instance.blog_id, 'path': i } info.append(row) if len(info) > 0: file_instance = BlogFilesSerializer(data=info, many=True) if file_instance.is_valid(): file_instance.save() return instance views.py class BlogViewSet(viewsets.ModelViewSet): queryset = BlogModel.objects.all() … -
Is there a better way to do calculations on relations in Django Viewsets?
I'm having trouble creating a viewset, doing calculations on fields in a related model. I am fairly new to Django, so please take it easy on me. :) Essentially. I have a Character Model. And a Raids model. The Raids model has a ManyToMany relation to Character. Each raid is worth a Value. I have summed up the values fine, I think. My main question is, I want to be able to calculate 30, 60, 90 day and lifetime attendance for each Character. And I'm struggling. Any help you can provide, I would appreciate. models.py from datetime import timedelta from django.contrib.auth.models import User from django.db import models from django.utils import timezone ... class Character(models.Model): name = models.CharField( 'Name', unique=True, primary_key=True, max_length=25, ) level = models.IntegerField( 'Level', ) character_class = models.ForeignKey( CharacterClass, on_delete=models.SET_NULL, null=True, verbose_name='Character Class', related_name='characters', ) character_type = models.ForeignKey( CharacterType, on_delete=models.SET_NULL, null=True, verbose_name='Character Type', related_name='characters' ) is_app = models.BooleanField( 'Applicant', default=False ) class Meta: ordering = ['name'] def __str__(self): return self.name ... class Raid(CreatedModifiedAbstractModel): event = models.ForeignKey( Event, on_delete=models.PROTECT, verbose_name='Event', related_name='raids', ) value = models.PositiveSmallIntegerField( 'DKP Value', ) datetime = models.DateTimeField( 'Date', auto_created=True, ) characters = models.ManyToManyField( Character, verbose_name='Attendees', related_name='raids', ) note = models.CharField( 'Note', max_length=100, null=True, ) not_attendance … -
oauth2 authentication work fine but in django engine return error invalid_client
In my project I have implemented oauth2 for login, when I run my project on nginx and I request to o/token/ I can get a token but when I run django engine(python manage.py runserver)it returns Invalid_client -
how do i do monthly sales projections in django
I am trying to develop an application where user can enter their average revenue projections per product for 12 months. The user should be able to enter the first month of their choice (month and year). The application should populate the following 11 months based on the first month and allow the user to input the revenue amount for each month and calculate the cost of sales of each month (cost of sales is 30% of the sales) and calculate the gross profit for each month (gross profit = revenue minus cost of sales) This is a part of a business plan development application for a business to prepare the financial projection for next 12 months -
User is always none, doesn't allow the user to sign in
While creating a login and signup form, I have been having issues with the sign up form, the issue is that whenever I create user through registration and try to log in with the test user it doesn't log, always points the Httpresponse I have set up. After checking the admin panel the user is being created, now I do not know where to go, I do think I am not grabbing the right data or its not grabbing it ## Register def register(request): if request.method == 'GET': return render(request, 'auth/register.html', { }) if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] passwordConf = form.cleaned_data['passwordConf'] email = form.cleaned_data['email'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] user = User.objects.create_user(username, password, email) if password == passwordConf: return HttpResponseRedirect("/auth/signin") else: return HttpResponse("Passwords do not match", status=400) else: return HttpResponse("Invalid registration request.(Bad Request)", status=400) else: form = RegistrationForm return HttpResponse("Method not allowed on /auth/register.(Method Not Allowed)", status=405) ## Signin def signin(request): if request.method == 'GET': return render(request, 'auth/signin.html', { }) if request.method == 'POST': form = SigninForm(request.POST) if form.is_valid(): username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect('/') … -
I have to create data on demand for the post
I am new to Django and building a blog app in which I am writing posting a status through ajax and now whenever i am clicking load more button I am not getting the contents from database. here is my code. this is the ajax i am using for load more button:- $("#mybtn").on('click',function(){ $("#load").val(1); $("#start").val(start); $("#end").val(end); $.ajax({ type: "Post", url: $("#myform").attr('action'), data: $("#myform").serialize(), ` success:function (response){ if(response.status == true ){ $('.contents:last-child').remove(); } }, error: function(data){ $("#message").html("Something went wrong!"); } }); }); this is the index.html: {% block content %} <ul class="hello"> {% for item in posts %} <div class="contents"> <li>{{ item.content }}</li> </div> {% endfor %} </ul> {% endblock %} and this is my view.py: if request.is_ajax(): response = {"status": False} load = request.POST.get('load') if load == 0: content = request.POST.get('content') post = Post() post.content = content post.save() response = {"status": True, "content": content} return HttpResponse(json.dumps(response), content_type="application/json") else: start = request.POST.get('start') end = request.POST.get('end') posts = Post.objects.order_by('-pub_date')[int(start):int(end)] print(posts) data = serializers.serialize('json', posts, fields=('content')) response = {"status": True, "content": data} return HttpResponse(json.dumps(response), content_type="application/json" ) else: posts = Post.objects.order_by('-pub_date')[:5] return render(request, 'post/index.html', {'posts': posts}) So, whenever I post a new status,the last 5th post should be removed and the latest 5 post … -
Pictures not being filtered based on the logged in user
I am building a Photo Gallery as my last project. A Photographer can log in on the website and upload pictures in his portfolio. This part of the code works. However, the pictures are not being filtered based on the logged in user. Instead i get all the pictures from all the users like you would on a home page. I am new to Django and Web Dev in general and I've been stuck with this for three days now. I'll be grateful for any help and even more grateful for a decent explanation :). Thank you very much in advance. I have tried to modify the query by using the get_queryset function but i probably lack the knowledge to do it properly. I have tried to match my user field with the user table, no results either. I am still learning half of how Django works. I came a long way just by going through some docs and tutorials but got stuck with this one pretty hard. models.py: class CustomUser(AbstractUser): full_name = models.CharField(max_length=200, default='') profile_picture = models.ImageField(upload_to='media/img', blank=True, null=True) introduction = models.TextField(default='') def __unicode__(self): return self.email class Pictures(models.Model): picture = models.ImageField(upload_to='img', blank=True, null=True) date = models.DateTimeField(default=timezone.now()) views = models.IntegerField(default=0) … -
Django collect static file when DEBUG = False
In django project deployment when I use DEBUG=False than static file is not working how can I solve this problem.