Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add comment to a particular model in django?
I have to add comment to model class Question, class Question(models.Model): My comment must be from user sides. Do help me with both codes for django and html-interface. -
Django-rest-framework with django OAuth 2.0 giving authentication error
I have integrated django-rest-framework with django-oauth-toolkit. And it is giving me {"detail": "Authentication credentials were not provided."} with un authenticated apis. Here's my settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } views.py from rest_framework.views import APIView from rest_framework.response import Response class SignUpView(APIView): """ Signup for the user. """ def get(self, request): return Response({'result': True, 'message': 'User registered successfully.'}) urls.py from django.urls import path from myapp.views import SignUpView urlpatterns = [ path('signup/', SignUpView.as_view()), ] -
Pagination in Django not working as expected
I wanted a pagination for all the courses available and that was easy to achieve. But now I'm stuck because I wanted pagination for faculties also, that will show specific courses of the accessed faculty. I have 4 models: faculties, departments, studies and courses. The pagination will show for faculties as well, but problem is that if I try to go to the second page, it will redirect me to the second page of all courses list. Or, if I change page on all courses and then try to access a faculty, no course will show at all in the faculty. This is working: <div id="crs"> <h3>All courses</h3> <ul> {% for course in courses %} <li><a href={{ course.slug }}>{{ course.name }}</a></li> {% endfor %} </ul> <div class="pagination"> <span class="step-links"> {% if courses.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ courses.previous_page_number }}">{{ courses.previous_page_number }}</a> {% endif %} <span class="current"> Page {{ courses.number }} of {{ courses.paginator.num_pages }} </span> {% if courses.has_next %} <a href="?page={{ courses.next_page_number }}">{{ courses.next_page_number }}</a> <a href="?page={{ courses.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> </div> This is not working: <div id="fac_{{ faculty.pk }}_tab" style="display:none;"> <h3> {{ faculty.name }} Courses</h3> <ul> {% for department in faculty.department_set.all %} {% for … -
Dynamic page using Django(1.8) and Python 3.5
I am making a Dynamic Websites which updates Cryptocurrency rates every 1 minute using Django 1.8 and Python 3.5 Question Is it possible to make a function using Django and python that calls itself after every 1 minute or make another function that calls the other function after every 1 minute ,since that function will update values of cryptocurrencies and also change values shown on the website to the user? -
MultiValueDictKeyError when submitting ModelFormSet
When trying to submit my ModelFormSet I am getting a MultiValueDictKeyError. The error message is not very descriptive so I'm not sure why the error is being thrown. Here is the view: def admin_tools(request): ElectionFormSet = modelformset_factory(Election, exclude=('Complete',), formset=BaseElectionFormSet, extra=0) if request.method == 'POST': if 'new_election' in request.POST: new_election = NewElectionForm(request.POST) if new_election.is_valid(): election = new_election.save(commit=False) election.save() messages.add_message(request, messages.SUCCESS, 'Election created') return redirect(reverse('elections:home')) elif 'edit_elections' in request.POST: formset = ElectionFormSet(request.POST) if formset.is_valid(): formset.save() messages.add_message(request, messages.SUCCESS, 'Election settings saved') return redirect(reverse('elections:home')) else: new_election_form = NewElectionForm() formset = ElectionFormSet() return render(request, 'admin/admin_tools.html',{ 'new_election': new_election_form, 'formset': formset, }) Here is the relevant section of the template: <div class="card-body"> <h4>Toggle election settings:</h4> <form method="post" action=""> {{ formset.management_form }} {% for form in formset %} {% csrf_token %} <div class='card'> <div class='card-body w-75 mx-auto'> <div class='row'> <div class='col-6 text-center'> <p>Name<br>{{form.Name}}</p> </div> <div class='col-6 text-center'> <p>Videos<br>{{form.FlipGrid}}</p> </div> </div> <div class='row'> <div class='col-12 text-center'> <p>Description<br>{{form.Description}}</p> </div> </div> <div class='row'> <div class='col-6 text-center'> <p>Allow registration: {{form.CandidateReg}}</p> </div> <div class='col-6 text-center'> <p>Allow voting: {{form.VotingOpen}}</p> </div> </div> </div> </div> {% endfor %} <div class='text-center'> <br><button type="submit" class='btn btn-outline-dark' name='edit_elections'>Save</button> </div> </form> </div> The error is raise MultiValueDictKeyError(repr(key)) django.utils.datastructures.MultiValueDictKeyError: "'form-0-id'" and it was flagged on the line: if formset.is_valid(): of the … -
Adding redirect for Django admin detail view
I'm trying to set up a redirect so that when Django CMS users are accessing a detail view for one of the admin models, they get redirected to the listing view. I was able to successfully override the detail view within the admin.py file: class MyAdmin(MyModelAdmin): change_form_template = u"admin/myadmin/change_form_content.html" within the template, I'm creating a redirect back to the list view: {% block content %} <meta http-equiv="REFRESH" content="0;url=/myadmin/"> {% endblock %} This works fine, but it's messy. How can I move the redirect to the admin.py file instead? -
django category and subcategory selection on admin page
I'm having three tables, Category, Subcategory, Products. While inserting new product, there are two select boxes 1)1st select is for Category (its working) 2) 2nd is for Subcategory, which should be relevant to the 1st select. Needs to fetch the data from subcategory table. Subcategory table has category id as a foreign key. I am a beginner, please somebody help. -
Django: Accessing user-uploaded files in view
I have the following question: I have a listview that lists a number of user uploaded PDF files. I am creating a method that Zips them all in a .zip file and emails them (when a button is clicked). I have the following question: I am currently working locally on test data, but on our production setup the User Uploaded files are kept on a seperate S3 storage server. (As I understand is common). Since these files are on a different server however, do I need to write code in my view to download them first? Lets say for example that this is the model of an PDF file class ResumeItemFile(models.Model): item = models.ForeignKey(ResumeItem, related_name='attachment_files') file = models.FileField( max_length=255, upload_to=RandomizedFilePath('resume_attachments'), verbose_name=_('Attachment')) name = models.CharField(max_length=255, verbose_name=_('Naam'), blank=True) Since the file field links to a different S3 server, would a ResumeItemFile.file call result in a .get request that I need to handle, or does Django do this stuff automatically in the background? -
Methods for rendering only a block in a django base template
I am in dire need of some direction, I need no code unless its an example. I have been struggling with this: My base.html page has 3 div elements in the top that will cycle alert messages and rotate every 10 seconds or so. Easy enough, however I want this ticker to remain site wide. I'm using Django as my back end and have yet to integrate react or riotjs. I attempted AJAX however I would have to do so much to make my site function as everything BUT the ticker would be an AJAX call which doesn't feel right. Plus I lose back button and SEO. Attached is an image of what the site looks like for these tickers. I can add code if anyone thinks it will help however i just need the basic method to decide where to move on. I cannot think of anything for the life of me, THANK YOU! This is the top of the site that I am working on, as you can see the 3 alert divs -
Loaded image on canvas disappears when user draws on it
I am working with Django framework and I want to load on a canvas an image and then draw over it. With the following code I successfully load the image: <form method="post" enctype="multipart/form-data"> <input TYPE="button" onClick="myReload();" VALUE="Refresh"> <script> function myReload() { location.reload(); } </script> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% if uploaded_file_url %} <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p> {% endif %} <canvas id="canvas" width="768" height="576" style="border:1px solid #d3d3d3"></canvas> {% if name_of_file %} <img id="image" style="display: none;" src="/static/{{ name_of_file }}"> {% endif %} I am trying to draw a polygon over the loaded image. When I press the 'Draw' button I can draw on the canvas but the image I uploaded disappears. <button onclick="drawPolygon()" name="plaque">Draw</button> function drawPolygon() { var img = new Image; img.onload= function() { document.getElementById("canvas").style.cursor="crosshair"; var canvas=document.getElementById("canvas"); var context=canvas.getContext("2d"); var cw=canvas.width; var ch=canvas.height; function reOffset(){ var BB=canvas.getBoundingClientRect(); offsetX=BB.left; offsetY=BB.top; } var offsetX,offsetY; reOffset(); window.onscroll=function(e){ reOffset(); } context.lineWidth=2; context.strokeStyle='blue'; var coordinates = []; var isDone=false; $('#done').click(function(){ isDone=true; }); $("#canvas").mousedown(function(e){handleMouseDown(e);}); function handleMouseDown(e){ if(isDone || coordinates.length>10){return;} // tell the browser we're handling this event e.preventDefault(); e.stopPropagation(); mouseX=parseInt(e.clientX-offsetX); mouseY=parseInt(e.clientY-offsetY); coordinates.push({x:mouseX,y:mouseY}); var stringY = document.getElementById('yA1').value; document.getElementById('yA1').value = stringY + ' ' +parseInt(e.clientY-offsetY); var stringX = document.getElementById('xA1').value; … -
Splitting Django views in multiple views with import in a separate file
I am trying to split my very very long view.py file I am following tutorials that I found but I may miss something. I will make my example generic to fit to other that may have the same issue. Let say that I have a view.py in following way : import xx from yy import xx from yy import xx from yy class name1(view): class name2(view): class name3(view): class name4(view): Now what I did is to create a view file with inside: View -> __init__.py -> views_import.py -> view1.py -> view2.py -> view3.py in __init__.py : from .views_import import * from .view1 import * from .view2 import * from .view3 import * However I get an error message that NameError: name 'generic' is not defined. When from django.views import generic is in my views_import.py Could you help ? -
Django ContentType Name of CamelCase models
I am playing with generic foreign key, and i wanted to filter the available models with limit_choices_to. class Foo(models.Model): name = models.CharField(max_length=300) class FooBar(models.Model): name = models.CharField(max_length=300) class Treatment(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to={'model': 'foo'}) # !! object_id = models.CharField(max_length=300, null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') So it works with the class Foo, in lower case, but for FooBar i tried foo_bar, fooBar, foo bar and none of these works... How am i suppose to spell it ?? I can see its separated by spaces in the drop down menu of the content type form. -
Django Crud for a Model, Need to Copy for Big no of Models, Need DRY Concept
I have crud for model but i need to copy this for big no of models.. I Need Your Recommendations to minimize the copy past. Thanks And kindly dont recomment django admin, i want to use my own theme. I hvae model as: class Board(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) description = models.CharField(max_length=100, null=True, blank=True) And ModelForm as: class BoardForm(forms.ModelForm): class Meta: model = Board fields = [ 'name', 'description', ] I have Django Url Patterns as shown below: url(r'^board/$', board_crud, name='board_crud'), url(r'^board/(?P<pk>\d+)$', board_crud, name='board_update'), And i Have View: def board_crud(request, pk=None): objects = Board.objects.filter() if pk is not None: object = get_object_or_404(Board, pk=pk) form = BoardForm(request.POST or None, instance=object) if form.is_valid(): form.save() form = BoardForm() return redirect('board_crud') return render(request, "crud/boards.html", {'form': form, 'object_list': objects}) else: if request.method == 'GET': form = BoardForm() else: form = BoardForm(request.POST) if form.is_valid(): instance.save() form = BoardForm() messages.success(request, 'Record Added Successfully') return render(request, "crud/boards.html", {'form': form, 'object_list': objects}) And Template with form Maker and Table: {% for field in form %} <section class="col col-6"> <label class="label">{{ field.label_tag }}</label> <label class="input"> {{ field }} </label> </section> {% endfor %} <table id="tbl" class="table table-bordered table-striped"> <thead> <tr> <th>Board Name</th> <th>Description</th> </tr> </thead> <tbody> {% for … -
Overriding Django Admin Detail View
How can I override the existing admin detail view for a model in Django? I understand how to make changes to the listing view, but I'm not entirely sure how to make changes to the detail views. Ideally I want create an override so that instead of accessing a form, the user is redirected back to the listing view. class MyAdmin(MyModelAdmin): change_list_template = u"admin/post_manager/content/change_list_content.html" -
circular import error in django
PS C:\Users\Shirish\Desktop\carwebsite> python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x061CB078> Traceback (most recent call last): File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 538, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 398, in check warnings.extend(check_resolver(pattern)) File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 397, in check for pattern in self.url_patterns: File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Shirish\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 545, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'home.urls' from 'C:\\Users\\Shirish\\Desktop\\carwebsite\\home\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Django signal conditionally update one table based on another
I'm working on my first django project that is a sports betting game. Here are my models: class Game(models.Model): home_team = models.CharField(max_length=200) away_team = models.CharField(max_length=200) home_goals = models.IntegerField(default=None) away_goals = models.IntegerField(default=None) class Bet(models.Model): gameid = models.ForeignKey(Game, on_delete=models.CASCADE) userid = models.ForeignKey(User, on_delete=models.CASCADE) home_goals = models.IntegerField() away_goals = models.IntegerField() score = models.IntegerField(default=None, null=True) First I create a game instance with null values in goals fields, then users make their bets. Once the game is over, I update game goals fields. Now I need to assign points for each user like this: WHEN bet.home_goals = game.home_goals AND bet.away_goals = game.away_goals THEN 2 WHEN game.home_goals > game.away_goals AND bet.home_goals > bet.away_goals THEN 1 WHEN game.home_goals < game.away_goals AND bet.home_goals < bet.away_goals THEN 1 WHEN bet.home_goals = bet.away_goals AND game.home_goals = game.away_goals THEN 1 ELSE 0 It seems that I should create a POST_SAVE singal to update Bet.score for each user based on update of Game.home_goals and Game.away_goals? But I have no idea how to do this -
Getting RIGHT JOIN with intermediate table with Django ORM?
I have these models: class Region(models.Model): region_name = models.CharField(max_length=64) def __str__(self): return self.region_name class GameRegionRelease(models.Model): region = models.ForeignKey( Region, on_delete=models.CASCADE, verbose_name='region' ) game = models.ForeignKey( Game, on_delete=models.CASCADE, verbose_name='game' ) release_date = models.DateField( verbose_name='release date', default=None ) class Game(models.Model): game_name = models.CharField(max_length=512) release_dates = models.ManyToManyField( Region, related_name='game_release_dates', through='GameRegionRelease' ) What I'm looking to get is every region listed for every game, even if there is no region data for that game. So the results would be Game x Region, with the region data filled in by GameRegionRelease where available. I'd want something similar to what the following would produce: SELECT * FROM gameslist_region gr CROSS JOIN gameslist_game gg LEFT JOIN gameslist_gameregionrelease grr ON gg.game_name = grr.game_id AND gr.region_name = grr.region_id; But I don't know how to express this in Django using native ORM constructs. Is this possible? I'm using Python 3.6.4 and Django 2.0.2. -
Multiple pagination in Django not working
I have 4 models: faculties, departments, studies and courses. I wanted a pagination for all the courses available and that was easy to achieve. But now I'm stuck because I wanted pagination for faculties also, that will show specific courses of the accessed faculty. The pagination will show for faculties as well, but problem is that if I try to go to the second page, it will redirect me to the second page of all courses list. Or, if I change page on all courses and then try to access a faculty, no course will show at all in the faculty. This is working: <div id="crs"> <h3>All courses</h3> <ul> {% for course in courses %} <li><a href={{ course.slug }}>{{ course.name }}</a></li> {% endfor %} </ul> <div class="pagination"> <span class="step-links"> {% if courses.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ courses.previous_page_number }}">{{ courses.previous_page_number }}</a> {% endif %} <span class="current"> Page {{ courses.number }} of {{ courses.paginator.num_pages }} </span> {% if courses.has_next %} <a href="?page={{ courses.next_page_number }}">{{ courses.next_page_number }}</a> <a href="?page={{ courses.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> </div> This is not working: <div id="fac_{{ faculty.pk }}_tab" style="display:none;"> <h3> {{ faculty.name }} Courses</h3> <ul> {% for department in faculty.department_set.all %} {% for … -
Django channels for relatively large files ~10mb, is it a good idea?
I am trying to set up an infrastructure to upload test result data, part of it should be a django application that should handle the data transfer from a different source (typically txt files around 3 to 10 mb). I am considering both the api and django channels approach, but going through the documentation of django channels I read that it is only good for interoperability and not complex applications. Api seems a safe choice but it might not be as fast as django channels which use websockets. Should django channels be used to transfer files (txt, csv etc) ~10 mb? Does it work well or should I fall back in api choice? -
Get Current Url Without Parameters in Django
I have a url like below: url(r'^board/(?P<pk>\d+)$', board_crud, name='board_update'), I want to get current view 'board' without parameters so that i can redirect to it. I want to redirect to current view(without param) in same view(with param). Thanks in Advance. -
How to apply two different mock.patches to one unit test?
When I'm trying to run this test: from unittest import mock @mock.patch('requests.get', side_effect=mocked_requests_get) @mock.patch('requests.post', side_effect=mocked_requests_post) def test_zeros(self, response): self.assertEqual(0, 0) it says TypeError: test_zeros() takes 2 positional arguments but 3 were given. So, how can I mock two different methods (I need requests.get and requests.post) in one test? -
Django restrict access to TemplateView
I'm using TemplateView to display swagger pages (local files). However, now I need to restrict access. Using a normal view, I could use @login_required mixin on the view. Is there a way to do that with TemplateViews? Or should I be using some other way of displaying these swagger pages? url(r'^swagger/', TemplateView.as_view(template_name='swagger.html'), name='swagger'), -
Django post-office: unable to open email attachement
I've written a django view that loads a number of PDF files and combines them into a .zipfile. I dont want to save the object on the server, so I am using StringIO() This is done with the following code: zip_buffer = StringIO.StringIO() summary_filename = 'summary' + str(user) + '.pdf' with zipfile.ZipFile(zip_buffer, mode='w', compression=zipfile.ZIP_DEFLATED) as zf: for file in attachements: zf.write(str(settings.MEDIA_ROOT) + '/' + str(file[0].file), file[1] + '.' + str(file[0].file).split('.')[-1]) zf.writestr(summary_filename, pdf) When I was debugging the code I had it return the object as a download in the browser through the following code response = HttpResponse(zip_buffer.getvalue(), 'application/x-zip-compressed') return response This all works as intended, when I click the button a .zip file is downloaded by the browser that contains all of the information. The problems started when I wanted to email the file as well. I am using Django post-office And intitally tried sending the email with the following command: attachment_file = zip_buffer.getvalue() send_email([requester.email], email_template context, attachments={'summary.pdf': attachment_file}) The attachement file is exactly the same as the one I supplied to the browser, yet this causes the following exception: file() argument 1 must be encoded string without NULL bytes, not str I then tried something different: send_email([requester.email], 'userprofile_summary', requester.profile.tenant, … -
Create multiple Django model instances using for loop
I have three Django models namely User, Project and Hourly. User model: which represents a standard Django user, which can start a new project. Project model: Represents a project, containing project specifc constants such as Time Zone, site latitude, site longitude, etc… Hourly model: Which represents all the hourly values (clock-time, solar time, solar hour angle, etc…) for a certain project. To simplify the problem the Hourly model has only two fields, namely project and clock_time. Eventually I would like to use fields to store these to the database. In addition I override the Project.objects.create(….) method using the ProjectManager() class. The meaning of this is that I would like to generate 8760 new hourly instances whenever a new project is created. How to implement this? At the moment every time only one Hourly object is created, whener Projects.object.create() is called. The Project and Hourly models and the ProjectManager are defined as follows: User = settings.AUTH_USER_MODEL class ProjectManager(models.Manager): """""" def create(self, owner, project_name, TMZ, lat, lon): project = super().create(owner=owner, project_name="CREATED BY PROJECTMANAGER", TMZ=TMZ, lat=lat, lon=lon) project.save() # Next I would like to delete all existing Hourly objects tied to this project hourly = Hourly.objects.filter(project=project) hourly.delete() # Next I would like to … -
Django formset , queries for relational field for every form
Models.py class Material(BaseModelClass): material = models.CharField(max_length=25, verbose_name='Material') def __str__(self): return self.material class PurOrder(BaseModelClass): order_number = models.CharField(max_length=25) class PurOrderItem(BaseModelClass): order = models.ForeignKey(PurOrder, on_delete=models.CASCADE) material = models.ForeignKey(Material, on_delete=models.PROTECT) I created a PurOrder form and PurOrderItem formset PurOrderForm = modelform_factory(PurOrder, fields=('order_number',)) PurOrderFormset = inlineformset_factory(PurOrder, PurOrderItem,fields=('material',)) Initialized them as follows. form = PurOrderForm(instance=order_instance) queryset = order_instance.purorderitem_set.all().select_related('material',) formset = PurOrderFormset(instance=order_instance, queryset=queryset) This setup costs me 22 queries if there is 20 PurOrderItem for selected purorder. 1 for PurOrder instance, 1 for PurOrderItem instance 20 for selected materials for those PurOrderItem's. Think of it, it there is 1000 PurOrderItem With the provided select_related, it add's material to PurOrderItemselect, but when it comes to display it I think, it query again. I use django-autocomplete-light, so it saves me from quering all material instances, but it keeps quering selected material, to display it even though I select_related material. Ideally, I would select PurOrder instance with prefetched purorderitem and related materials, these means 3 queries. Prefetched purorderitem's and material's will be used, when it's their turn. Please advice me a way to avoid selected choices query. Note: Caching is not an option, if possible.