Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
URL to each user's profile in a list of users
I have the following code in my userprofile_list.html template: {% extends "base.html" %} {% block content %} {% for users in userprofile_list %} <a href="{% url 'users:user_profile' user.pk %}"> <div class="user-card"> <img class="profile-pic" src="{%if user.userprofile.profile_pic%}{{user.userprofile.profile_pic.url}}{%endif%}"> <p class="user-card-name">{{ users.pk }}</p> <p class="user-card-name">{{ users.first_name }}</p> <p class="user-card-type">{{ users.user_type }}</p> </div> </a> {% endfor %} {% endblock %} Note the line <a href="{% url 'users:user_profile' user.pk %}">, I am using it elsewhere in the my app and when clicked it takes you to the profile of the currently logged-in user. However, I would instead like it to take you to the profile of whichever user you clicked on in the users list being created by the for loop. How do I change the url to do that? I think what has to be done is that instead of getting the pk of the currently logged in user it has to instead get the pk of that specific user in the users list, which is then passed through to the url patterns (already working so I didn't posting it). Note: If I'm not right with my logic on what has to happen thats fine just let me know what you need to see in … -
How annotate the Max value of two fields in a Django QuerySet
I have a model Client, how do i annotate then sort, the Max of its two fields: from django.db import models class Client(models.Model): uploaded_photo_at = models.DateTimeField() uploaded_document_at = models.DateTimeField() The following: Client.objects.annotate( latest_activity_at=Max('uploaded_photo_at', 'uploaded_document_at', output_field=DateTimeField()) ).order_by('latest_activity_at') Raises this error: django.db.utils.ProgrammingError: function max(timestamp with time zone, timestamp with time zone) does not exist LINE 1: ...oto_at", "clients_client"."uploaded_document_at", MAX("clien... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. I am using Posgresql and Django 1.11, if that helps. -
indexing db content to elastic search
Hello all I am working on a Django project with backend database as a PostgreSQL server. and I have chosen elastic search as a search engine for my project. I have used elastic search-dsl-py to create a mapping between Django models and elastic search doc type. and use Django signals to capture update and delete events. By the way, I haven't mapped all the fields from Django model to elastic search. When a user search he/she get's a list of an item from the homepage. When user clicks to the detail page. Where should I query the data about the detail of an item, in the elastic_search or in the Postgres If I put all the details of every object in an elastic server, It will going to be a pain for me as, there is a nested relation in Django models. If I don't put all the details in elastic search server, I need to query to the database to get the detail of an item which is going to be slow as compared to an elastic search query. Index all the properties along with the nested relation in elastic search server and do all the querying operation to … -
Django 1.11 Pagination Markdown
I tried to paginate a very long string in Django by splitting it using an array which I successfully did however the django-markdown-deux stopped working. Here is how I implemented it: models.py: class Post(models.Model): content = models.TextField() def get_markdown(self): content = self.content markdown_text = markdown(content) return mark_safe(markdown_text) views.py: def post_detail(request, slug=None): #retrieve instance = get_object_or_404(Post, slug=slug) #Detect the breaklines from DB and split the paragraphs using it tempInstance = instance.content PaginatedInstance = tempInstance.split("\r\n\r\n") paginator = Paginator(PaginatedInstance, 5) #set how many paragraph to show per page page = request.GET.get('page', 1) try: Paginated = paginator.page(page) except PageNotAnInteger: Paginated = paginator.page(1) except EmptyPage: Paginated = paginator.page(paginator.num_pages) context = { "instance": instance, "Paginated": Paginated, #will use this to display the story instead of instance (divided string by paragraph) } return render(request, "post_detail.html", context) post_detail.html: this is the one that works(without pagination): {{ instance.get_markdown }} this one works as plain text if I remove the .get_markdown and won't display anything if I put .get_markdown {% for paginatedText in Paginated %} {{ paginatedText.get_markdown }} {% endfor %} -
I wanna assign trunsaction_id each user_id
I wanna assign trunsaction_id each user_id.Now User model is class User(models.Model): trunsaction_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) regist_date = models.DateTimeField(auto_now=True) user_id = models.CharField(max_length=200,null=True) name = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) When I run this code,trunsaction_id is assigned in turn of registration. Is it possible to assign trunsaction_id each user_id?If the answer is yes,I wanna know the way. For example,if user_id is 1,trunsaction_id is one of be connected user_id &trunsaction_id in under score like 1_randomly trunsaction_id .Is it possible?If answer is no,is there another way to assign trunsaction_id each user_id? -
URL to non-logged in user's profile
I have the url the goes to the logged-in user's profile, however I have a page on my site which displays a list of all the users. I would like have each entry in the user list to be a link that goes to each user's profile, even though they are not logged-in. So essentially any user can go to the list and see another user's profile. I'm just not sure how to get all the other users' ok's (which is what I think I have to do here)... app views.py: def detailprofile(request,pk): user = get_object_or_404(User,pk=pk) posts = UserPost.objects.filter(author=user) context = {'user':user,'posts':posts} return render(request,'users/userprofile_detail.html',context) app user profile_list.html: {% extends "base.html" %} {% block content %} {% for users in userprofile_list %} <a href=""> <div class="user-card"> <img class="profile-pic" src="{%if user.userprofile.profile_pic%}{{user.userprofile.profile_pic.url}}{%endif%}"> <p class="user-card-name">{{ users.first_name }}</p> <p class="user-card-type">{{ users.user_type }}</p> </div> </a> {% endfor %} {% endblock %} -
Python, if else and key modification
I have a one program/website that will read the output from a text file. Python will read each of line and display it on the website. There is two output that Python will read and display, which is visual id and time delay. It able to only display visual id in one column and both visual id, time delay perfectly. QUESTION My problem is when I only want to display 'time delay' it will take the first output line to 'visual id' column, which is it will display two column. I want it to display all the 'time delay' in one column. Views.py with open(path) as input_data: for line in input_data: if 'visual' in tokens and line.startswith('2_visualid_'): prev_key = line.lstrip('2_visualid_').rstrip() data.update({prev_key: []}) if 'time' in tokens: if search_string in line and prev_key in data: data[prev_key].append(next(input_data).lstrip('2_mrslt_').rstrip()) else: if search_string in line: prev_key = (next(input_data).lstrip('2_mrslt_').rstrip()) data.update({prev_key: []}) context = {'output': data} Form HTML <form action=""> &nbsp&nbsp<input class="regular-checkbox" type="checkbox" name="token" value="visual"><b>&nbsp&nbsp Visual ID</b><br> &nbsp&nbsp<input class="regular-checkbox" type="checkbox" name="token" value="time"><b>&nbsp&nbsp Time Delay Index</b> </form> Table HTML <div class="input-group" align="center" style=" left:10px; top:-110px; width:99%"> <table class="table table-bordered"> <thead class="success" > <tr> <th class="success"> <b>Visual ID</b> </th> <th class="success"> <b>Time Delay Index</b> </th> </tr> {% for key, … -
Data is saved including blank
I wanna parse excel and put it to the model(City&Prefecture&Area&User) . I wrote fourrows_transpose=list(map(list, zip(*fourrows))) val3 = sheet3.cell_value(rowx=0, colx=9) user3 = Companyransaction.objects.filter(corporation_id=val3).first() if user3: area = Area.objects.filter(name="America").first() pref = Prefecture.objects.create(name="Prefecture", area=area) city = City.objects.create(name="City", prefecture=pref) price= Price.objects.create(city=city) pref.name = fourrows_transpose[0][0] pref.save() for transpose in fourrows_transpose[2:]: if len(transpose) == 5: if "×" in transpose or "○" in transpose: city.name = transpose[1] city.save() price.upper1000 = transpose[2] price.from500to1000 = transpose[3] price.under500 = transpose[4] price.save() Now DB is My ideal db is in name A,A,A,A,B,B,B,B,C . I rally cannot understand why such db is made. I think the position of writing city.name = transpose[1] city.save() is wrong, so I wrote these code under price.save(),but same db was made. What is wrong in my code?How can I fix this? -
Adding custom attrs to a form widget
I'm currently working with some forms in Django, and I need to add a custom attribute to all my widgets, for example: widgets = { 'datefield': forms.widgets.DateInput(format = settings.DATE_INPUT_FORMATS, attrs = {'myownattr': 'foobar_value'}) } Is this valid? And if it, how can I access it from a template? I tried {{ field.myownattr }}, but that doesn't return anything at all. -
Ionic Google social authentication to Django Rest Framework backend
I am trying to get social authentication working for my mobile app (an Ionic app on Android). Django rest framework backend with rest_framework_jwt, social_django, and rest_social_auth. On my Ionic app I was using satellizer.js, however, I can't use InAppBrowser so now I am trying to do the following with cordova-plugin-googleplus: Step#1 (On client/app) if (provider == 'google') { // Use Google API Natively to get tokens and user info window.plugins.googleplus.login( { // TODO Get the WebClient from App settings 'webClientId': '[*.myclientid]', // optional clientId of your Web application from Credentials settings of your project - On Android, this MUST be included to get an idToken. On iOS, it is not required. 'offline': true, // optional, but requires the webClientId - if set to true the plugin will also return a serverAuthCode, which can be used to grant offline access to a non-Google server }) ................ Result: This gets me a valid response with both a idToken, serverAuthCode, and a userId. Step#2 I am not sure what the next step is. Originally, I was going to try using Django rest_social_auth to do the following from my client/app: POST /api/login/social/ with data (json) provider=google&code=ASLKDJASLDKJASLD Which was supposed to return a JWT token … -
Django .get() returns a tuple and not the object
I have a simple function which looks like this: parent_key = SeoKeys.objects.get(view_id=view_id, key_nbr=key_nbr) if parent_key.status != 'active': parent_key.status = status parent_key.save() metrics, created = SeoMetrics.objects.get_or_create( seo_url = url_sent, date = date, parent_key = parent_key, defaults = { 'parent_key':parent_key, 'seo_url': url_sent, 'url_found':url_found, 'position':position, } ) Now in theory this should work, however I get the following error: ValueError: Cannot assign "(<SeoKeys: SeoKeys object>,)": "SeoMetrics.parent_key" must be a "SeoKeys" instance. This happens because it's a tuple. If I do 'parent_key':parent_key[0] it will save it fine. However this seems a rather hacked solution and I would like to rather understand why this happens. Any ideas? My model looks something like this: class SeoMetrics(models.Model): parent_key = models.ForeignKey('SeoKeys', on_delete=models.CASCADE) -
Something's not quite right with my template tags
Is something with this if statement? It works, just not correctly. No error comes up and it does display the number associated with each word value however it won't display the correct word and the front end. <p class="accent list-text">I'm a:</p> {% if request.user.userprofile.user_type == 1 %} <p class="profile-info list-text">Designer</p> {% elif request.user.userprofile.user_type == 2 %} <p class="profile-info list-text">Designer</p> {% else %} <p class="profile-info list-text">Both</p> {% endif %} -
Django Many-to-one relationships
For my question, I´ll be using Examples of Django documentation. My problem is that I would like to click a Reporter name and then change webpage to get the list of all articles. This is the models.py from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): # __unicode__ on Python 2 return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): # __unicode__ on Python 2 return self.headline class Meta: ordering = ('headline',) How can I change one model to other useing Many-to-one relationship with Class-based views. https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_one/ Thanks in advance -
Django admin inlines with different readonly fields
Say we have model inlines in Django admin. How can we make some fields(of inline) readonly if inline object exists but editable for new instances? For example if model has related comments, we wont let existing comments to be editable, but possible to create new (from inline admin). -
Django-Rest-Framework - nested objects and serializers, how to?
I'm using DRF for the first time. I've been reading the documentation pages but no clue on how to do this. I have two models, the AdPrice Model make reference to the Ad Model. I need to list the various prices for an Ad. My question is: How can I get a list of Ads like this? [ { "title": "Some long title for Ad1", "name": "Name Ad1", "prices": { { "name": "price now", "price": 200 }, { "name": "price later", "price": 300 } } }, ] models.py class Ad(models.Model): title = models.CharField(max_length=250) name = models.CharField(max_length=100) def __str__(self): return self.name class AdPrice(models.Model): ad = models.ForeignKey(Ad) name = models.CharField(max_length=50) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.name serializers.py class AdPriceSerializer(serializers.Serializer): name = serializers.CharField(max_length=50) price = serializers.DecimalField(max_digits=6, decimal_places=2) class Meta: model = AdPrice class AdSerializer(serializers.Serializer): title = serializers.CharField(max_length=250) name = serializers.CharField(max_length=100) prices = AdPriceSerializer(many=True) views.py class AdViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Ad.objects.all().order_by('-date_inserted') serializer_class = AdSerializer When I try the code above I got this error: AttributeError at /ads/ Got AttributeError when attempting to get a value for field `prices` on serializer `AdSerializer`. The serializer field might be named incorrectly and not match … -
Searching multiple fields in Django for loop
I have a couple form fields I need to format differently and am trying to use a IF statement to find the fields when rendered, but doesn't seem to be working as the documentation suggests. I want to format "Country" and "State" differently, but the code doesn't like what I'm trying. {% for field in customerfields %} {% if field.name != 'country' or 'state' %} {{ field.label.upper }} <div class="FormRow"> {{ field }} </div> {% else %} <div class="FormRow"> <div class="StyledSelect"> {{ field }} </div> </div> {% endif%} {% endfor %} How do I search for more than one field? Is there a better way to do this? -
Cannot define model in django
I am trying to build my first django app using the most common posts as an test. Unfortunately the server keeps returning errors such as Postmodel admin not defined. I have tried migrating the new changes but this doesnt work, as well as modifying the views, but it seems i need to explicitly define this model. Could someone point me in the right direction Heres how my admin.py looks like from django.contrib import admin Register your models here. from .models import posts import views admin.autodiscover() class PostsModelAdmin(admin.ModelAdmin): list_display = ('title', 'updated', 'timestamp') list_display_links = ('updated') list_editable = ('title') list_filter = ('updated', 'timestamp') search_fields = ("title", 'content') class Meta: model = posts admin.site.register(posts) admin.site.register(PostModelAdmin) -
'python -m django' gives conflicting messages in virtualenv
I created a virtualenv: virtualenv --python=/usr/local/bin/python2.7 workoutpy2.7 I'm working on a workout diary web app, hence that name. Then I installed django nonrel in it: pip install git+https://github.com/django-nonrel/django@nonrel-1.5 and then djangotoolbox for django nonrel: pip install git+https://github.com/django-nonrel/djangotoolbox and then the mongodb engine: pip install git+https://github.com/django-nonrel/mongodb-engine I then assumed that django was installed in my virtualenv. So I typed: python -m django and got the following output: /Users/sahandzarrinkoub/Documents/Programming/Web/Django/workoutpy2.7/bin/python: No module named django.__main__; 'django' is a package and cannot be directly executed What does this mean? For the record, the same thing happens with ANY package I install in this way. Just have a look at this: (workoutpy2.7) Sahands-MacBook-Pro:workoutpy2.7 sahandzarrinkoub$ pip install pymongo Requirement already satisfied: pymongo in ./lib/python2.7/site-packages (workoutpy2.7) Sahands-MacBook-Pro:workoutpy2.7 sahandzarrinkoub$ python -m pymongo /Users/sahandzarrinkoub/Documents/Programming/Web/Django/workoutpy2.7/bin/python: No module named pymongo.__main__; 'pymongo' is a package and cannot be directly executed Thankful for any help. -
Python sports game outcome algorithm
I would like to create an algorithm to generate a score for both teams in a game using both an element of random, and the teams overall rating. So far I have something similar to the following. # determine score home_overall = 78 away_overall = 85 home_score = numpy.random.choice(range(4), p=[.2, .4, .3, .1]) away_score = numpy.random.choice(range(4), p=[.2, .4, .3, .1]) I'm unsure how to factor in the teams overall rating without it being a direct correlation to the outcome. What I DON'T want is to take the score and just multiply it by the teams overall. Ideally I'd like to include more granular factors in the future instead of just overall, but that may be something to tackle another day. -
python app not starting in visual studio
I have created django python app, and when I press F5 , it pops up a python shell which says Available subcommands: [auth] changepassword createsuperuser [django] check compilemessages createcachetable dbshell diffsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate runfcgi shell showmigrations sql sqlall sqlclear sqlcustom sqldropindexes sqlflush sqlindexes sqlmigrate sqlsequencereset squashmigrations startapp startproject syncdb test testserver validate [sessions] clearsessions [staticfiles] collectstatic findstatic runserver Press any key to continue . . . But it does not open any browser and app is not running, when I hit any key , it just stops the app. I am wondering what is the issue. Weird thing is few days ago this app was working fine and I didn't do anything after that. -
Anybody get django cookiecutter to work with anaconda instead of virtualenv?
Just when I think I'm starting to get a handle with django I start reading Two Scoops Of Django where they advise to use Cookiecutter instead of the regular django-admin startproject. The authors of Two Scoops are big on virtualenv. I've been using Anaconda because everywhere says it's better than virtualenv. I'm tempted to get rid of anaconda and just use virtualenv to try to get this to work, but figured I'd ask here first. Anybody know how to get cookiecutter to work with Anaconda??? -
Django Collectstatic Suspicious File operation
I am trying to run collectstatic on heroku. When I got this error: remote: 'component ({})'.format(final_path, base_path)) remote: django.core.exceptions.SuspiciousFileOperation: The joined path (/tmp/build_4652acfe079723bc273763513a187201/fonts/glyphicons-halflings-regular.eot) is located outside of the base path component (/tmp/build_4652acfe079723bc273763513a187201/staticfiles) I thought perhaps I had missed something with collectstatic on my end, so I ran it locally, and got the exact same error. Then I went looking. I found: /home/malikarumi/Projects/aishah/jamf35/staticfiles/bootstrap/fonts/glyphicons-halflings-regular.eot and /home/malikarumi/Projects/aishah/jamf35/static/bootstrap/fonts/glyphicons-halflings-regular.eot My settings: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/bootstrap/fonts/'), There is a ticket out there, but it seems to be about paths, and I see nothing wrong with my paths, https://code.djangoproject.com/ticket/27201 Another one deals with files, and might be closer to my issue, because it has to do with created tmp files, but I really can't tell: https://code.djangoproject.com/ticket/26644 I should note that I also looked at Django: The joined path is located outside of the base path component, Django: How to allow a Suspicious File Operation / copy a file, and Django | joined path is located outside of the base path component {% static img.thumbnail.url %}, Error 400 with whitenoise, but they seem to be more about MEDIA ROOT issues. I'm not sure what the fix is, here. Please advise. Thanks. -
Django on mod_wsgi syntaxError
I installed Django 1.11.5 with Virtualenv on mod_wsgi. python version is 2.7.13. I get this error in /var/log/httpd/error_log: [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] mod_wsgi (pid=9606): Target WSGI script '/var/www/html/memit/memit/wsgi.py' cannot be loaded as Python module. [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] mod_wsgi (pid=9606): Exception occurred processing WSGI script '/var/www/html/memit/memit/wsgi.py'. [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] Traceback (most recent call last): [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] File "/var/www/html/memit/memit/wsgi.py", line 13, in <module> [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] from django.core.wsgi import get_wsgi_application [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] File "/var/www/html/memit/env/lib/python2.7/site-packages/django/__init__.py", line 3, in <module> [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] from django.utils.version import get_version [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] File "/var/www/html/memit/env/lib/python2.7/site-packages/django/utils/version.py", line 7, in <module> [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] from django.utils.lru_cache import lru_cache [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] File "/var/www/html/memit/env/lib/python2.7/site-packages/django/utils/lru_cache.py", line 28 [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] fasttypes = {int, str, frozenset, type(None)}, [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] ^ [Wed Sep 13 16:41:00 2017] [error] [client 5.125.70.26] SyntaxError: invalid syntax And My Apache virtual host is: <VirtualHost *:80> ServerName … -
Adding a button to Wagtail Dashboard
Is it possible to add a button on the top panel as shown in the picture? I did't find anything in Google here. -
Django Search Query comparing votes and post age with Annotate
I trying to make a django query to get posts order by VOTES - POST AGE. Example: Normal Posts 1 - Hello World (10 votes) (Posted today) 2 - Stackoverflow ( 12 votes) (Posted 2 days ago) 3 - StackExchange ( 30 votes ) (Posted 19 days ago) So when I filter query by annotate, I want this: 1 - StackExchange ( 30 votes - 19 days ago = 11 points) 2 - Hello World ( 10 votes - 0 days ago = 10 points) 3 - Stackoverflow ( 12 votes - 2 days ago = 10 points) What I try: class DiffDays(Func): function = 'DATEDIFF' template = "%(function)s(%(expressions)s)" class CastDate(Func): function = 'DATE_FORMAT' template = "%(function)s(%(expressions)s, '%%%%Y-%%%%m-%%%%d')" list_posts = posts.extra(select={'pub_date': "DATE_FORMAT(pub_date,'%%%%Y-%%%%m-%%%%d')"}).annotate(diff_days=DiffDays(CastDate(today), F('pub_date')), output_field = DecimalField()).annotate(days_votes=ExpressionWrapper(F('n_votes') - F('diff_days'), output_field=IntegerField())).order_by('days_votes') but I'm getting: 'IntegerField' object has no attribute 'resolve_expression'