Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make popular feed - the posts which has the most likes and created recently
I want to implement 'Popular' Feed. I want to show the series of posts which has the likes the most. Here is abstract model schema. (Model) Like user = User content_type = Post, User, Group object_id = 22 (Model) Post user = User content = '' created_at = '12082017' In views.py, I want to get sorted queryset like, Post.objects.order_by('-like')[:30] Since my Post model doesn't have like field, I can't use order_by. I'm thinking about adding score field to track of likes and current time since then. Do you think it will work? :) Also any thought or advice on how to make popular feed will be highly appreciated. Thank you -
How to Update/Refresh Scrolling Texts in html (as they are scrolling)
I'm working with Django, and I'm trying to create a horizontally scrolling text that is updated every few seconds. The code I got so far is (including some I gathered from other posts): index.html <script> $(document).ready(function() { $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh var my_refresh = setInterval(function() { $('#updateBox').load("{% url 'updateBox' %}"); }, 1000); }); </script> .... .... <div id="updateBox"> {% include "updateBox.html" %} </div> updateBox.html <marquee behavior="scroll" direction="left"> {{updateText_1}} ; {{updateText_2}} ; {{updateText_3}} </marquee> views.py def getNewTexts(parms): (updateText_1,updateText_2,updateText_3) = someAPIwrapper.(parms) return (updateText_1,updateText_2,updateText_3) def index(request): return render(request, 'index.html' ) def updateBox(request): (updateText_1,updateText_2,updateText_3) = getNewTexts(parms) return render(request, 'updateBox.html', {'updateText_1': updateText_1, 'updateText_2':updateText_2,'updateText_3':updateText_3}) Now these codes so far results in this: The texts get correct values upon loading index page, starts scrolling, but right after it starts scrolling for 1 second (1000ms as specified in the script), the whole division "updateBox" gets refreshed and reloaded, and the texts starts scrolling from the very right-hand-side again. The result is that, only half of {{updateText_1}} ever gets shown. Ideally, I would want to find a solution to only update the texts {{updateText_1}} ; {{updateText_2}} ; {{updateText_3}} without … -
Why the group do not shows its users(it contains the test02) in user_set?
I have a user test02, and you can see there is 售后组 group in its groups: { "id": 3, "account": null, "last_login": null, "username": "test02", ... "is_admin": false, "is_staff": false, "is_superuser": false, "status": "1", "groups": [ { "id": 3, "name": "售后组", "permissions": [ 13 ] } ], "user_permissions": [] } But when I use group.user_set to check the group's users, it shows None. try: group = Group.objects.get(pk=group_id) # there I get `售后组 group` users = group.user_set for user in users: message = Message.objects.create( title = title, content = content, create_user = create_user, ) message.save() message.receive_user.add(user) except Exception as e: raise e Why the 售后组 group do not shows its users(it contains the test02)? -
Django from .models import is not working
I am working on development project using Django an PyCharm as Editor. I have defined the database structure in the models.py file of the app called empresas models.py I am trying to access the database called datosEmp with and from .models import datosEmp. I have tried several options such as: from .models import datosEmp from empresas.models import datosEmp from ..models import datosEmp import empresas.models views.py None of the used options are working for accesing datosEmp. I already defined the directory of the app as Source root, and also tried to use different python interpreter version The structure of my app: Structure of My app Any help will be very much appreciated -
"<Message: title>" needs to have a value for field "id" before this many-to-many relationship can be used.
I have a Message model, And in it I have create_user ForeignKey and receive_user ManyToManyField: class Message(models.Model): """ 消息 """ message_num = models.CharField(default=getMessageNum, max_length=16, help_text="消息") # 注意:message_num 相同,说明是同一次发送 title = models.CharField(max_length=64, help_text="消息名称") content = models.CharField(max_length=1024, help_text="消息内容") create_user = models.ForeignKey(User, related_name="created_messages",help_text="创建者") receive_user = models.ManyToManyField(User, related_name="received_messages", help_text="接受者") def __str__(self): return self.title def __unicode__(self): return self.title When I use the bellow to save a message, I except a exception: try: receive_user = User.objects.get(id=user_id) message = Message.objects.create( title=title, content=content, create_user=create_user, receive_user=receive_user, ) message.save() except Exception as e: raise e I get the exception: "<Message: title>" needs to have a value for field "id" before this many-to-many relationship can be used. How to resolve this issue? some friend can help me about this? -
Saving file to disk sent from React-Redux front-end to Django (DRF) back-end
From what I can tell this is mostly working; however, I sort of stumped as to how to actually save the file to disk in a specific location. Been re-reading the documentation and not really getting anywhere as the examples primarily use Django forms, which I am not using. https://docs.djangoproject.com/en/1.11/topics/files/ https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/ Not faring much better with Googling "django save uploaded file to disk", its variations, and reviewing the various SO related questions. Anyway, so the POST itself is going through and status code 200 with this in the request payload: ------WebKitFormBoundarym8pSNA7EDqtcyJC0 Content-Disposition: form-data; name="file" [object File] ------WebKitFormBoundarym8pSNA7EDqtcyJC0-- I also a print(request.data) just to see that it is making its way to the views.py which it seems to be as it prints the following in the console: <QueryDict: {'file': ['[object File]']}> Just not sure where to go from there and not finding it clear in the documentation since it is using Django Forms. Here is React submitDocument action: import axios from 'axios'; import { push } from 'react-router-redux'; import { ROOT_URL } from '../../config/config.json'; // Establish the different types export const DOCUMENTS = 'documents'; export function submitDocument(files) { var formData = new FormData(); formData.append('file', files) return function(dispatch) { axios .post( `${ROOT_URL}/api/documents/fileupload`, … -
Is there a maximum length for django request URL?
I was trying to send a get request to django beackend which encodes a list of ids that I need. I noticed that when this list of id(string) goes too long, the django will not handle this request. I can see the request in the django test server, but it never actually enter any view. In the browser, nginx gives me 404. URL: "/xxx/xxx/xxx?type=xxx&ids=4918230_25808605%2C4996758_49144848%2C5121093_43940616%2C56944804_40780188...." I know I can maybe use post to encode params in the body instead, but I just want to find out the reason behind this. -
Is Celery needed for asynchronous file writing functionality in Django?
I'm planning to add some functionality to my Django app that will write a row of data to a csv file when certain views are called: session_dict = collectUserDataFromRequest(request) #....collect parameters from request if os.path.isfile(filename): with open(filename, 'a') as csv_file: a = csv.DictWriter(csv_file,session_dict.keys()) a.writerow(session_dict) csv_file.close() else: with open(filename, 'w') as csv_file: w = csv.DictWriter(csv_file,session_dict.keys()) w.writeheader() w.writerow(session_dict) csv_file.close() # then proceed to render the html A problem I am facing is dealing with potential race conditions when multiple users are accessing my app at the same time. While the data can be added to the csv file in any order, I don't want some user's to wait longer for a view to load while waiting for a lock to be released on the csv file. As such, I think an Asynchronous queue of string data to be written to the file that can run in the background sounds like a good workaround. I have been told that Celery is a good framework for adding asynchronous processes to my Django app. But looking through several tutorials, I am seeing that additional frameworks such as Redis are usually required. I worry that this may be overkill for what I aim to accomplish. Will … -
Solr nested documents vs. grouping/field collapse (via Django Haystack)
I'm working on a website that's running Django with Solr as it search backend. Haystack functions as Django's interface to Solr. I currently have one Solr collection, Apps. Apps each have multiple releases, but in Solr they manifest as one (most recent) release per app. I've come up against a limitation for that architecture: I need to be able to search all of an app's releases and return the most relevant one. Example data in Django ORM: App Foo - Release A - released Nov 2017, compatible with Linux - Release B - released April 2017, compatible with Windows Example search in Solr: Give me all the apps with a release that's compatible with Windows Expected: App Foo is returned. Actual: App Foo is not returned because we're only storing Release A's metadata in the App Foo document in Solr. A solution I'm pursuing is to index Solr based on Release rather than App. But when we do that, how do we use Solr/Haystack to return only the most recent release that matches the query? It seems like Result Grouping / Field Collapsing might solve the problem: http://yonik.com/solr-result-grouping-field-collapsing/ But does Haystack support it? If not, is there a way to … -
Is there a better way to make this queryset using Q? django
I have a query which uses filter but I know there is this thing called Q but trying to play around with it, I am not sure how I can use Q. I am not sure which one would be better but trying to know another way to do the query. What I actually want to do is... for my queryset return I have a default field and two input fields which are options. let's say, language in default is english, there is a location and title field. If location and title fields are available, make a query to query location, title, and language. If only location then only query location and language, if only title then only query title and language. I have done it two ways, one with filter only which has less code... postings = Posting.objects.filter(language='EN') if kwargs.get('title'): postings = postings.filter(title__icontains=kwargs.get('title')) if kwargs.get('location'): postings = postings.filter(location__icontains=kwargs.get('location')) the above does work with using only filter I am trying to see if I can do it with using Q but cannot seem to make it work I have something like this at the moment if title and location: postings = Posting.objects.filter(title__icontains=title, location__icontains=location, language='EN') else: queryQ = Q(posting_language='EN') if title: … -
Django - Trying to a field that is not in the form but is in the model
Right now I have a model.form with one field nothing more, but the model has 3 fields(see reference down below) and 1 of them set by the form, one has a default to false as it should be and the last one I will set in the view but it won't correctly do it and idk why. Model & Form. class TeamMembership(models.Model): user = models.ForeignKey(User) team = models.ForeignKey(Team) leader = models.BooleanField(default=False) class TeamSettings_acceptForm(forms.ModelForm): class Meta: model = TeamMembership fields = ('user',) View @login_required def teamsettings_accept_applications(request, team_pk): if request.method == 'POST': logged_in_user = get_object_or_404(User, pk=request.user.pk) requested_team = get_object_or_404(Team, pk=team_pk) for member in requested_team.teammembership_set.all().order_by('-leader'): if member.user.pk == request.user.pk and member.leader: formaccept = TeamSettings_acceptForm(request.POST) accepteduserid = formaccept.data['user'] teamapplications = TeamApplication.objects.all().filter(from_user=accepteduserid).count() if teamapplications > 1: messages.success(request, "Error") return redirect('teamsettings_applications', team_pk=team_pk) else: if formaccept.is_valid(): teamapplications = TeamApplication.objects.all().filter(from_user=accepteduserid) teamapplications.update(accepted=True) formaccept.team = requested_team.pk formaccept.save() messages.success(request, "User has now been added to your team!") return redirect('teamsettings_applications', team_pk=team_pk) it should create a new row with that data and update the others. All I get in return from Django is staff_teammembership.team_id may not be NULL -
Test results of POST in django custom admin actions django 1.11
I am still very, very new to python and django, so please forgive my ignorance: I am trying to write a test for my custom admin action and the custom action appears to be working, but the test is still failing. I am missing something. I tried to apply the answers from this post: Testing custom admin actions in django The objects are being created correctly, and they have primary keys, but the changes are still not being reflected after I post to the action. If I run the tests I get a test failed: AssertionError: Response should not contain 'unable to find match for' Despite this, when I run the code and manually test it, the changes all work perfectly. Thanks in advance! admin.py def autodetect_manager(modeladmin, request, queryset): employees_to_update = queryset message_container = 'Manager auto-detection results: ' for e in employees_to_update: new_manager = get_manager_from_manager_email(e.manager_email) if new_manager is not None: Employee.objects.filter(pk=e.pk).update(manager=new_manager, manager_email='') else: message_container += 'unable to find match for: ' + e.first_name + ' ' + e.last_name + ' ** ' messages.add_message(request, messages.INFO, message_container) autodetect_manager.short_description = "attempt to automatically detect manager based on email address entered" def get_manager_from_manager_email(manager_email): return Employee.objects.filter(email_address=manager_email).filter(is_manager=True).filter(is_active=True).first() tests.py def test_autodetect_manager(self): # Test manager auto detect """ … -
CSRF token missing or incorrect when trying to upload a file with ajax
I have a file upload form in html with which I'm trying to upload a file(and file size to display) via ajax call. I'm using django. Here's the upload form: <form class="uploadForm" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" id="uploadFile"> <input type="submit" class="button" id="uploadButton" value="Upload"> </form> Here's my Jquery + Ajax: $('.uploadForm').on('submit', function(event){ event.preventDefault(); var fileSize = ($('#uploadFile')[0].files[0].size/1024); var fileName = $('#uploadFile')[0].files[0].name; var realSize = sizeConverter(fileSize); var fileData = new FormData($('#uploadFile').get(0)); $.ajax({ url: '{% url 'project:uploadFile' %}', type: 'post', data: { 'uploadedFile': fileData, 'fileSize': realSize, csrfmiddlewaretoken: '{{ csrf_token }}' }, cache: false, processData: false, contentType: false, success: function(data){ alert(data); } }); }); And in views.py I have this: class uploadFile(TemplateView): template_name = "project/uploadFile.html" def post(self, request): fileSize = request.POST.get('fileSize') return JsonResponse(fileSize, safe=False) With the above code I get Forbidden (CSRF token missing or incorrect.) error. I googled this and someone here suggested removing processData and ProcessType. When I remove those two parameters absolutely nothing happens when I submit the form(nothing in the console neither). What could be wrong with this? Thanks. -
Django can't find settings module
I'm trying to migrate my Django project "Sales Tracker", but python manage.py migrate, but when I do I get this error message: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) When I looked in the Sales Tracker folder though, the settings.py file is there. Why isn't it being recognized? -
How to create users with different fields?
Currently using the custom created user as its Django recommended way to handle users for projects. class CustomUser(AbstractUser): pass -
Save calculated value as a model field
As a follow up to my eariler question I have a new one. How can I save this calculated value as a model field. I would like to use it in my views and templates to order list by this field. My models: class Tournament(models.Model): name = models.CharField(max_length=100) date = models.DateTimeField('date') player_num = models.IntegerField(verbose_name="") points = models.FloatField(default=1000.00) def get_rating(self): return self.points / 1000.00 class TournamentStandings(models.Model): tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) player = models.ForeignKey(Player, on_delete=models.CASCADE) player_place = models.FloatField(verbose_name=u"") player_points = models.FloatField(verbose_name="", blank=True) #added for testing to save the calculated value in it @property def player_points(self, obj): return obj.tournament.player_num * obj.tournament.get_rating() - obj.tournament.get_rating()*(obj.player_place - 1.00) def save(self, *args, **kwargs): self.player_points = self.get_player_points super(TournamentStandings, self).save(*args, **kwargs) def __float__(self): return self.player_points Funny as on the admin list I have a column where player_points are calculated correctly but when I add a new model instance and try to save it I get this error : 'TournamentStandings' object has no attribute 'get_player_points'. Is it bacause I am trying to do a "self" save and my calculation is (self, obj) ?? Any hints are wellcome. -
Override django change_form.html template when a third app is overriding it
I am trying to override change_form.html only for one model, so I did as explained in the django documentation and created /templates/my_app_name/my_model_name/change_form.html. The problem is, it is not working and I am not seeing the extra features that I have added to the change_form template. I am using django_guardian, which also overrides the same template, so my assumption is that this is causing the issue. It is worth mentioning, that before placing the template in the my_app_name/my_model_name/ folder, the features of both templates were visible in the admin interface. Is there a way to apply this only for 1 model? -
How validate initial values in a Django formset
I am developing an application which where the user to uploads a text based data file (CSV), validates the data file, and displays the data in a form with any error messages so that the user can correct the errors and then commit the data to the DB. I'd like to have the Formset (which displays the records) validate the initial data but I can't seem to get the formset to indicate that it is bound and thus validate (everything displays OK just can't get it to validate). Any advice on how I can pull this off? I've poked around this site and seen a lot of discussion that comes close to answering my question but haven't quite found the solution yet. Thanks in advance! Here's my form code: class BasePITReleaseFormset(BaseFormSet): def clean(): #haven't gotten to coding this part yet return super().clean() class PITReleaseFormsetHelper(FormHelper): def __init__(self, *args, **kwargs): super(PITReleaseFormsetHelper, self).__init__(*args, **kwargs) self.form_method= 'post' self.layout = Layout( 'field1', 'field2', ... 'field9') self.render_required_fields = True Here's my view: class ReleaseGroupLoaderView(View): file_upload_action = #some action template_name = #some template PITReleaseFormset = formset_factory(PITReleaseForm, BasePITReleaseFormset, extra=0) rel_formset_helper = PITReleaseFormsetHelper() rel_formset_helper.template = 'bootstrap/table_inline_formset.html' #this post is called when the user uploads the data file def post(self, … -
Django Formview Won't Validate
Django newbie here. I recently implemented a simple search with Django. I user specifies data in search bar, search is executed. I was able to determine today how to get the search to be null if user clicks on empty search bar. What I'm really trying to accomplish is to implement error logic so that the user has to specify data in the search bar. This has been very straight forward with all of the other views, but the search is a bit trickier, for me anyway. I have done several SO searches today, and determined that my HTML get method is ok for a search, but it may be causing some problems with the FORMVIEW that I am using. I have also tried to override POST and GET for the FORMVIEW, but can't seem to get it to work. I want to stick with CLASS BASED VIEWS, so I am using FORMVIEW. Here is my code.... My HTML <form method="GET" autocomplete=off action="{% url 'Book:book_request_search_results' %}" > <div> <h1 class="title">Book Request Search</h1> </div> {{ form.non_field.errors }} <div class="section"> <input type="search" class="name2" name="q"> </div> <div class="section"> <input type="submit" id="" class="submit6" value="Search"> </div> My VIEWS.PY class BookRequestSearchView(LoginRequiredMixin,FormView): form_class = BookRequestSearch template_name = … -
Correct structure for a Django application and handling the views and sub views
I struggle a bit in order to understand how a Django Application should be properly structured. In particular, I struggle to get my head around the views. So I have this file base.html And I know that this file will have common elements of the whole application such as footer, navbar, head etc. So far so good. Inside my base.html file I will have the tag: {% block content %} {% endblock %} Which handles the dynamic content of the application. Now I create a static page called home.html and inside that file I put {% extends 'base.html' %} ... Whatever I want {% block content %} And now comes the part that I really struggle to understand how it works. I create a new app called dashboard. I create a dashboard.html file and similarly to home.html I extend the base, and but elements inside the content block. In the views.py of the generated application I define: @login_required(login_url="login/") def dashboard(request): return render(request, "dashboard.html") and the dashboard.html {% extends 'base.html' %} {% block content %} <div class="dashboard-page"> <div class="row equal-sides"> <div class="col-sm-2 trim-right"> {% include 'dashboard_navigation.html' %} </div> <div class="col-sm-10 trim-left"> <div class="dashboard-main card"> <h3>Welcome to your dashboard</h3> </div> </div> </div> … -
Django - ValueError: too many values to unpack (expected 2)
I try to use make a droplist from model. USER_TYPE = { 'admin': "Admin", 'patient': "Patient", 'helper': "Helper", 'therapist': "Therapist", } class User(AbstractBaseUser): user_type = models.CharField(max_length=10, choices=USER_TYPE, default="patient") However, I get this error: ValueError: too many values to unpack (expected 2) Thanks in advance! -
I can't set labels in Django forms fields
This is my model: class CalEvents(models.Model): user = models.ForeignKey(User) activity_name = models.CharField(max_length=256, unique=False, blank=True) activity_type = models.CharField(max_length=30, unique=False, blank=True) activity_code = models.CharField(max_length=30, unique=False, blank=True) def __str__(self): return "Activity: '{}' - @{}".format(self.activity_name, self.user.username) This is my forms.py (with my attempted solutions to define the labels): from django.forms import ModelForm from gCalData.models import CalEvents from accounts.models import User class CalEventsForm(ModelForm): class Meta: model = CalEvents fields = ['activity_name','activity_type','activity_code'] labels = {"actiity_name": "Activity name", "activity_type": "Activity type", "activity_code": "Activity code"} def __init__(self, *args, **kwargs): super(CalEventsForm, self).__init__(*args, **kwargs) self.fields['activity_name'].label = "Activity name" self.fields['activity_type'].label = "Activity type" self.fields['activity_code'].label = "Activity code" This is the part of my template where I put the form: <tr> <form method="POST"> {% csrf_token %} {% for field in form %} <td>{{ field }}</td> {% endfor %} <td><input type="submit" name="new_record" class="btn btn-primary" value="Add Activity"></td> </form> </tr> What am I doing wrong? -
Detect table cell change on user edit
I'm trying to detect html table cell change on user input. When I click on table cell I can type text in it, but my .change function is not triggered. However on page load when data are populated from database, for every table cell change change function is fired. I can not figure why. Can you help. My code below: <div id="table" class="table-editable"> <table id="myTable" style="width:100%" class="table"> <tr> <th>Id</th> <th>Link</th> <th>Naslov</th> <th>Lokacija</th> <th>Cijena</th> <th>Telefon</th> <th>Posjet</th> <th>Opis</th> <th>Prednosti</th> <th>Nedostaci</th> <th>Slike</th> <th>Select</th> {% for entry in entries %} </tr> <tr> <td>{{ forloop.counter }}</td> <td><a id="linkHouse_{{ forloop.counter }}" href="{{ entry.link }}">Link na oglas</a></td> <td contenteditable="true">{{ entry.header }}</td> <td contenteditable="true">{{ entry.location }}</td> <td id="priceHouse_{{ forloop.counter }}" contenteditable="true">{{ entry.price }}</td> <td id="contactHouse_{{ forloop.counter }}" contenteditable="true">{{ entry.contacts }}</td> <td id="visitedHouse_{{ forloop.counter }}" contenteditable="true">{{ entry.visited }}</td> <td id="descriptionHouse_{{ forloop.counter }}" contenteditable="true">{% for line in entry.description.splitlines %} {{line}}<br> {% endfor %}</td> <td id="prosHouse_{{ forloop.counter }}" contenteditable="true" >{% for line in entry.pros.splitlines %} {{line}}<br> {% endfor %}</td> <td id="consHouse_{{ forloop.counter }}"contenteditable="true">{% for line in entry.cons.splitlines %} {{line}}<br> {% endfor %}</td> <td > <a class="fancybox" target="_blank" data-fancybox="images" href="{% static "Pic/img_fjords_wide.jpg" %}"><img src="{% static "Pic/img_fjords_wide.jpg" %}" alt="" style="width:150px"></a> <a class="hide fancybox" target="_blank" data-fancybox="images" href="{% static "Pic/img_lights_wide.jpg" %}"><img src="{% static "Pic/img_lights_wide.jpg" %}" … -
How to solve this `ImportError: Cannot import name url` in Django 2.0?
Okay I am following this https://tutorial.djangogirls.org/en/django_urls/ tutorial. And when I run the code python manage.py runserver I get the following error: Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7faf45be1d08> Traceback (most recent call last): File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check for pattern in self.url_patterns: File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/piyush/.virtualenvs/myenv/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/piyush/Desktop/Djangosite/mysite/urls.py", line … -
Django issuing extra GET request
I recently noticed that every page I navigate to in my app automatically issues a second GET request. Doesn't matter if the initial request is GET or POST. I've spent all day digging around the web, and came across this question. It's the same issue, but I've done all of the solutions suggested in the responses (make a blank template, APPEND_SLASH=False, take out all tags to load resources, no link rel="shortcut icon" in my templates), and I still get the double request. Here is the output from my log with the requests for a page that is just a blank template: "GET /app/norepeat/ HTTP/1.1" 200 89 Not Found: /favicon.ico "GET /favicon.ico HTTP/1.1" 404 4719 "GET /app/norepeat/ HTTP/1.1" 200 89 And here is the view for that URL: def norepeat(request): return render(request, 'norepeat.html') And norepeat.html is a blank html file. Any ideas what is going on here? I know that this doesn't really affect my app's functionality, but I would rather that my server doesn't get hit with double the requests when my app is in production. Thanks!