Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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/") * … -
How can I upgrade heroku plan on Heroku?
I am going to upgrate plan on Heroku with my Django app from hobby-dev to hobby-basic. At the moment heroku pg:info returns: Plan: Hobby-dev Status: Available Connections: 0/20 PG Version: 9.6.4 Created: 2017-11-12 19:20 UTC Data Size: 135.9 MB Tables: 19 Rows: 1272760/10000 (Above limits, access disruption imminent) Fork/Follow: Unsupported Rollback: Unsupported Continuous Protection: Off Add-on: postgresql- ... I tried to use Upgrading Heroku Postgres Databases but I am not sure which way should I choose. It seems to be that pg:copy would be the best idea? I think that steps in this case should look as shown below, am I right? 1.heroku addons:create heroku-postgresql:standard-0 2.heroku pg:wait 3.heroku maintenance:on 4.heroku pg:copy DATABASE_URL HEROKU_POSTGRESQL_PINK --app sushi How can I check DATABASE_URL and HEROKU_POSTGRESQL_PINK? I quess that DATABASE_URL is in Config Vars and this is it postgres://gxapb...2840@ec2-77-131-196-1207.compute-1.amazonaws.com:5432/d...md, isn't it? But how can I generate HEROKU_POSTGRESQL_PINK? I found information that it is the target database. 5.heroku pg:promote HEROKU_POSTGRESQL_PINK 6.heroku maintenance:off -
Ajax + Django Like button
I have problems while I am building a simple like button. I have done everything as I have read in different tutorial but when I click on the Like button, it does not do anything. Look: models.py class Comentario (models.Model): titulo = models.CharField(max_length=50) texto = models.CharField(max_length=200) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) likes = models.IntegerField(default=0) views.py def like (request): com_id = None if request.method == 'GET': com_id = request.GET.get('comentario_id') likes = 0 if com_id: com = Comentario.objects.get(id=int(com_id)) if com: likes = com.likes + 1 com.likes = likes com.save() return HttpResponse(likes) urls.py urlpatterns = [ url(r'^like/$', login_required(views.like), name='like'), ] .html {% extends 'base/base.html' %} {% for comentario in objects %} ... {% if user.is_authenticated %} Like|{{ comentario.likes }} {% endif %} {% endfor %} js/ajax.js $('#likes').click(function(){ var comid; comid = $(this).attr("data-comid"); $.get('/home/like/', {comentario_id: comid}, function(data){ $('#like_count').html(data); $('#likes').hide(); }); }); And in base.html I have import all the .js base.html <script src="{% static 'jq/jquery-3.2.1.min.js' %}"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script> <script src= "{% static 'js/bootstrap.min.js' %}"></script> <script src= "{% static 'js/ajax.js' %}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> The issue is that when I push the button nothing happens. It is a simple code but somethin crashes. In the inspection do not show any error or … -
NoReverseMatch at / even after going back to the older working version
I did a reset master to this commit with hard-discard all working copy change, to the commit which was working perfectly. (and tried with much older commits as well) Also restarted the server. But still am not able to get rid of this error. Any help please! -
How can I connect Django with React?
I've got small application in React and several api on the server side. I want to deploy this site on Heroku. I performed the setup as stated on the site. As I started my project with react-start-app I ran npm run build Then python manage.py collectstatic Here is package.json { "name": "client", "version": "0.1.0", "private": true, "proxy": "http://127.0.0.1:8000", "dependencies": { "axios": "^0.16.2", "lodash": "^4.17.4", "materialize-css": "^0.100.2", "react-dom": "^15.6.1", "react-fileupload": "^2.4.0", "react-quill": "^1.0.0", "react-redux": "^5.0.6", "react-router-dom": "^4.2.2", "react-scripts": "1.0.12", "react-tabs": "^1.1.0", "redux": "^3.7.2", "redux-form": "^7.0.4", "redux-thunk": "^2.2.0" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" }, "devDependencies": { "eslint": "^4.5.0", "eslint-config-airbnb": "^15.1.0", "eslint-plugin-import": "^2.7.0", "eslint-plugin-jsx-a11y": "^5.1.1", "eslint-plugin-react": "^7.3.0", "react": "^15.6.1" } } settings.py ... STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') REACT_APP_DIR = os.path.join(BASE_DIR, 'client') STATICFILES_DIRS = [ os.path.join(REACT_APP_DIR, 'build', 'static'), ] And my entry point: views.py from django.views.generic import TemplateView class IndexView(TemplateView): template_name = 'index.html' 'index.html' is located in static dir, also I had en error and I changed with this configuration I ran heroku local web and opened http://0.0.0.0:5000 but there was clean page without any errors -
I have fixed select option list in HTML/CSS. I am trying to link it django char field.But Not finding a way through
Following is Django Form Field i have defined. source_currency = forms.CharField(max_length=5) Following is Select/Option HTML <select name="fancySelect" for="{{ form.source_currency.id_for_label }}" class="makeMeFancy" id="drop1"> <!-- Notice the HTML5 data attributes --> <option value="BTC" selected="selected" data-skip="1" data-icon="assets/images/large/bitcoin.png" data-html-text="BTC&lt;i&gt">BTC<span class="select_coin_button_arrow">▾</span></option> <option value="BTC" data-icon="assets/images/small/bitcoin.png" data-html-text="BTC&lt;i&gt" >BTC</option> <option value="ETH" data-icon="assets/images/small/ether.png" data-html-text="ETH&lt;i&gt;">ETH</option> How They can be linked so that on submit These values are passed as string? -
Failed system checks when hosting application
When I try to host my web app, I get this: (workout) sahands-mbp:workout sahandzarrinkoub$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10ce3b950> Traceback (most recent call last): File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 405, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. workoutcal.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. workoutcal.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. System check identified 4 issues (0 silenced). I can't interpret this error message, because it doesn't look like a normal python error message. Before I got this error, I was … -
How to configure Django to run on MSSQL Server
I'm able to run Django 1.11 with SQLite Database. But I'm getting an error with MSSQL Server. Apart from settings.py file I had not modified anything. It is showing ImproperlyConfigured: Django 1.11 is not supported. Here is my configuration: Settings.py DATABASES = { 'default': { 'ENGINE': 'django_pyodbc', 'HOST': '127.0.0.1', 'NAME': 'demo2016', 'USER': 'sa', 'PASSWORD': '', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } } In cmd prompt: C:\Users\Vitriv-Desktop\Desktop\sqldjango>python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 124, in …