Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display pages with specific tag in Django
i'am using bootstrap Tab panes and i need to show posts with specific tag in each pane without reloading the page of course for more detail i'm using Django with Wagtail CMS my app based on models file models.py: class BlogIndex(Page): intro = RichTextField(blank=True) def get_context(self, request): # Update context to include only published posts, ordered by reverse-chron context = super(BlogIndex, self).get_context(request) blogpages = self.get_children().live().order_by('-first_published_at') context['blogpages'] = blogpages return context class BlogPageTag(TaggedItemBase): content_object = ParentalKey('BlogPage', related_name='tagged_items') class BlogPage(Page): #info tags = ClusterTaggableManager(through=BlogPageTag, blank=True) #contentpanel .... note: i am using taggit but it seems that i didn't well handle it blog_index.html <div> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#News" aria-controls="News" role="tab" data-toggle="tab">News</a></li> </ul> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane" id="News"> #this is what i'am thinking of #for posts in blogpages : # if post tag == "News": # show post </div> </div> </div> -
How to consult data with django forms?
I'm playing with Django and I have a situation where I have a form and the user define a two dates, like when we need to book a flight, departure date and return date. In my forms.py I have a Form class with two fields for dates class MyForm(forms.Form): dateOne = forms.DateTimeField() dateTwo = forms.DateTimeField() I need to retrieve objects from a model by passing the dates defined by the user. In my template I'm using get action, on form html tag, but I'm stuck on how I can make this consult and bring the objects to the template. If I need create a logic on my views.py or in my forms.py. Does anyone know some thing to me start this task? -
How to repeat a model field in django with the help of jquery
I have the following models class Medicine(models.Model): name = models.CharField(max_length=100, default='') class Prescription(models.Model): prescribed_medicine = models.ManyToManyField(Medicine) Now when the doctor writes a prescription to patient, there should be 3 empty fields for prescribed_medicine, and add More button to add some more empty fields for prescribed medicines along with an option to delete adjacent to medicine field. -
Travis CI with mysql and django returns (1045, "Access denied for user 'root'@'localhost' (using password: YES)")
I'm trying the test of the program with django & mysql on travis-ci, but raise that error. pymysql.err.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") my .travis.yml is language: python python: - '3.6' services: - mysql matrix: include: - os: osx language: generic sudo: required env: - DJANGO=1.11 DB=mysql before_install: - brew update - brew install python3 - virtualenv env -p python3 - source env/bin/activate - brew install mysql install: - pip install -r requirements.txt before_script: - mysql.server start script: - cd <my_django_project> - python manage.py test In the test, it went well until $cd <my_django_project> and returns The command "cd <my_django_project>" exited with 0. But $python manage.py test raises that error pymysql.err.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") Also, when use my local Terminal, $python manage.py test raises no error and normally pass the test. I looked up the existing question, but this information is probably old. what can I do? Thanks. -
Django vs ExpressJs ( Nodejs) - Which is better to built an ecommerce website?
Which out of the two is better to built an ecommerce website in terms of security , Scalability , Easy Cms etc.? -
Obtain all foreign keys, Django
I have two models: UserEdus and Question. I need to get all Questions that have a specific UserEdus as their author. Models.py class UserEdus(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) class Question(models.Model): author = models.ForeignKey(UserEdus, null=False) Views.py class MyQuestionListView(generic.ListView): model = Question paginate_by = 10 queryset = Question.objects.filter(author=User.useredus) template_name = 'edus/myquestion_list.html' This queryset returns int() argument must be a string, a bytes-like object or a number, not 'ReverseOneToOneDescriptor' If I do queryset = User.useredus.question.all() that returns 'ReverseOneToOneDescriptor' object has no attribute 'question' Although on the template level, I can get the correct result using {% for question in user.useredus.question_set.all %} -
explain like Im five test case classes in django rest framework
I could really use this cleared up. The docs http://www.django-rest-framework.org/api-guide/testing/#test-cases explain that DRF has test case classes but it does not explain when to use them, and why there are multiple text cases. DRF docs say that these test cases inherent from the regular django test cases https://docs.djangoproject.com/en/1.11/topics/testing/tools/ and explain some of the features of the text cases example: Some useful assertions like: Checking that a callable raises a certain exception. Testing form field rendering and error treatment. Testing HTML responses for the presence/lack of a given fragment. Verifying that a template has/hasn't been used to generate a given response content. Verifying a HTTP redirect is performed by the app. Robustly testing two HTML fragments for equality/inequality or containment. but what does that mean? Does it mean I just call these assertions, does it do it for me? and why would I use one, and which one would I use? There is an example of testing that I got off git hub: https://github.com/erdem/DRF-TDD-example/blob/master/todoapp/todos/tests.py Why is he using APITestCase why not APIsSimpleTestCase or APITranacationTestcase <<--(most likely because he may never interact with a test database. Here is the thing guys I don't have a mentor at all and really need someone … -
Invalid file erorr, converting image to base64
How do i get a image from a image input and convert it into base64. erorr: invalid file: <InMemoryUploadedFile: image.jpg (image/jpeg)> def fileView(request): form = FileForm(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid: image = request.FILES.get('image') with open(image , "wb") as img: img.write(base64.decodebytes(image)) request.session['image_file'] = img return redirect('') -
Swift Login with Facebook to Django
I am trying to integrate login with Facebook in my iOS app which I did successfully. After that I want to authenticate the user and save it in my backend which is Django. What I have done is that I have a web-app with: Django Rest Framework django-rest-framework-social-oauth2 Python social auth I have studied the OAuth2 flow and also tried the example given at: https://github.com/PhilipGarnero/django-rest-framework-social-oauth2 I created an application in my backend with the help of Django OAuth toolkit and with the given client id and client secret I was successfully able to send a POST request using curl with the access token provided by Facebook. It returns me a dictionary like this , {"access_token":"An access token over here","token_type":"Bearer","expires_in":36000,"refresh_token":"Refresh token over here","scope":"read write"} I have a lot of confusions so how do I go about getting the user from my front-end and then associating and making a user in my back-end and later on checking if all the actions are done by that user (like referencing the user). What I have understood is that in my front-end which is my swift-app I should be making my user login with Facebook. Facebook authenticates the user and then returns an access token. … -
Django admin - form validation in admin panel
I hava a problem with form validation. This is a part of my clean method (forms.py - class SiteAddFormFull(forms.ModelForm)): url = self.cleaned_data['url'] if self.check_url_in_database(url) is True: errors.append('Url already exists') if errors: raise forms.ValidationError(errors) return self.cleaned_data This is check_url_in_database method: def check_url_in_database(self, url1): if url1[7:10] == 'www': url = 'http://' + url1[11:] else: url = url1.replace('http://', 'http://www.') try: Site.objects.get(url=url1) return True except ObjectDoesNotExist: try: Site.objects.get(url=url) return True except ObjectDoesNotExist: return False When I create new object (Site) in my django admin it works fine (validates if url exists in database). Problem appears when I try to modify existing object. It throws the same error ('Url already exists'). What is a proper way to validate only new objects? -
Django+Nginx+Gunicorn "Connection reset by peer" Error
I'm using the Digital Ocean tutorial (here) to set up a app that allows for a file upload (videos ranging from 5 mb to 1 GB). I know that large file uploads is not an ideal use case, but the client and the server are sitting in neighboring buildings connected via LAN (fast speeds in transfer) and FTP was not an option provided to me. When the files are small enough (30-40 mb), the app works fine. With 100 mb+ videos, I get a "502 - bad gateway" error on the client side. Nginx error log shows the following: 2017/07/17 15:52:18 [error] 18503#18503: *9 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: <client-ip>, server: <my-hostname>, request: "POST /videos HTTP/1.1", upstream: "http://unix:/www/app/app.sock:/videos", host: "<my-hostname>", referrer: "<app-domain>/videos" The Gunicorn error log shows no errors. My gunicorn settings: [Unit] Description=gunicorn daemon After=network.target [Service] User=django Group=www-data WorkingDirectory=/www/stitch EnvironmentFile=/www/stitch/.env2 ExecStart=/home/django/.pyenv/versions/django/bin/gunicorn --access-logfile /backup/logs/app_gunicorn_access.log --error-logfile /backup/logs/app_gunicorn_errors.log --workers 3 --worker-class=tornado --timeout=600 --graceful-timeout=10 --log-level=DEBUG --capture-output --bind unix:/www/app/app.sock app.wsgi:application [Install] WantedBy=multi-user.target What am I doing wrong? -
Django - local variable 'secs' referenced before assignment
I've been trying to handle this but I have no clue how I have a form where I'm getting secs form role="form" action="" method="POST" >{% csrf_token %} <br> <input type="number" name="secs" min="0" max="999" maxlength="3" class="form-control no-spinners" placeholder="Programar..."> <br> <button type="submit" id="btn-login" class="w3-btn w3-large w3-green" style="width:30%"> Aceptar </button> </form> in my views.py def streaming(request): if request.method == 'POST': secs = request.POST['secs'] print secs programarTiempo(secs) messages.info(request, 'Iniciando streaming en...' + secs + ' segundos') time.sleep(float(secs)) return redirect('streaming') return render(request, "straming.html", {"secs":secs}) When I got to my .html I got the following error: UnboundLocalError at /streaming/ local variable 'secs' referenced before assignment Thanks in advance! -
How to make change in request.data in django rest framework?
So I am making quiz app which has following structure class UserQuizRecord(models.Model): user = models.OneToOneField(User) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='userrecord') score = models.FloatField(default=0.00) I have serializer class of it class UserQuizRecordSerializer(serializers.ModelSerializer): class Meta: model = UserQuizRecord fields = ('user', 'quiz','score') Here is the views.py file and the detail route I am providing with data {quiz:1,score:7} I wish to add user to the request.data or serializer at in the views function. I am failing to get the right way to do it. class QuizView(viewsets.ModelViewSet): serializer_class = QuizSerializer queryset = Quiz.objects.all() model = Quiz @detail_route(methods=['post'], permission_classes=[AllowAny], url_path='rank') def rank(self, request, pk=None): request.data.quiz = Quiz.objects.get(pk=pk) serializer = UserQuizRecordSerializer(data = request.data ) if serializer.is_valid(): serializer.save() rank = UserQuizRecord.objects.filter(Q(quiz=request.data.quiz.id),Q(score__gte=request.data.score)).count() return Response({'rank':rank}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) What is the best way to perform this operation? -
Django can't find images and static files
I use django and my site works perfect but cant load images. I guess wrong thing is paths but i can't fix it. I see questions like that and apply all of them to my site but they did not work, please someone help me, i can't solve that for a few days. enter image description here enter image description here NOTE : my site works fine on localhost, on my computer but don't work on server -
HAYSTACK and Solr schema
It is my problem: SolrCore Initialization Failures blog: org.apache.solr.common.SolrException:org.apache.solr.common.SolrException: Could not load conf for core blog: java.io.IOException: Error parsing synonyms file: [enter image description here][1] [1]: https://i.stack.imgur.com/Alxt7.png I created search_indexes.py , post_text.txt In solr.. -> conf solrconfig.xml and schema.xml <?xml version="1.0" ?> <schema name="default" version="1.5"> </schema> Until then everything works (reload also) even added by the Add Core "blog" is visible, but according to the book I learn to change in the schema.xml file with: Python manage.py build_solr_schema copies everything from enter code here http://wklej.org/id/3216890/ Paste saves run java -jar start.jar and will display the error below Add core blog will disappear -
ProgrammingError: relation 'blah blah' does not exist, trying to run the specific migration and get error
I am getting an error: $ python manage.py migrate swsite 0023_hitcounter.py Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 398, in execute self.check() File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/usr/lib64/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/usr/lib64/python2.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/lib64/python2.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver for pattern in resolver.url_patterns: File "/usr/lib64/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/lib64/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/lib64/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/lib64/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/var/www/swlab-website/mysite/urls.py", line 25, in <module> url(r'^swsite/', include('swsite.urls')), File "/usr/lib64/python2.7/site-packages/django/conf/urls/__init__.py", line 52, in include urlconf_module = import_module(urlconf_module) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/var/www/swlab-website/swsite/urls.py", line 2, in <module> from . import views File "/var/www/swlab-website/swsite/views.py", line 27, in <module> class IndexView(generic.ListView): File "/var/www/swlab-website/swsite/views.py", line 31, in IndexView newhit = HitCounter.objects.create() File "/usr/lib64/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib64/python2.7/site-packages/django/db/models/query.py", line 401, in … -
django_rest_framework swagger error
I'm trying to set up django-rest-swagger on an existing django project using django_rest_framework but I keep getting a strange error when I try to access the endpoint I configured. My code looks something like this. views.py from rest_framework_swagger.views import get_swagger_view swagger_api_view = get_swagger_view(title='My API', url='/v1') urls.py from .views import swagger_api_view urlpatterns = [ ... url(r'^api_docs', swagger_api_view, 'swagger_api_view'), ... ] And the error is this Traceback: File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/utils/deprecation.py" in __call__ 138. response = self.process_request(request) File "/usr/local/lib/python3.5/dist-packages/django/middleware/common.py" in process_request 62. if self.should_redirect_with_slash(request): File "/usr/local/lib/python3.5/dist-packages/django/middleware/common.py" in should_redirect_with_slash 80. not is_valid_path(request.path_info, urlconf) and File "/usr/local/lib/python3.5/dist-packages/django/urls/base.py" in is_valid_path 158. resolve(path, urlconf) File "/usr/local/lib/python3.5/dist-packages/django/urls/base.py" in resolve 27. return get_resolver(urlconf).resolve(path) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py" in resolve 364. sub_match = pattern.resolve(new_path) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py" in resolve 364. sub_match = pattern.resolve(new_path) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py" in resolve 198. kwargs.update(self.default_args) Exception Type: ValueError at /v1/api_docs Exception Value: dictionary update sequence element #0 has length 1; 2 is required Any thoughts on what might be causing this, and/or ways to fix it? -
Django: how to use MultipleChoiceField in a form/admin
I need a MultipleChoiceField for and online enrollment application. When I try to use them in a field I get the an unknown field error. They also do not appear in the admin panel. # models.py ... CHILDCARE_REASONS = (('Working', 'working'),('Training', 'training'),('Teen Parent', 'teen_parent'),('Working W/Child With A Disability', 'child_disability'),('Adult W/Disability', 'adult_disability'),) reasons_for_childcare = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=CHILDCARE_REASONS) ... # forms.py class EnrollForm(forms.ModelForm): class Meta: model = EnrollmentApplication fields = [ ... 'reasons_for_childcare ', ... ] -
Extend User Model or Custom Pipeline in Social-App-Django
I am implementing social-app-django (not the deprecated one; the one that relies on Python-social-auth) with django 1.11 (not using Mongo). My application will need to store and manipulate a lot of data on users other than that which is fetched from their social media accounts at login. I don't need to fetch or collect any extra data when the user authenticates, but various actions they perform on my site will need to be saved to their user model. I am wondering which of the following approaches is preferred (I've searched extensively online, but can't find a specific explanation of why to use one vs the other): Create my own user model in my app's models.py (call it MyUser) that doesn't extend anything special, and then add a function in the authentication pipeline that associates the social-app-django user with a corresponding instance of MyUser. Leave AUTH_USER_MODEL and SOCIAL_AUTH_USER_MODEL unchanged. or... Create my own user model in my app's models.py, and in the project's settings.py set AUTH_USER_MODEL and SOCIAL_AUTH_USER_MODEL to point to MyUser. Leave the pipeline unchanged. In this case, I was wondering whether someone could clarify what MyUser and its manager should extend, and what I need to import in modules.py … -
setting up Postgres sql with dhango advise
im new to django and python , i know my way around Postgres. is it possible to create tables and set many to many connection in Postgres and make it reflect in django? -
localization of django template
I am trying to localize the date field in django template. Created and Completed date format is hardcoded as 'M d, Y'. <td class="medium-2 columns">{{ report.created|date:'M d, Y' }}</td> <td class="medium-2 columns">{{ report.completed|date:'M d, Y' }}</td> What I am trying to accomplish is, The Created and Completed date format should correspond to the current language. For example, German (DE): 17. Jan 2017 English (EN): Jan 17, 2017 Spanish (ES): 17 ene de 2017 (17 enero de 2017) I have in my settings.py file LANGUAGES = ( ('en', _('English')), ('fr', _('French')), ('it', _('Italian')), ('es', _('Spanish')), ('de', _('German')), ('ja', _('Japanese')), ) USE_L10N = True what is the best way to accomplish it? -
Missing apps.py,using python 2.7.12 with django 1.8
Iam using django 1.8 with python version 2.7.12 which is the right combination.But when I run command python manage.py startapp app_name,no apps.py got created but i can see under app_name init, admin, models, tests, views,migrations got created. Does django 1.8 not create any apps.py or what am i missing here? -
How to manage the sections of a website with Django?
am a newbie in Django, and am developing my first website with this framework. Is it correct to make one app for each section (home, about, contact), or I have to make one app that contains ALL the website? Thanks in advance -
how to display data of database in django
I am trying to retrieve data from mysql database in django.And i want to display it in a table with three columns name,photo,phone number. it showing no error but it only displaying one column and not other two.And i don't know why.. view.py- class Travel_Details(View): try: def __init__(self, **kwargs): self.template_name ='Travel/Travel_list.html', def get_context_data(self, request, **kwargs): context = RequestContext(request) return context def get_queryset(self, **kwargs): return def post(self, request, **kwargs): return def get(self, request, **kwargs): context_dict = {} return render(request,self.template_name, context_dict) except Exception as general_exception: print general_exceptionf print sys.exc_traceback.tb_lineno class OrderListJson(BaseDatatableView): model = Users columns = ['user_fname','user_photo','user_mob'] order_columns = ['user_fname'] max_display_length = 1000 def __init__(self): pass def render_column(self, row, column): # We want to render user as a custom column if column == 'user': return '{0} {1}'.format(row.user_fname,row.user_photo,row.user_mob) else: return super(OrderListJson, self).render_column(row, column) # def get_initial_queryset(self): return Users.objects.all() def filter_queryset(self, qs): search = self.request.GET.get(u'search[value]', None) if search: qs=qs.filter(user_fname_istartswith = search) return qs def prepare_results(self, qs): json_data = [] for item in qs: json_data.append([ item.user_fname, item.user_photo, item.user_mob ]) return json_data -
Retry celery tasks before their countdown
we are running Django v1.10 with celery v4.0.2, rabbitMQ v3.5.7 and flower v0.9.1 and are pretty new with celery, rabbitMQ and flower. There is a function x() which was set to retry after 7 days in case of failure. We have 1000's of instances of x re-queued on production. We have fixed the issue and would like to retry the instances asap. Is there a way to force the retry before it's scheduled time?