Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Import Django Static File with Dynamic Name using Regex
I'm building a SPA with Django and React, but I'm relatively new to Django and can't find info on importing a static file with a dynamic name using regex. The static file is a webpack bundle in the format 'main-[hash].js' - examples: main-92e041e445bf7b737036.js and main-3583de2c3fcf00501624. Also, I realize that I can change webpack to generate bundles with static names, but that'd be no fun. -
There will get cross-domain issue when I deploy the frontend and django backend to remote server
Deploy the test environment to remote server. I use python manage.py to run the development server for django backend: python manage.py runserver 8001 and use the apache to listen the 80 port for website frontend. So, when website request the backend, there is cross-domain issue, because the port is not same. How to handle this issue correctly if in the development environment? Or if this is impossible, whether only can use distribution environment to realize it? -
Django Change Date Format from YYYY-MM-DD HH:MM to MM/DD/YYYY
I'm trying to pass input from a template to a query in my view, but if the date is not passed in Django's default date format YYYY-MM-DD then it throws an error. [u"'11/11/2012' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] template.html <form method="GET" action="/BusComm/interactions"> <div style="width: 100px; float:left"> <p>To Date:</p> </div> <div style="width: 200px; float:left"> <input type="date" Placeholder="mm-dd-yyyy" name="date_to" id="id_q" value="{{ query }}" float="right"> </div> <input type="submit" value="Submit" /> </form> View.py def interactions(request): today = datetime.now().date() table = interactionsTable(Interactions.objects.all()) if request.GET.get('date_from'): date_from = request.GET.get('date_from') table = interactionsTable(Interactions.objects.filter(date__range=[date_from, today])) return render(request, 'BusComm/interactions.html',{ 'table': table, }) The interactionsTable(Interactions.object.filter()) line is the one that throws the error. My question is how can I change the date format in Django to accept MM/DD/YYYY instead of YYYY-DD-MM? -
How to deploy the website frontend and Django backend ?
How to config the website frontend and backend ? I use Python/Django write the backend, and use html/css/js write the frontend. now I want to put the frontend and backend to the remote server (CentOS 7.2). I installed apache, in httpd.conf I config the DocumentRoot: DocumentRoot "/var/www/html/website" under the /var/www/html/website there is the website's index.html. But where I put the Django code to as the backend, and how to config it? If is in java-ee, the common practice is put the frontend and backend together, how about Django backend? How to deploy them? -
Run a Django project from VSCODE
Is there a way to run a Django project from VSCODE editor? Currently I use the windows CMD to run my project. Every time when I hit the button 'run' on VSCODE it doesn't run the project. On pyCharm we can add 'runserver' to its script parameters configurations. Is there something like that on VSCODE? Thanks. -
This is about Python window program(CRUD, DB connect). please answer
Hi I am a third year programmer. I recently started studying Python in earnest. However, programming languages such as php and JavaScript have a lot of information on the Internet, but they are not accessible to Python. So I would like to ask some people who studied Python first, so I write this. The goal is, in conclusion, to create a Windows program -CRUD (DB linked) within December by python. Is there a good example and site to learn about Python? A- Web program. 1. A good source or site about Django 2. Using Django to create a CRUD (source) 4. Other frameworks except Django. 3. CRUD web program example by direct coding. B- Windows program.(I want to create) 1. CRUD window program example through Python direct coding 2. Windows program examples for Python direct coding 3. Windows program frameworks. I am curious. Please help .. Please answer me. thank you. -
Django app in heroku deleting model objects after some time
I've written a simple django Q&A forum app and deployed it on Heroku, the local version of the site works fine. However, the production version does not store the questions, answers etc. for more than a few hours. I decided to stick with sqlite3 that comes with Django. I don't expect a lot of traffic to the site so I decided it would be worth it to keep the development db for now. site: http://immense-plateau-35286.herokuapp.com I've tried a few solutions from the DB setup page on Heroku, but have not had any success so far. Any idea what this might be? -
Unable to get data from django choice form
Hi, I'm trying to develop a simple django app, and I'm having trouble accessing a form's data. I've looked at django's documentation extensively and many questions on here on the same topic but nothing is working. Here's my code inside my view, that is otherwise working: def post(self, request): """Return only the games from the upcoming gameweek""" form = GWForm(request.POST) if form.is_valid(): curr_gw = form.cleaned_data['gweek'] args = {'form': form, 'this_gw_fixtures': Game.objects.filter(gweek=curr_gw), 'curr_gw': curr_gw} return render(request, self.template_name, args) else: curr_gw = 17 form = GWForm() args = {'form': form, 'this_gw_fixtures': Game.objects.filter(gweek=curr_gw), 'curr_gw': curr_gw} return render(request, self.template_name, args) And here's the code of my template: <form action="/predict/" method="post">{% csrf_token %} <label for="Gameweek">Gameweek: </label> <input id="gwparam" type="number" value="{{ curr_gw }}" min="17" max="40"> <input type="submit" value="Go"> </form> {% if this_gw_fixtures %} <ul> {% for game in this_gw_fixtures %} <li><a href="{% url 'predict:detail' game.id %}">{{ game }}</a></li> {% endfor %} </ul> {% else %} <p>No game predictions are available for this gameweek.</p> {% endif %} What I'm trying to do is get the input of a choice form and render a list of games that are in the gameweek selected in the form. Minumum 17, max 40. Here's my form code. class GWForm(forms.Form): gweek = … -
django model form RegexValidator error message not showing up
I'm using the class below in the models.py to restrict file uploads to certain file extensions. class ExtensionValidator(RegexValidator): def __init__(self, extensions, message=None): if not hasattr(extensions, '__iter__'): extensions = [extensions] regex = '\.(%s)$' % '|'.join(extensions) if message is None: message = 'File type not supported. Accepted types are: %s.' % ', '.join(extensions) super(ExtensionValidator, self).__init__(regex, message) def __call__(self, value): super(ExtensionValidator, self).__call__(value.name) Here is the model form where it is called: class Product(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=100) description = models.CharField(max_length=300) price = models.DecimalField(max_digits=10, decimal_places=2) url = models.CharField(max_length=200, blank=True) product_type = models.CharField(max_length=15, choices=product_types, default='choose') image = models.ImageField(upload_to='product_images', blank=True, null=True) image_url = models.CharField(max_length=200, blank=True) product_file = models.FileField(upload_to='product_files', validators=[ExtensionValidator(['jpg', 'jpeg', 'png', 'zip'])], blank=True, null=True) likes = models.IntegerField(default=0) def __str__(self): return self.name def get_absolute_url(self): return reverse('index', kwargs={}) I've tested and the functionality works, but the error message is not showing up when the user submits the form. For all forms I'm using an include - form.html below: {% load widget_tweaks %} {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} {% for field in form.visible_fields %} <div class="form-group"> … -
Exception Value: 'dict' object has no attribute 'render_context'
Environment: Request Method: GET Request URL: http://localhost:8001/accounts/000111222/edit/ ... Traceback: File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 137. response = response.render() File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/response.py" in render 103. self.content = self.rendered_content File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/response.py" in rendered_content 80. content = template.render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in render 148. return self._render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in _render 142. return self.nodelist.render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in render 844. bit = self.render_node(node, context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in render_node 858. return node.render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render 126. return compiled_parent._render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in _render 142. return self.nodelist.render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in render 844. bit = self.render_node(node, context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in render_node 858. return node.render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render 126. return compiled_parent._render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in _render 142. return self.nodelist.render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in render 844. bit = self.render_node(node, context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in render_node 858. return node.render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render 126. return compiled_parent._render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in _render 142. return self.nodelist.render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in render 844. bit = self.render_node(node, context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in render_node 858. return node.render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render 65. result = block.nodelist.render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in render 844. bit = self.render_node(node, context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in render_node 858. return node.render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render 65. result = block.nodelist.render(context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in render 844. bit = self.render_node(node, context) File "/home/infinity/.virtualenvs/test-2/local/lib/python2.7/site-packages/django/template/base.py" in render_node 858. return … -
IntegrityError: null value in column "id" for all models/fields with ForeignKey after postgres restore from dump
I'm running into issues trying to use a heroku postgres datastore from a restore of a local postgres database I have. Using the restored postgres database Django runs as normal. It retrieves all objects and uses their fields, primay key's etc without any issues. But when it comes to writing to the database, I get the same error across the board, regardless of the model(s). If it has any field that is a relationship field, I will get this error: psycopg2.IntegrityError: null value in column "id" violates not-null constraint The relationship object(s) are being passed into the .save(), .add() methods etc. and work JUST fine locally. But using this restored database, it throws this IntegrityError as if all objects in the database have null id's. I can't find anything anywhere online with a similar problem to go off of. When I reset the heroku database and create objects from a blank slate there are no problems. But if I try to do this with the restored copy, I always get this null value in column "id" violates not-null constraint .. but the object(s) WAS/WERE passed in and DID have a primary key(s)! I'm not passing in Null values, which in … -
django chat using socket: WebSocket DISCONNECT right after HANDSHAKING
Now I am trying to make chat using socket, but just this message is showing. [2017/12/08 18:51:07] WebSocket DISCONNECT /chat/prj/chat/ [127.0.0.1:55457] [2017/12/08 18:51:08] WebSocket HANDSHAKING /chat/prj/chat/ [127.0.0.1:55461] Really don't how to fix this problem. Please help me to solve this! here is my consumers.py @channel_session def ws_connect(message): try: prefix, label = message['path'].strip('/').split('/') if prefix != 'chat': log.debug('invalid ws path=%s', message['path']) return room = Room.objects.get(label=label) except ValueError: log.debug('invalid ws path=%s', message['path']) return except Room.DoesNotExist: log.debug('ws room does not exist label=%s', label) return log.debug('chat connect room=%s client=%s:%s path=%s reply_channel=%s', room.label, message['client'][0], message['client'][1], message['path'], message.reply_channel) message.reply_channel.send({"accept": True}) Group('chat-'+label, channel_layer=message.channel_layer).add(message.reply_channel) message.channel_session['room'] = room.label @channel_session def ws_receive(message): try: label = message.channel_session['room'] room = Room.objects.get(label=label) log.debug('recieved message, room exist label=%s', room.label) except KeyError: log.debug('no room in channel_session') return except Room.DoesNotExist: log.debug('recieved message, buy room does not exist label=%s', label) return try: data = json.loads(message['text']) except ValueError: log.debug("ws message isn't json text=%s", text) return if set(data.keys()) != set(('handle', 'message')): log.debug("ws message unexpected format data=%s", data) return if data: log.debug('chat message room=%s handle=%s message=%s', room.label, data['handle'], data['message']) m = room.messages.create(**data) Group('chat-'+label, channel_layer=message.channel_layer).send({'text': json.dumps(m.as_dict())}) @channel_session def ws_disconnect(message): try: label = message.channel_session['room'] room = Room.objects.get(label=label) Group('chat-'+label, channel_layer=message.channel_layer).discard(message.reply_channel) except (KeyError, Room.DoesNotExist): pass and here is chat.js $(function() { var ws_scheme = … -
Is something wrong with my slugified url paths?
I am using slugify to take the name of a university and make them into slugs. I then have them in the url paths, however it is return the page not found error Here are my urls. Project urls: from django.conf.urls import url from django.contrib import admin from django.conf.urls import include #from ads import views #from spider import views #from stats import views from listings import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.HomeView.as_view(),name='index'), # url(r'^ads/',include('ads.urls',namespace='ads')), url(r'^university/',include('listings.urls',namespace='listings')), # url(r'^spider/',include('spider.urls',namespace='spider')), # url(r'^stats/',include('stats.urls',namespace='stats')), ] app urls: from django.conf.urls import url from listings import views app_name = 'listings' urlpatterns = [ url(r'^(?P<u_slug>\w+)$',views.UniversityView.as_view(),name='university_homepage'), url(r'^(?P<university>\w+)/(?P<u_slug>\w+)$',views.ListingView.as_view(),name='listing_detail'), ] Here's the 404: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/university/temple-university Everything looks fine to but I've also been looking at this for a while so I could be overlooking something. -
Retrieve a filtered ForeignKey with Django
I have three main models, Picture, Place and PlaceRating: class Picture(models.Model): file = ImageField(max_length=500, upload_to="images) user = models.ForeignKey(User, null=True, related_name="userpictures") place = models.ForeignKey(Place, null=True, related_name='pictures') class PlaceRating(models.Model): place = models.ForeignKey(Place, null=True, related_name="placeratings") user = models.ForeignKey(User, null=True, related_name="userratings") rating = models.DecimalField(null=True, max_digits=4, decimal_places=1) class Place(models.Model): name = CharField(max_length=50) I would like to display the place's rating given by the user, together with the place's image, but I cannot manage to do that as I would need to filter the ForeignKey and Django does not seem to allow that. Example of what I would like to do: {% for picture in pictures %} <img src="{{ picture.file.url }}" class="bigpicture"> {{ picture.place.placeratings.0.rating|user:picture.user }} {% endfor %} For information, I managed to do it with templatetags, but this generates a lot of different queries to the database which I can't prefetch..: {% for picture in pictures %} <img src="{{ picture.file.url }}"> {% getplaceratingrelatedtopic picture.place.id picture.user.id %} {% endfor %} And: @register.simple_tag def getplaceratingrelatedtopic(placeid, userid): print(placeid) theplace = Place.objects.get(id=placeid) user = User.objects.get(id=userid) placerating = PlaceRating.objects.filter(author=user, place=place).last() if rating: return placerating.rating else: return "" I work with Python 2.7/Django 1.9. Any clue ? Thanks a lot! -
Django imagefield can't assign via ModelForm
I'm creating new Contact instance and after contact = contact_form.save(commit=False) in cleaned_data['avatar'] i saw default avatar path, but in form i set another pic. Why is this happening? Contact model: class Contact(models.Model): first_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) note = models.TextField(max_length=280, blank=True) avatar = models.ImageField(upload_to=generate_upload_to_path, default='/contacts/default_icon.png', blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None) Contact ModelForm: class ContactForm(forms.ModelForm): prefix = 'contact' class Meta: model = Contact exclude = ('user',) def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.fields['last_name'].widget.attrs['placeholder'] = 'Last name' self.fields['first_name'].widget.attrs['placeholder'] = 'First name' self.fields['avatar'].widget.attrs['placeholder'] = 'Avatar' views.py def index(request): if request.user.is_authenticated: if request.method == 'POST': contact_form = ContactForm(request.POST) phone_number_form = PhoneNumberForm(request.POST) email_form = EmailForm(request.POST) if contact_form.is_valid() and phone_number_form.is_valid() and email_form.is_valid(): contact = contact_form.save(commit=False) contact.user = User.objects.get(pk=request.user.pk) contact.save() phone_number = phone_number_form.save(commit=False) phone_number.contact = contact phone_number.save() email = email_form.save(commit=False) email.contact = contact email.save() return redirect('contacts:index') -
Webpack unnable to bundle due to SyntaxError
I was interested in learning Django + ReactJS on Windows, so I followed this step by step tutorial. Now, I'm on the bundling stage. When I run my bundler as a quick sanity check: $ node_modules/.bin/webpack --config webpack.dev.config.js I got node_modules is not recognized as a windows command. After trying different solutions, I found that using the node command in front of the webpack command was executing webpack. Doing that seems to launch webpack but I'm getting this error: $ node node_modules/.bin/webpack --config webpack.dev.config.js \node_modules\.bin\webpack:2 basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") ^^^^^^^ SyntaxError: missing ) after argument list at createScript (vm.js:80:10) at Object.runInThisContext (vm.js:139:10) at Module._compile (module.js:599:28) at Object.Module._extensions..js (module.js:646:10) at Module.load (module.js:554:32) at tryModuleLoad (module.js:497:12) at Function.Module._load (module.js:489:3) at Function.Module.runMain (module.js:676:10) at startup (bootstrap_node.js:187:16) at bootstrap_node.js:608:3 Could this be an error due to package.json? -
Django project folder doesn’t push to gitlab
When i try to push my Django project into my gitlab repository it, all the files gets pushed properly except for the project folder it gets uploaded with a remove icon and text next to it that looks like that: @ it 1080bae7 -
Django running custom Python Script
I'm working on my first Django application and I'm having trouble running a custom python script. I created an application named awardnominee and updated the model.py to create an AwardNominee. I also create a directory management/commands/ inside I added a script named addawarddata.py. Whenever I run the command python3 manage.py addawarddata I receive an error ModuleNotFoundError: No module named 'awardnominee.management.conferencesite' The issue is with my import statement from conferencesite.mysite.awardnominee.models import AwardNominee. If I path to reference my model local using the both options I receive the respective errors. from ....awardnominee.models import AwardNominee ValueError: attempted relative import beyond top-level package or from ....awardnominee.models import AwardNominee ModuleNotFoundError: No module named 'awardnominee.management.awardnominee' lastly from awardnominee.models import AwardNominee attributeError: module 'awardnominee.management.commands.addawarddata' has no attribute 'Command' I have posted my code below. Any help would be appreciated. models.py from django.db import models # Create your models here. class AwardNominee(models.Model): nominee_name = models.CharField(max_length=200) nominee_desc = models.CharField(max_length=200) # my nominee photos streamed from urls nominee_img_src = models.CharField(max_length=200) nominee_votes = models.IntegerField(default=0) aaddawarddata.py # from conferencesite.mysite.awardnominee.models import AwardNominee from awardnominee.models import AwardNominee nominee1 = AwardNominee( nominee_name="Team 1's app", nominee_desc="Team 1 created an Android mobile application for pets.", nominee_img_src="https://images.unsplash.com/photo-1490222939321-2a267366a124?auto=format&fit=" "crop&w=1050&q=60&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D", nominee_votes=0) nominee1.save() nominee2 = AwardNominee( nominee_name="Team 2's app", nominee_desc="Team 2 … -
Django Rest Framework: get_FOO_display in serializer not letting me POST
I recently added a source='get_fieldname_display to my serializer. It worked perfectly for the purpose of obtaining the display value of a choices tuple but now I can no longer POST data using the API end point without getting an error: TypeError: 'get_fieldname_display' is an invalid keyword argument for this function To be clear, the addition to the serializer was this line specifically: fieldName = serializers.CharField(source='fieldName_display') I know that this line is causing the problem because when I comment it out, I can POST data without a problem. However, I need this line in there so I may obtain the display names from the choices tuple when I am GETting data. I think the problem may be remedied if I use two different serializers, one for GET and another for POST, but I am not sure how to go about doing this--I am using a generics.ListCreateAPIView in my views.py. -
Django/Bootstrap RadioButtom Rendered appears to be disabled
I am using Django1.8.6 along with django-bootstrap3. This is my model for companies to set there program status and privacy class CompanyInformationSetting(models.Model): PROGRAM_PRIVACY = ( ('private', 'Private'), ('public', 'Public') ) PROGRAM_STATUS = ( ('active', 'Active'), ('Inactive', 'Inactive') ) program_privacy = models.CharField(max_length=30, choices=PROGRAM_PRIVACY, default='public') program_status = models.CharField(max_length=30, choices=PROGRAM_STATUS, default='Inactive') company_user = models.OneToOneField(User) twitter_handle = models.URLField(max_length=250, blank=True) blog_or_website_url = models.URLField(max_length=250, blank=True) about_or_tagline = models.TextField(max_length=500, blank=True) and this is the form I am using so that user can change the values accordingly. class CompanyInformationSettingForm(forms.ModelForm): program_privacy = forms.ChoiceField(choices=CompanyInformationSetting.PROGRAM_PRIVACY, widget=forms.RadioSelect()) program_status = forms.ChoiceField(choices=CompanyInformationSetting.PROGRAM_STATUS, widget=forms.RadioSelect()) twitter_handle = forms.URLField(max_length=250, widget=forms.TextInput(attrs={'placeholder': 'www.twitter.com/123456'} ) ) blog_or_website_url = forms.URLField(max_length=250, widget=forms.TextInput(attrs={'placeholder': 'www.example.com/123'} ) ) about_or_tagline = forms.CharField(max_length=100, widget=forms.TextInput(attrs={ 'placeholder': 'Give us your TagLine which tell us about you' } ) ) class Meta: model = CompanyInformationSetting fields = ('program_privacy', 'program_status', 'twitter_handle', 'blog_or_website_url', 'about_or_tagline') and render the form in my template using django-bootstrap3 template tags like this <form class="" role="form" action="" method="post"> {% csrf_token %} {% bootstrap_form company_information_setting_form %} <div class="row m-t-20 m-b-10"> <div class="col-lg-12"> <div class="pull-left"> <button class="btn btn-complete" type="button" id="previous_policy">Previous Policy</button> </div> <div class="pull-right"> {% buttons %} <button class="btn btn-complete" type="submit" >Save</button> {% endbuttons %} </form> However when I run my server the form which is rendered appears that radioselection … -
Django-Rest-Auth Reset Password via email
I'm attempting to implement a Forgot Password button, utilizing the url /rest_auth/pasword/reset. My assumption, from reading the docs on this endpoint, is that you only need to pass an email to the endpoint, and then the reset email will be sent, prompting the user to reset their password. The issue is, this flow only works when the user is actually logged in, thus when the session has a valid token key to send back to the server. If the user forgets their password, they obviously won't be logged in, and thus won't have a token to send back to the server. This is the error I get when trying to post to the endpoint with just the email and no token header. {"detail":"Invalid token header. No credentials provided."} I didn't think that we should need to include a token in the header because that defeats the purpose. Am I misunderstanding how this endpoint is supposed to be used? -
Django seems to be using incorrect settings module
Something strange has happened in my django app and I can't seem to trace it back to a particular change. Whenever I run python manage.py runserver, I get this error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. My settings module is configured properly -- I have DEBUG=True and I have also set ALLOWED_HOSTS. I continued to investigate and it seems like somehow, Django has decided to import the wrong settings module. When I do from django.conf import settings and I print settings.__dict__, I see this: {'LANGUAGE_CODE': 'en-us', 'LOGGING': {}, 'DEBUG': False, 'USE_I18N': True, 'INSTALLED_APPS': ('django_nose',), 'FORCE_SCRIPT_NAME': None, 'LOGGING_CONFIG': 'logging.config.dictConfig', '_wrapped': <Settings "django.conf.global_settings">} It seems like DJANGO_SETTINGS_MODULE is somehow being set to django.conf.global_settings. I've tried to override this by settings os.environ['DJANGO_SETTINGS_MODULE'] explicitly in manage.py, but this doesn't seem to fix anything (though the env. variable does appear to be set properly after this). However, I still get the same bizarre value for my settings file. I've also tried uninstalling django-nose, thinking that this might be the culprit (as it seems to be the only app installed in this bizarre settings file). But that didn't seem to change anything. -
Django Commenting system
I'm making an answering/commenting system for my post's. And here's how the models.py looks: from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.utils import timezone import misaka from groups.models import Group from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name="posts") created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name="posts",null=True, blank=True) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse( "posts:single", kwargs={ "username": self.user.username, "pk": self.pk } ) class Meta: ordering = ["-created_at"] unique_together = ["user", "message"] class Answer(models.Model): post = models.ForeignKey('posts.Post', related_name='posts') author = models.ForeignKey(User, related_name='answers') answer = models.TextField() create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.answer def get_absolute_url(self): return reverse('post_detail', kwargs={ "username": self.user.username, "pk": self.pk, }) I've been having a problem, with basically showing the answers/comment's in the post detail. Here's how my post detail looks: <!DOCTYPE html> {%load staticfiles%} <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="keywords" content="footer, address, phone, icons" /> <link href="https://fonts.googleapis.com/css?family=Abel|Raleway|Signika|Signika+Negative" rel="stylesheet"> <title>Ask Uptown</title> <style media="screen"> .logo-text span{ color: #5383d3; } .backgr{ background-color: #7F7F7F; height: 13vh; width: 100%; background-size: … -
Slow database operation Django filter
I have to filter through a model that has around 24 mil. instances (records). I need to filter them based on some name got from the url kwarg, I have something like this: Model.objects.filter(field__icontains=self.kwargs['kwarg']).values() on a view. This is absolutely not efficient since the page is really slow and takes a lot of proccessing from the CPU. How can I solve this issue? Thanks in advance for answers! -
Django's HttpResponseRedirect not visible by proxy system
I have Django web application and route all requests to this web app via reverse proxy (Netflix Zuul). One of view classes in Django returns HttpResponseRedirect("/"), but this redirect does not visible by routing system (by Netflix Zuul). Is it possible somehow to setup Django web app so all redirections (status codes 301 and 302) will be visible by proxy system? Or should I setup routing system for that? Please explain this behavior. Reproduction steps I launched Django web app on localhost:8000. When in browser I want to point to view class that has redirection: "localhost:8000/list", then browser's developer tool displays two requests: first with status code 302 and second with 200, and after redirection link looks like "localhost:8000/". first request: * Request URL:http://localhost:8000/list * Request Method:GET * Status Code:302 FOUND * Remote Address:127.0.0.1:8000 and response headers contain: Location:http://localhost:8000/ second request: * Request URL:http://localhost:8000/ * Request Method:GET * Status Code:200 OK * Remote Address:127.0.0.1:8000 After that I applied proxy system and launched it on localhost:8080 (routing redirects all requests to localhost:8000). When searching in browser by "localhost:8080/list", browser's developer tool displays only a single request and still stays on the same link (but I need link changed to "localhost:8080/") * …