Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to check a setting and run tests only if that setting is set?
Is there a way to check a setting and run tests only if that setting is True? Is it possible to do this in the setup method so that no test cases are run if a flag is set to false? -
Page not found(404) error in django
I am getting a 404 error if the activation url is wrong or invalid. accounts/urls.py -- urlpatterns = [ url(r"^signup/$", views.signup, name="account_signup"), url(r'^login/$', views.login_view, name='account_login'), url(r'^logout/$', auth_views.logout, {'next_page': '/account/login'}, name='logout'), url(r'^confirmemail/$', views.confirmemail, name='account_confirmemail'), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',views.activate, name='activate'), ] accounts/views.py def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() user.profile.save() login(request, user) return redirect('home') else: return render(request, 'accounts/account_activation_invalid.html') #return HttpResponseRedirect("account_activation_invalid.html") It should redirect to account_activation_invalid.html if the account activation url is wrong. Any help/links is highly appreciated. Thanks in advance. -
Django duplicated SQL queries
I'm using django and redis to build a ranking application,items score are stored in a sorted set with the key "ranking:id:item_rank". Django-debug-toolbar says SQL queries have duplicates when i display rankings and its top three items in index page. # models.py class Ranking(models.Model): title = models.CharField(max_length=16, unique=True) class Item(models.Model): title = models.CharField(max_length=128) ranking = models.ForeignKey(Ranking, related_name='items') # views.py def index(request): rankings = Ranking.objects.all() return render(request, 'myapp/index.html', {'rankings': rankings}) I create custom template tags to display top three items in index page. # templatetags/ranking_tags.py r = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB) @register.assignment_tag def get_top_3(ranking): item_rank = r.zrange('ranking:{}:item_rank'.format(ranking.id), 0, 2, desc=True) item_ids = [int(id) for id in item_rank] items = list(Item.objects.filter(id__in=item_ids)) text = '' try: text = '<p>#1 :' + items[0].title + '</p>' text = text + '<p>#2 :' + items[1].title + '</p>' text = text + '<p>#3 :' + items[2].title + '</p>' except: pass return text # index.html {% for ranking in rankings %} <div> <h4>{{ ranking.title }}</h4> </div> <div> {% autoescape off %} <div> {% get_top_3 ranking %} </div> {% endautoescape %} </div> {% endfor %} # Django Debug Toolbar 1.SELECT "myapp_ranking"."id", "myapp_ranking"."title" FROM "myapp_ranking" 2.SELECT "myapp_item"."id", "myapp_item"."title" FROM "myapp_item" WHERE "myapp_item"."id" IN ('1', '2', '5') Duplicated 2 times. 3.SELECT "myapp_item"."id", "myapp_item"."title" … -
Inheritance directory is wrong
Now I am making Django web app. Inheritance directory is wrong,so this error TemplateDoesNotExist at /polls/ djangostudy/base.html happens.Directory is base.html(it is in polls which is in templase)is like {% extends "djangostudy/base.html" %} {% block nav_polls %}active{% endblock %} ,and base.html of "djangostudy/base.html" ,which is in same place of djangostudy&polls files.How can I fix this?What should I do to write this? -
Django: Test Driven Development rules and using external library
I'm trying to develope my application using TDD according to Obey The Testing Goat book. Currently, I'm working on feature which requires external library django-addanother. This library allows to create model forms resembling forms in admin (with plus button and popup forms). I created testing, working implementation of this feature (aka spike). Now I want to create functional tests based on this implementation and then develop final, destination code using these FT and TDD rules. Now, as far I know, TDD suggests to entirely listen to your tests during development. The problem is that there is no way that FT will tell me to use external library to achieve my goal. It will lead me to write my own code and then, eventually, I would use django-addanother during refactoring. It will be too complex and time-consuming task and I don't want to do it. So, is it ok that I will asume from the start that I'm using django-addanother during TDD process? Hope that my problem isn't too exaggerated. -
Django-tables2 - weird difference of two equal requests
I'm facing a very weird behaviour of Django and Django-tables2. I use table to help to render multiple types of documents. For simplicity, there are two types of documents - 'faktura' and 'dobropis'. 'dobropis' has to have first column labeled "Dobropisujeme Vám" and 'faktura' - "Názov položky" + those columns are equal. So I'm checking, if the type of Document is 'faktura' or 'dobropis' inside Table __init__ function and accordingly set self.base_columns['column'].verbose_name = ... The weird thing is that it works, but only after second refresh. Situation: I've opened 'faktura' page - I can see 'Názov položky' which is ok. Then I open 'dobropis' page and I see 'Názov položky' label again. Then, if I refresh again, there is 'Dobropisujeme Vám'. Then, after each refresh, I see correct label - 'Dobropisujeme Vám'. But, if I open 'faktura' page, there is 'Dobropisujeme Vám' too for the first time, after second refresh it goes normal. class PolozkyTable(tables.Table): nazov_polozky = tables.columns.Column(orderable=False) pocet = tables.columns.Column(orderable=False) jednotka = tables.columns.Column(orderable=False) cena = tables.columns.Column(orderable=False, verbose_name=u'Jednotková cena') zlava = tables.columns.Column(orderable=False) dph = tables.columns.Column(orderable=False) celkom = tables.columns.Column(orderable=False) class Meta: model = Polozka fields = ['nazov_polozky', 'pocet', 'jednotka', 'cena', 'zlava', 'dph', 'celkom'] attrs = {'class': 'table table-striped table-hover'} def __init__(self, … -
Pass parameter to Django REST framework serializer to use with model
I have a class Object with a method state that takes a datetime parameter dt. How do I pass the datetime parameter from the URL to Object.state()? The model: class Object(models.Model): def state(self, dt=datetime.datetime.now()) -> dict: ...stuff... return {'dt': dt, 'other_stuff': stuff} The view: class ObjectDetail(generics.RetrieveAPIView): queryset = models.Object.objects.all() serializer_class = serializers.ObjectSerializer def get_serializer_context(self): return {'dt': self.request.query_params.get('dt', datetime.datetime.now())} def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) And the serializer classes: class ObjectSerializer(serializers.HyperlinkedModelSerializer): state = StateSerializer(read_only=True, context={'dt': dt}) class Meta: model = models.Object fields = ('state') class StateSerializer(serializers.Serializer): dt = serializers.DateTimeField() ... other stuff... As you can see I am trying to pass dt as extra context in the line state = StateSerializer(read_only=True, context={'dt': dt}) having set the context earlier in the view. The problem here is that when ObjectSerializer is initialized dt is not accessible via self.context['dt'] as self is not defined. -
Image with a chinese filename returns UnicodeEncodeError
I have an api backend made of Django Rest Framework and I can not return my Image File with chinese characters like code/温州银行.png. It always return the error below: File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/rest_framework/viewsets.py", line 83, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/rest_framework/views.py", line 477, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python2.7/site-packages/rest_framework/views.py", line 437, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python2.7/site-packages/rest_framework/views.py", line 448, in raise_uncaught_exception raise exc UnicodeEncodeError: 'ascii' codec can't encode characters in position 9-12: ordinal not in range(128) Is there any way to solve this? -
django-social auth Exception Type: AuthAlreadyAssociated how to redirect custom
Trying to add social auth with my django website. All is done can log-in/sign up. But getting only one problem while trying to sign-up with already existed social account it's redirecting me to a exception page(Exception Type: AuthAlreadyAssociated) but i want the user to redirect on a page where i want. How ? -
Syntax error in 'as', is it about import?
I copied and pasted powerball model from GitHub in order to make powerball website. But it doesn't work with error message that invalid syntax in last one (as=rng, outsz=6) What should I do to fix it? Is it error about import? Should I install other packages? from django.db import models from django.conf import settings, BaseSettings from django.utils import timezone import random from .rng import random_numbers, _sort from .eth_tools import address, Contract def buy_ticket(first,second,third,fourth,fifth,powerball): if msg.value >= self.config.ticket_cost: if block.number <= self.config.lottery_deadline: id = self.config.next_id if self._validate_ticket(first, second, third, fourth, fifth, powerball ) != 1: return(-3) self.tickets[id].owner = msg.sender self.tickets[id].numbers[0] = first self.tickets[id].numbers[1] = second self.tickets[id].numbers[2] = third self.tickets[id].numbers[3] = fourth self.tickets[id].numbers[4] = fifth self.tickets[id].powerball = powerball self.config.next_id = id + 1 return([id], 1) else: return(-2) else: return(-1) def check_winners(): if (block.number <= self.config.lottery_deadline): return(-1) elif self.config.winning_numbers[0] != 0: return(-2) else: winning_numbers = self.config.rng_address.random_numbers(as = rng, outsz = 6) i = 0 while i < 6: self.config.winning_numbers[i] = winning_numbers[i] i += 1 i = 0 while i < self.config.next_id: self._calculate_result(i) i += 1 self._calculate_jackpot_results() return(winning_numbers, 6) -
Django Admin: can't add html attribute to FilteredSelectMultiple options
I'm working with Django 1.8 and I'm using a FilteredSelectMultiple in the Django Admin. I need to add a new html attribute (let's call the new attribute data-my-new-attr) to each of its options from the FilteredSelectMultiple . Something like (notice the data-my-new-attr="aaa"): <select multiple="multiple" class="filtered" id="id_realm_from" name="realm_old"> <option value="1" title="xxx" data-my-new-attr="aaa">ac-hoteles</option> <option value="2" title="yyy" data-my-new-attr="bbb">acs</option> </select> This is how I'm trying to do it: Admin.py: class MySelect(admin.widgets.FilteredSelectMultiple): def render_option(self, selected_choices, option_value, option_label): return format_html( u'<option value="{}" title="{}" data-my-new-attr="x">{}</option>', option_value, option_label, option_label ) class MyModelForm(forms.ModelForm): # MY_CHOICES = (....) my_field = forms.MultipleChoiceField( widget=MySelect('components', False), choices=MY_CHOICES) class Meta: model = MyModel fields = '__all__' So, basically, as you can see, I'm creating a new class MySelect that inherits from FilteredSelectMultiple to override its format_html method. I would expect to see the new attribue data-my-new-attr since I'm creating it in such method. But it doesn't appear. However, I know for a fact that the code runs through that function because I put a pdb.set_trace() and the execution stops there. Any idea on what I'm missing or doing wrong? -
Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['app1/(?P<question_id>[0-9]+)/vote/$']
https://docs.djangoproject.com/en/1.11/intro/tutorial04/. I Have a problem and checked others problems but still have no idea what to do with my code. Everything worked fine without generic views. Please help.### Problem: NoReverseMatch at /app1/2/ Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['app1/(?P<question_id>[0-9]+)/vote/$'] Request Method: GET Request URL: http://127.0.0.1:8000/app1/2/ Django Version: 1.11.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['app1/(?P<question_id>[0-9]+)/vote/$'] Exception Location: C:\Python36\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 497 Python Executable: C:\Python36\python.exe Python Version: 3.6.1 Python Path: ['C:\\Users\\Tomasz\\Desktop\\GitHub\\DjangoTutorialProject', 'C:\\Python36', 'C:\\Python36\\python36.zip', 'C:\\Python36\\DLLs', 'C:\\Python36\\lib', 'C:\\Python36\\lib\\site-packages'] Server time: Thu, 24 Aug 2017 08:34:58 +0200 Error during template rendering In template C:\Users\Tomasz\Desktop\GitHub\DjangoTutorialProject\app1\templates\app1\detail.html, error at line 5 Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['app1/(?P[0-9]+)/vote/$'] 1 <h1>{{ question.question_text }}</h1> 2 3 {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} 4 5 <form action="{% url 'app1:vote' question.id %}" method="post"> 6 {% csrf_token %} 7 {% for choice in question.mychoice_set.all %} 8 <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> 9 <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> 10 {% endfor %} 11 <input type="submit" value="Vote" /> 12 </form> 13 Problem is this piece of code: {% url 'app1:vote' question.id %} MY FILES: … -
Django template reload div with javascript - url tag
Hi i just wanted to reload part of data on the website using ajax. Website is created using template language from Django. I have problem with using url tag inside javascript tags, code below. urls.py urlpatterns = [ url(r'^(?P<place_id>[\w]+)/$', place_views.place_website, name='room_view'), ] Website <script type="text/javascript"> setInterval(function () { $("#displayMoment").load("{% url room_view room_id %}"); }, 60000); </script> Legend room_view is the name of the view inside views.py room_id is the room id which is captured by regex in url pattern. But it should be in double bracket right ? {{ room_id }} ? displayMoment is the id of the DIV. Problem With this i get error NoReverseMatch at /places/2/ Reverse for '' not found. '' is not a valid view function or pattern name. Ho does the website part should look like ? -
DRF - how to validate url parameters
I build API. In my url I can have include parameter where I can place names of relationships that should be included in the response together with main object. I would like to validate names in include to only allow the ones specified in serializer. Where is the best place to validate these url parameters and at which point? In which method? -
Templates add string to the front
In my templates, I can use the |add:'xx' to add string to the templates string. <body> <form action="/cookie/fm/" method="post"> {% csrf_token %} <p><input type="text" name="username"> {{ obj.errors.username.0 | add:' -- error --' }} </p> <p><input type="text" name="pwd"> {{ obj.errors.pwd.0 }} </p> <p><input type="text" name="email"> {{ obj.errors.email.0 }} </p> <input type="submit" value="submit"> </form> </body> But you know it is add at the end, how can I add the string in the front ? -
getting output {"list of append values": [10, 20, 30, 1, 2, 3, 4]}. i need the service to append the values in url
class changeme(View): def get(self, request): mylist = (request.GET['my_list']) return self.change_f(mylist) def change_f(self,mylist): a=[1,2,3,4] mylist=[10,20,30]+a return HttpResponse(d({"list of append values": mylist})) -
Rendering template object in an if comparison string
I've been trying to do this and getting no results <ul> {% for topic in topics %} <li {% if request.get_full_path == "/topic/{{ topic.topic_slug }}/" %}class="is-active"{% endif %}> <a href="{% url "TopicView" topic.topic_slug %}">{{ topic.topic_name }}</a> </li> {% endfor %} </ul> The error, I'm guessing is from the {{ topic.topic_slug }} being rendered in the string. I'd like it to be "/topic/tech/" during rendering but that seems not to be working. -
Is Django as powerful as PHP?
I'm about to code a news website, and i'm gonna have to make some complex features for it. Those features include: Resourceful statistics panel (e.g access origin devices, average session time and so on...) Smart content showcases by learning the user preferences as the user navigates through the website video gallery (and maybe other media types) Survey processing Smart ad system based on CPC and CPM (similar to Adsense) API to respond to XMLHttpRequests from the website itself (with authentication) Basic image processing (e.g Cutting, Resizing, Applying filters) Integration with Redis Integration with social media APIs such as Facebook and YouTube Classified ads system And obviously, large database manipulation The question is: is Django able to do these thing (even with third-part libs)? I know that PHP is able to do this and much more, but i have to do this website/app using Django/Python. I know that one (Django) is a framework and the other (PHP) is a programming language, but anyway... PS: I know my english isn't that thing, but forgive me, i'm not a native speaker of your language =) -
Searching if a person is available at a certain time
I am coding a Python/Django app. I have a model that contains a list of events. These have a start_datetime and finish_datetime attribute that marks the duration of the event. It also has a foreign key to a Staff object who is rostered on at that time. I have an event that I need to staff, and I have to find someone available to do the job. I'm not sure how to start coding this at all because I don't have any idea on how to search between two rows. This will have to be scaled over a dataset with possibly 1m records in the not too distant future. Any help would be greatly appreciated. -
Django template not displaying results in browser
I have two Django templates that are dependent, that is, once I hit submit on the form of my first template, I should be redirected to see the results into the second template but I am encountering the error: NoReverseMatch at /tickets_per_day_results/ where tickets_per_day_results is the template that should display the results. Forms class DropDownMenuForm(forms.Form): week = forms.ChoiceField(choices=[(x,x) for x in range (1,53)]) year = forms.ChoiceField(choices=[(x,x) for x in range (2016,2021)]) Views.py class ChartData8(APIView): def get(self, request): template_name = 'personal_website/tickets_per_day_no_results.html' form = DropDownMenuForm() return render(request, template_name, {'form': form}) def post(self, request): template_name = 'personal_website/tickets_per_day_results.html' #print(template_name) if request.method == "POST": year = request.POST.get('select_year', None) week = request.POST.get('select_week', None) ... do stuff .... return render(request, template_name, data) urls.py url(r'^tickets_per_day_no_results/$', ChartData8.as_view()), url(r'^tickets_per_day_results/$', ChartData8.as_view()), Template 1: tickets_per_day_no_results: This is the first template where you select your options from the drop-down menus. My guess is that the action to the second template is causing the problem. {% extends "personal_website/header.html"%} {% block content %} <h3>Please, select the year and week number to retrieve the data.</h3> <form id="search_dates" method="POST" action="/tickets_per_day_results/"> {% csrf_token %} <h6>Select year</h6> <div class="row"> <div class="col-sm-8"> <select name="select_year"> <option value = {{form.year}}></option> </select> </div> <div class="col-sm-8"> <h6>Select week</h6> <select name="select_week"> <option value= {{form.week}}></option> </select> … -
Can I run 3 uwsgi service using different port
I have 3 python django application on same server. And I want to run each service using different port. ex) 80 for end user 8001 for service provider 8002 for service operator But I have no idea how can I do this. Now, one uwsgi service is running using systemctl. This is my uwsgi.service. # uwsgi.service [Unit] Description=uWSGI After=syslog.target [Service] ExecStartPre=/bin/bash -c 'mkdir -p /var/run/uwsgi; chown root:ubuntu /var/run/uwsgi; chmod g+w /var/run/uwsgi;' ExecStart=/bin/bash -c 'source /var/www/html/remosys/bin/activate; uwsgi --ini /var/www/html/remosys/uwsgi.ini' #Restart=always Restart=on-failure KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all [Install] WantedBy=multi-user.target And uwsgi.ini is the following. [uwsgi] uid = ubuntu gid = ubuntu # Django-related settings # the base directory (full path) chdir = /var/www/html/remosys/remoshin # Django's wsgi file module = remoshin.wsgi # the virtualenv (full path) home = /var/www/html/remosys # process-related settings # master master = true # maximum number of worker processes processes = 2 threads = 1 # the socket (use the full path to be safe socket = /var/run/uwsgi/master.sock pidfile = /var/run/uwsgi/master.pid # ... with appropriate permissions - may be needed chmod-socket = 666 # clear environment on exit vacuum = true thunder-lock = true max-requests = 6000 max-requests-delta = 300 # log logto = /var/log/uwsgi/uwsgi.log deamonize = /var/log/uwsgi/uwsgi-@(exec://date +%Y-%m-%d).log log-reopen … -
Attaching the image in Django Ajax Rest Api
When I attach an image, the it returns null in the console but it goes on to post the text data, I want to be able to include the image file too. NOTE: when I upload image from the Rest api admin side, it works well and image displays, meaning that my Ajax image upload is the one lacking $("#userpost-form").submit(function(e){ e.preventDefault() var this_ = $(this) var formData = this_.serialize() //var form_data = new FormData(); //form_data.append('image', $(this_).get(0)); //console.log(form_data); $.ajax({ url: "/api/posts/create/", data: formData, method: "POST", dataType: "json", success: function(data){ console.log(data) }, error: function(data){ console.log("error") }, }) }) //post form end This Code posts the data very well without the image, So my challenge is on how to include the image file -
error code h14 on heroku
I was attempting to deploy a Django web app via Heroku using the following tutorial: https://devcenter.heroku.com/articles/git Once it said the app has been served on Heroku, I tried to open it but got an error: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=vast-spire-40247.herokuapp.com request_id=5d76216b-aa11-4e2d-a32e-30b70200eca7 fwd="73.163.159.62" dyno= connect= service= status=503 bytes= protocol=https I googled the error code, it took me the official heroku error documentation. It told me to enter a line a inside the command line. I entered that line but it did not resolve my issue, any suggestions? -
python script which will extract the total number of user who has been logged
Can any one help to write Python script below task: How to write python script which will extract the total number of user who has been logged on reporting portal so far and number of instances has been created. -
Modelchoicefield Queryset Confusion
All, I'm new to Django and have been doing pretty good so far but this one has me stumped. I'm trying to utilize ModelChoiceField for a number of records that have the same name. I'm using Postgresql so I was able to determine that I need to use the distinct command and that is working perfectly. The records in my dropdown are all stripped down to just one version of each of the records. However, when I try to get all of the versions of a particular record, that's where I'm getting lost. I am able to get the detail of each record if I don't use distinct via a DetailView, but I am really trying to get all versions of each record on the screen after the modelchoicefield. Here is my form: class History(forms.Form): dropdown = forms.ModelChoiceField(queryset=History.objects.all()) def __init__(self, user, *args, **kwargs): super(History, self).__init__(*args, **kwargs) self.fields['dropdown'].widget.attrs['class'] = 'choices1' self.fields['dropdown'].empty_label = '' qs = History.objects.all().distinct('record_name') self.fields['dropdown'].queryset = qs I am ultimately trying to get a view the queryset on the screen via my template. I have tried several different versions of code in the template but nothing seems to work. If I use the CBV DetailView without distinct I can …