Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, how to get information when confirm window'ok button is clicked
I want to know how to get event or result when confirm windows'ok button is clicked. I'm using Django. I wrote the code using xxx,, ((confirm( ,,, )" for u in myList -
Django ORM: group records by a field and then get the records with max value in each group
I have a model like this: Class Foo(model.Models): date = models.DateField() price = models.FloatField() volume = models.IntegerField() I want to get a list of all objects with the most price in each day! something like this: { 2017-01-01: {"date": 2017-01-01, "price": 1000, "volume": 210}, 2017-01-02: {"date": 2017-01-02, "price": 1032, "volumne": 242}, . . . } Can I do this with one query? The database is relatively large and performing a loop on dates is not going to work. -
Django: select_related to a table vs table's field
I have 2 models class A(models.Model): val = models.IntegerField() class B(models.Model): val2 = models.IntegerField() a = models.ForeignKey(A) class C(models.Model): b = models.ForeignKey(B) val3 = models.IntegerField() How is the query - C.objects.select_related('B').all() better than - C.objects.select_related('B__val2').all() And if not how query one can be optimised? -
Visual Studio Django app fails to build with StaticRootPath error
I'm writing my first Django app, and I have encountered a problem. When I go to build the project in visual studio, the build fails without giving any errors. The only way I can get it to show me an error at all is by changing the output to diagnostic mode, at which point it shows me this: Target "DetectStaticRootPath" in file "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\Python Tools\Microsoft.PythonTools.Django.targets" from project "C:\Users\OEM\Documents\TSM_shared\student-marketplace-v2\ecommerce test\ecommerce test.pyproj" (target "DjangoCollectStaticFiles" depends on it): Initializing task factory "RunPythonCommandFactory" from assembly "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\Microsoft\Python\Core\Microsoft.PythonTools.BuildTasks.dll". Using "RunPythonCommand" task from the task factory "RunPythonCommandFactory". Task "RunPythonCommand" Task Parameter:Target=import test.settings as settings; print(settings.STATIC_ROOT or '') Task Parameter:TargetType=code Task Parameter:ExecuteIn=none Task Parameter:WorkingDirectory=. Task Parameter:Environment=DJANGO_SETTINGS_MODULE=test.settings Task Parameter:ConsoleToMSBuild=True Output Property: DjangoStaticRootSetting= Done executing task "RunPythonCommand" -- FAILED. Done building target "DetectStaticRootPath" in project "test.pyproj" -- FAILED. Those are the only parts of the build that fail. Below is my settings.py: INSTALLED_APPS = [ 'app', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'app/static/'),) STATIC_ROOT = os.path.join(BASE_DIR,'static/') Thank you for your time. -
ImportError: No module named 'parse'
I got an error,ImportError: No module named 'parse' . In parse.py I wrote class DataRate(): data_rate ={} data_rate =defaultdict(dict) def try_to_int(arg): try: return int(arg) except: return arg book4 = xlrd.open_workbook('./data/excel1.xlsx') sheet4 = book4.sheet_by_index(0) tag_list = sheet4.row_values(0) for row_index in range(0, sheet4.nrows): row = sheet4.row_values(row_index) row = list(map(try_to_int, row)) value = dict(zip(tag_list, row)) closing_rate_dict[value['ID']].update(value) user = User.objects.filter(corporation_id=closing_rate_dict[value['ID']]['NAME']) I wanna user DataRate class in data_rate_savedata.py,so I wrote import parse def data_rate_save(): if user2: if parse.closing_rate_dict[parse.value['ID']]['NAME'] == 'A': parse.user2.update(data_rate_under_500 = parse.closing_rate_dict[parse.value['ID']]['d500'], data_rate_under_700 = parse.closing_rate_dict[parse.value['ID']]['d700'], data_rate_upper_700 = parse.closing_rate_dict[parse.value['ID']]['u700']) I wanna use parse.py & data_rate_savedata.py in main_save.py,so I wrote from app.parse import DataRate #parse DataRate() #save data_rate_save() When I run main_save.py,I got an error ImportError: No module named 'parse',traceback says File "/Users/app/data_rate_savedata.py", line 1, in import parse is wrong.Is it IDE problem?Or am I wrong to write codes?How can I fix this error? -
ImportError: Couldn't import Django
I've already configured virtualenv in pycharm, when using the python managed. Py command E:\video course\Python\code\web_worker\MxOnline>python manage.py runserver Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? How should I fix it, I've installed django -
redirect reverse in Django
I'm working on Django 1.11 I want to redirect user from view. contents of myapp/accounts/urls.py app_name = 'accounts' urlpatterns = [ url(r'^$', views.ProfileView.as_view(), name='profile'), url(r'^profile/', views.ProfileView.as_view(), name='profile') ] and in myapp/accounts/views.py from django.contrib.auth.models import User # Create your views here. from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView, UpdateView class ProfileView(TemplateView): template_name = 'accounts/profile.html' class UpdateProfile(UpdateView): model = User fields = ['first_name', 'last_name'] template_name = 'accounts/update.html' def get_object(self): return self.request.user def get_success_url(self): messages.success(self.request, 'Profile Updated Successfully') return HttpResponseRedirect(reverse('profile')) This is giving error on redirect. NoReverseMatch at /accounts/update/ Reverse for 'profile' not found. 'profile' is not a valid view function or pattern name. How to redirect user to profile page after updating profile details? How to redirect user to other app's view? -
Recover deleted Django migrations
On my production server I accidentally deleted my migrations directory in one of my apps. Multiple people work on the app, so at the time of making the app, what we did was push up our model changes without making any migrations locally, and than make the migrations on the production server, and migrate there. We did this because we were having migrations merge issues in the past, and thought this might be a good solution. Since there is no local copy of the migrations folder I fear its gone forever. My question is this. I can access phpPgAdmin in Webfaction, and the database has a django_migrations table. I thought one solution would be to find the latest migrations, lets say for example 0009_migration.py, and than simply rename a new migration file, 0010_migration.py for my next migration if I ever make any model changes in the future in that app. That way I can simple run migrate, and it will only be considered with the migration that it has yet to run, 0010_migration.py. But just out of curiosity, is there some command that will look at your PostgreSQL database, and create the migration files in your app migrations directory from … -
what are most frequently used real-time examples of Django custom middleware? It would be great if a code snippet is also shared
what are most frequently used real-time examples of Django custom middleware? It would be great if a code snippet is also shared. -
How to use Apache to serve Django server and React client?
I'm trying to configure Apache2 to serve Django for backend APIs (/api/), and React app for client side JS (/). I want the root path to load the React app (e.g. www.example.com/). I'm having a hard time. If I Alias/Documentroot the / to React's /build directory, then Apache stops serving Django. And conversely when I remove the Alias/Documentroot, then Django serves fine but React doesn't. How could I do this? Here's my httpd.conf file: ``` DocumentRoot /home/ubuntu/project/webapp/build/ Alias / /home/ubuntu/project/webapp/build/ <Directory /home/ubuntu/project/webapp/build> Require all granted </Directory> Alias /static /home/ubuntu/project/webapp/build/static <Directory /home/ubuntu/project/webapp/build/static> Require all granted </Directory> WSGIDaemonProcess server python-home=/home/ubuntu/python3.5/ python-path=/home/ubuntu/project/server WSGIProcessGroup server WSGIScriptAlias /admin /home/ubuntu/project/server/server/wsgi.py <Directory /home/ubuntu/project/server/server> <Files wsgi.py> Require all granted </Files> </Directory> ``` -
Would like to create a POST method for my Django API
I would like to create a POST method for my Django project while setting up the API. I have tried creating an override method for create but it gives me an integrityconstrain. I would like to make a post that stored all the field in a tidy JSON. I'm not sure if it's because of manytomanyfield that is causing the problems. Thank you in advances. Models.py class Results(models.Model): type = models.CharField(max_length=200, blank=True) question = models.CharField(max_length=200, blank=True) title = models.CharField(max_length=200, blank=True) ytid = models.CharField(max_length=200, blank=True) correct_answer = models.CharField(max_length=200, blank=True) incorrect_answers = ArrayField(models.CharField(max_length=200), blank=True) def __str__(self): return '{}, {}, {}, {}, {}, {}'.format(self.type, self.question, self.title, self.ytid, self.correct_answer, self.incorrect_answers) class Simulation(models.Model): sequence = models.PositiveIntegerField(unique=False) method = models.CharField(max_length=200) results = models.ForeignKey(Results, on_delete=models.CASCADE) class Meta: ordering = ['sequence'] def __str__(self): return '{}'.format(self.sequence) class respond_code(models.Model): respond_code = models.PositiveIntegerField(primary_key=True) simulation = models.ManyToManyField(Simulation) class Meta: ordering = ['respond_code'] def __str__(self): return '{}'.format(self.respond_code) Serializers.py class ResultsSerializer(serializers.ModelSerializer): class Meta: model = Results fields = ('type','question','title','ytid','correct_answer','incorrect_answers') class SimulationSerializer(serializers.ModelSerializer): results = ResultsSerializer(many=False) class Meta: model = Simulation fields = ('sequence','method','results') class respond_codeSerializer(serializers.ModelSerializer): simulation = SimulationSerializer(many=True) class Meta: model = respond_code fields = ('respond_code', 'simulation') def create(self, validated_data): simulations_data = validated_data.pop('simulation') simulation = Simulation.objects.create(**validated_data) for i in simulations_data: Simulation.objects.create(simulation=simulation, **i) for data in … -
Django 1.11 not discovering test cases inside tests folder
I have been doing this in earlier Django versions like 1.8, which I created a tests package inside the app and have different test cases in each files. Then I import the test cases inside __init__.py, exactly described in this SO But it seems doesn't work as expected in Django 1.11, it seems to work halfway, eg. When I run ./manage.py test app, it doesn't discover any tests. When I run ./manage.py test app.tests, it finds all the tests What am I doing wrong? -
Static Ports In Django w/ Visual Studio
Has anyone found out a way to have visual studio run a Django app on a static port rather than it changing ports every run? I have a separate program sending requests to the server but it becomes a hassle having to change the port every time I re run the server. Thanks in advance for any direction on the subject. -
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 %}