Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Logger not logging but all other loggers work
I have configured my Django application to run in production but I cannot get anything out of the django logger. The root logger is writing out to file and Azure logging so I can see my elasticsearch and opencensus logs writing fine but nothing is coming out of django. At the moment I am using INFO level just to see if anything comes out but I'll be adjusting those once I know things are writing out. DEBUG = False LOGGING = { "disable_existing_loggers": False, "filters": { "require_debug_false": { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'simple': { 'format': '[%(asctime)s] %(levelname)s %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, 'verbose': { 'format': '[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, }, "handlers": { "file": { "class": "logging.FileHandler", "filename": os.path.join(APP_ROOT, 'logs', 'app.log'),#"/warden/logs/arches.log", "level": "INFO", "formatter": 'verbose', 'filters': ['require_debug_false'], #,'require_debug_true'], }, 'console': { # writes to the console 'class': 'logging.StreamHandler', 'level': 'INFO', 'filters': ['require_debug_true'], 'formatter': 'verbose' }, 'azure':{ 'level': 'INFO', 'filters': ['require_debug_false'], #,'require_debug_true'], 'class': 'opencensus.ext.azure.log_exporter.AzureLogHandler', 'formatter': 'verbose' }, }, "loggers": { 'django': { 'handlers': [ 'azure', 'file', ], 'level': 'INFO', }, '': { 'handlers': [ 'azure', 'file', ], 'level': 'INFO', }, }, "version": 1 } -
Import django model class into Plotly-Dash stateless app
I'm trying to build a dashboard app using django-plotly-dash. I was able to get the app up and running when pulling the data from a .CSV file but this is slow. To speed things up I imported the data into my backend Postgresql server and created a model in the pages app in my Django project. The problem comes when I attempt to import a specific table from my model into my stateless DjangDash app in a different folder. The error I keep getting is "unable to import pages.models" Folder Structure: DjangoProject >dash_apps >finished_apps -appOne.py >pages -__init__.py -admin.py -apps.py -models.py -test.py >base -__init__.py -asgi.py -routing.py -settings.py -urls.py -wsgi.py -manage.py The app is named appOne.py and the table or class is in the models.py file and is named general_finance_metrics So far I have tried the following in my appOne.py file with no luck: from pages.models import general_finance_metrics (error is: unable to import 'pages.models' pylint (import-error)) from DjangoProject.pages.models import general_finance_metrics (error is: unable to import 'DjangoProject.pages.models' pylint (import-error)) from .models import general_finance_metrics (error is: attempted relative import beyond top-level package pylint (relative-beyond-top-level)) from base.models import general_finance_metrics (error is: unable to import 'base.models' pylint (import-error)) from base import models (error is: unable to … -
Django saving data from a template into the admin panel
I am creating basically a site where a user will fill out 5 fields on a page and then the data that the user entered get stored in the admin panel for me to view. I am not sure if this is possible. I have tried searching for what I am trying to accomplish and either my searching is bad or this isn't possible. -
Combine Latitude and Longitude figures together in real time
I modified my code after looking at at Romas post (GeoDjango: Can't save a model with PointField(), Error: SpatialProxy (POINT) with value of type: <class 'users.models.Point'>). I calculate Location by doing self.Location = Point(self.Longitude, self.Latitude). The problem with this approach is that the location is only updated when I click save (at the moment I am modifying the table via the admin page and not the front end). Is there a way of getting the Location value to be updated in real time? class Property(models.Model): id = models.AutoField(primary_key=True) User = models.ForeignKey(User, on_delete=models.CASCADE) Latitude = models.FloatField(blank=True, null=True, verbose_name='Latitude', default="00.0000000") Longitude = models.FloatField(blank=True, null=True, verbose_name='Longitude', default="00.0000000") Location = models.PointField(blank = True, null=True, srid=4326) City = models.CharField(max_length=50, default="") Street = models.CharField(max_length=60, default="") PostCode = models.CharField(max_length=60, default="") Residential = models.CharField(choices=NO_OF_HRS, max_length=60, default='1') def save(self, *args, **kwargs): self.Location = Point(self.Longitude, self.Latitude) super(Property, self).save(*args, **kwargs) -
django local static file configuration
Somehow in a Django project, I changed my config for static files. Now I have to run python manage.py collectstatic --noinput before I run python manage.py runserver. Otherwise whatever changes I made to my project will not show up. Does anyone know how to fix this? Thanks -
How to serve static files in django-tenants?
I am getting trouble configuring static files. please help. The templates are served correctly for each tenant. The directory /tenants/<schema>/ contains two folders 'static' and 'templates'. I have two schemas 'public' and 'tenant1'. So naturally, the static files are copied to /staticfiles/<schema> ie, /staticfiles/public and /staticfiles/tenant1 The problem im getting is, the server searches for static files for tenant1 in the folder /tenants/public/static/, and not /staticfiles/tenant1 or even /tenants/tenant1/static/. I am using django server and not HTTP server like apache2 or nginx. What am i doing wrong here? The following are my settings: STATIC_URL = "/static/" MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATIC_ROOT = os.path.join("F:\dev\django\\sitename", "staticfiles") MULTITENANT_STATICFILES_DIRS = [ os.path.join("F:\dev\django\\vislr", "tenants\%s\\static"), ] DEFAULT_FILE_STORAGE = "django_tenants.files.storage.TenantFileSystemStorage" MULTITENANT_RELATIVE_MEDIA_ROOT = "" # (default: create sub-directory for each tenant) STATICFILES_STORAGE = "django_tenants.staticfiles.storage.TenantStaticFilesStorage" MULTITENANT_RELATIVE_STATIC_ROOT = "" # (default: create sub-directory for each tenant) REWRITE_STATIC_URLS = False REWRITE_MEDIA_URLS = False SITE_ID = 1 STATICFILES_FINDERS = ( "django_tenants.staticfiles.finders.TenantFileSystemFinder", "django.contrib.staticfiles.finders.FileSystemFinder", "aldryn_boilerplates.staticfile_finders.AppDirectoriesFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ) MULTITENANT_TEMPLATE_DIRS = [ os.path.join("F:\dev\django\\sitename\\tenants\%s\\templates"), ] -
Can't serve Django Static folder with Nginx, GUnicorn and Docker
I am trying to deploy an django project and to finalize the development I need to access the /admin path that is on port 8000 (localhost:8000/admin/). However, the the css files are not being loaded on nginx. The way that is now, /static/ is on port 80 (localhost:80/static/) but if you open the "inspect" on admin page you will see that the static folder has to be on 8000 too. docker-compose version: '3' services: djangoservice: build: . restart: always ports: - 8000:8000 volumes: - ./django:/srv/djangoproject - ./config:/srv/config networks: - testnetwork nginx: build: context: . dockerfile: nginx.dockerfile restart: always ports: - 80:80 - 443:443 depends_on: - djangoservice networks: - testnetwork networks: testnetwork: driver: bridge nginx.dockerfile FROM node:13 as build-stage RUN mkdir -p /srv/src COPY frontend /srv/src WORKDIR /srv/src RUN rm -rf node_modules RUN npm install RUN npm run build || npm run build FROM nginx RUN mkdir -p /srv/www COPY --from=build-stage /srv/src/dist /srv/www RUN mkdir -p /srv/static COPY ./django/static /srv/static COPY config/nginx/conf.d /etc/nginx/conf.d website.conf upstream djangoserver { server djangoservice:8000; } server { listen 0.0.0.0:80 default_server; #teste server_name _; #teste root /srv/www; index index.html index.htm index.nginx-debian.html; location /static/ { alias /srv/static/; autoindex on; } location /api { proxy_pass http://djangoserver; } location / … -
Django: Sort Items in Dropdown (via field_order?)
I am using a dropdown on a template. I do want an alphabetical order in that dropdown and don't know how to get this. template.html: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset> {{ form|crispy }} </fieldset> <div> <button type="submit">OK</button> </div> </form> The context comes from views.py: def my_view(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): … return render(request, 'xxx/template.html', {'form': form}) The form is defined in forms.py: from django import forms from .models import Project class MyForm(forms.Form): project = forms.ModelChoiceField(queryset=Project.objects) field_order = ['name', ] models.py: class Project(models.Model): name = models.CharField() … The documentation talks about field_order. The line field_order = ['name', ] in form.py has no effect. What's wrong? -
!Push rejected, failed to compile Python app. -Heroku
I am getting an error when I try to deploy heroku django app. Any suggestion please, The Error is, remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to djlms. remote: To https://git.heroku.com/djlms.git ! [remote rejected] master -> master (pre-receive hook declined) requirements.txt is asgiref==3.2.7 dj-database-url==0.5.0 Django==2.2 django-ckeditor==5.9.0 django-crispy-forms==1.9.1 django-heroku==0.3.1 django-js-asset==1.2.2 gunicorn==20.0.4 Pillow==7.1.2 psycopg2==2.8.5 pytz==2020.1 sqlparse==0.3.1 whitenoise==5.1.0 And python runtime is python3.7.0. -
How to get the SMTP server response code in Django?
Goal: Hi! How can I get the SMTP response codes through Django, similar to return values given from the smtplib module??? I want to use Django's api instead of having to use that, and I see nothing in Django's email docs. I know send_mail(), send_mass_mail() , and EmailMessage.send_messages(...) all have return values that show the number of successfully delivered messages... But I want the response codes for all of them. The point is to get proof that an email is sent, bad email address, etc, like smtp response codes show. And it's looking to me like I'd have to make a custom email backend for this, and subclass from BaseEmailBackend... It's using smtplib anyway. Example code for smtplib's response code import smtplib obj = smtplib.SMTP('smtp.gmail.com', 587) response = obj.ehlo() print(response) # Obviously this doesn't send a message yet, but I want response[0] (250, b'smtp.gmail.com at your service, [111.222.33.44]\nSIZE 31234577\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8') -
Django Rest Framework link logged user to app model
When I add a new Article, I have a dropdown with a list of all registered users. I want to link the current user to the new Article. models.py from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL class Article(models.Model): title = models.CharField(max_length=100) user = models.OneToOneField(User, related_name='Article', on_delete=models.CASCADE) def __str__(self): return self.title serializers.py from rest_framework import serializers from .models import Article class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ['id', 'title', 'user'] -
Enable a function when validation from another user are met
I have a Django project that have a send SMS function but the SMS distribution needed to be only available when needed or permission granted. I have 2 users, Admin Staff Staff handles the system, and Admin handles the permissions. Now to enable Send SMS, staff needs permission to the Admin to enable the button which is disabled by default. I'm thinking like, Admin's end have a function into a button, that when the admin clicks that button, it will enable the other button on staff's end. How am I gonna do this? please help! Thanks! -
How to stop having a value error on django?
I am trying to add a follow sistem to my django project my when running my code, I am getting a The QuerySet value for an exact lookup must be limited to one result using slicing. error, It is saying that the wrong part is on this line of code of the views.py file following_obj = Following.objects.get(user=user). views.py def profile(request, username=None): profile, created = Profile.objects.get_or_create(user=request.user) if username: post_owner = get_object_or_404(User, username=username) user_posts = Profile.objects.filter(user_id=post_owner) user = User.objects.filter(username=username) is_following = Following.objects.filter(user=request.user, followed=user) following_obj = Following.objects.get(user=user) follower, following = following_obj.follower.count(), following_obj.followed.count() else: post_owner = request.user user_posts = Profile.objects.filter(user=request.user) args1 = { 'post_owner': post_owner, 'user_posts': user_posts, 'connection': is_following, 'follower': follower, 'following': following, } return render(request, 'profile.html', args1) def follow(request, username): main_user = request.user to_follow = User.objects.get(username=username) following = Following.objects.filter(user = main_user, followed = to_follow) is_following = True if following else False if is_following: Following.unfollow(main_user, to_follow) is_following = False else: Following.follow(main_user, to_follow) is_following = True resp = { 'following': is_following, } response = json.dumps(resp) return HttpResponse(response, content_type="application/json") models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png') bio = models.CharField(max_length=400, default=1, null=True) follower = models.IntegerField(default=0) following = models.IntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' class Following(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed = … -
Django how to know if a method is instance method or class method
How do I know if a method in Django is an instance method or a class method, so that when overriding, I will know to put in "self". For example: the method get_object(self, QuerySet=None) is an instance method because there is "self". However, in Django official doc, they do not explicitly write out "self" (Please see the link to the picture.) Thus, I do not know if get_object() is an instance method. link to the pic I work on VScode, and VScode doesn't have good autocompletion to show the template of get_object(self, QuerySet=None). So then again, there is no way for me to find out get_object() is an instance method. I appreciate any help! -
How to create a model that inherits from another model that inherits from Django-User model using Django generic.CreateView
I have a model named 'Category' that inherits from "django.contrib.auth.models.User" . I also have a model named 'Content' that inherits from the 'Category' model. Its like: A user can have several categories and each category can have several contents. I'm trying to create a front-end for users to create contents using "django.contrib.views.generic.CreateView" class. Do you have any ideas how might possibly that happen? tell me if you have any other ways than generic-views as well please. -
I have problem to deploy my django project with docker nginx and gunicorn
If I have running my containers on the server side and everything is okay,for accessing route on the browser should I put ip of nginx container with domain in etc/host or it have to work without that? my nginx.config server { listen 80; server_name my_domain; root /code/; error_log /var/log/nginx/new_error.log debug; location / { proxy_pass http://web:8000/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /code/staticfiles/; } location /mediafiles/ { alias /code/mediafiles/; } } where web is my docker-container with gunicorn running -
empty_form in inline formset django
i try to make an inlineformset to submit multiple forms at the same time depend on empty_form, but when i submit the form it will only save first one this is the entire snippet <form method="POST">{% csrf_token %} <div class="col-12 p-0 border-top text-center border-light row info mx-auto"> <div class="row col-12 mt-1 mx-auto"> <div class="col-6 inp text-center"> {{form.title | add_class:'col-12'}} </div> <div class="col-6 inp text-center "> {{form.logo | add_class:'col-12 d-inline'}} </div> </div> </div> <!-- order --> <div class="col-12 p-0 border-top border-light "> <table class="customeTable col-12 table-responsive-sm info text-center table1 mx-auto mb-2 "> <thead> <tr > <th>name</th> <th>year</th> <th>note</th> </tr> </thead> <tbody class="tbody tb1 "> <tr class="p-0 col-12" id="form_set"> {{formset.management_form}} {% for info in formset.forms %} <td class=""> <div class="col-12 p-0 mt-3 inp"> {{info.name | add_class:'col-12'}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{info.year | add_class:'col-12'}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{info.note | add_class:'col-12'}} </div> </td> </tr> </tbody> {% endfor %} <tfoot> <tr style="background-color: #5dbcd3;color: #ffffff;"> <th colspan="2" > <label for="">date</label> {{form.date | add_class:'col-12'}} </th> </tr> </tfoot> </table> <input type="button" value="submit"> </div> </form> <div id="empty_form" style="display: none;"> <tr class="p-0 col-12"> <td class=""> <div class="col-12 p-0 mt-3 inp"> <input class="col-12 qarz" type="number" name="" placeholder="qarz"> </div> </td> <td … -
Django / Python - Convert image from AWS S3 bucket to Base64?
I'm trying to convert each image instance to base64. All images are stored in my amazon-s3 bucket. Unfortunately, my generated encryption is not displaying the image at my recipe_plain.html template. Any help is appreciated. views.py ... import base64 class RecipePlainView(DetailView): model = Recipe template_name = 'recipes/recipe_plain.html' def get_context_data(self, **kwargs): context = super(RecipePlainView, self).get_context_data(**kwargs) image = self.object.image image.open(mode='rb') context['recipe_image_base64'] = base64.b64encode(image.read()) image.close() return context recipe_plain.html <img src="data:image;base64,{{ recipe_image_base64 }}" alt="{{ recipe.image.name }}"> Here is one of the images for the testing purposes: baketoom-recipes-files.s3.amazonaws.com/default.jpg... When run by the RecipePlainView(), context['recipe_image_base64'] returns the following string found in the snippet: copyText = document.getElementsByTagName('textarea')[0]; document.getElementsByTagName('button')[0].onclick = function() { copyText.select(); document.execCommand('copy'); console.log('Copied') } document.getElementsByTagName('span')[0].innerHTML=copyText.innerHTML.length+' Characters in total.' <textarea style="width: 100%; min-height: 50px"> b'/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAEsASwDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD3+iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKpatq1joemTajqM6wW0K5Z2/kB3J7CgC7RXKeEviFonjJ7iPTzPFPBy0VwoViv94YJBFdXQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFVNU1Sz0bTZ9Qv51gtoV3O7fyHqfagBuq6rZaJpk+oahOsNtCu5mb+Q9SfSvmHx548vvGup7m3Q6bCx+z22en+03qx/SnePvH17401L+KDTIWP2e2z/483qx/SuPoA0tB1u68Pazb6laMQ8TfMoP31PVT9a+rPDWu2+u6TBeW7hklQMP8K+Qa9T+DniC4tL+5012JtSPNXP8LZwR+P8ASgD6GopkMgljDDvT6ACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKq6jqNppOnzX9/OkFtCu55GPAH+PtQAmp6nZ6Pp09/fzrDbQrud2/z1r5j8f+P7zxpqO1d0Glwt+4t89f9tvU/wAqf8QfiDd+M9Q8uPfBpULfuIM8t/tv7+3auKoAKKKsWVlPf3S28C7nb8gPU0AFlZT6hdLbwLl26nso9TXrfg7QBYOkdupZiQZJCOWNVvDPhlbdFggXc7f6yTHLH/CvXtB0KOxhVmUbqANixQx2qK3XFWaAMDAooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiq9/f2umWM17ezpBbQqWeRzgAUAJqGoWmlWE19fTpDbQrud2PAFfMvxC+IV34zvzDCXg0mFv3MOeXP99vf27U/4ifES68ZXxt7cvBpELfuoTwZD/ff39B2rhqACi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JVWO3VQOygCups9NtIwNsQoA8e0H4SQqyyXm+4b0bhfyr03SfCNpYxooiRVXoqjAFdMkaIPlUCn0AQw20UC4RQKmoooAKKKKACiiigAooooAKKKKAP//Z' </textarea> <br> <span></span> <br><br> <button>Copy All</button> : -
Access values from joined table in django
I have 2 tables linked together by a foreign key (Category, Activity). I'm trying to access the values in the category table from my query using the activity object. Model class: class Category(models.Model): name = models.CharField(max_length=100) weekly_goal = models.IntegerField(blank=True, null=True) metacat_fk = models.ForeignKey(MetaCategory, models.DO_NOTHING, db_column='metacat_fk') class Meta: managed = False db_table = 'category' class Activity(models.Model): name = models.CharField(unique=True, max_length=100) distance = models.FloatField(blank=True, null=True) duration = models.TimeField(blank=True, null=True) date = models.DateField(blank=True, null=True) note = models.CharField(max_length=100, blank=True, null=True) category = models.ForeignKey(Category, models.DO_NOTHING, db_column='category_fk') class Meta: managed = False db_table = 'activity' Trying to access the values in Category: activity = Activity.objects.select_related('category') frequency_df = pd.DataFrame(list(activity.values())) logging.warning(activity.query) logging.warning(frequency_df.head()) Output: SELECT "activity"."id", "activity"."name", "activity"."distance", "activity"."duration", "activity"."date", "activity"."note", "activity"."category_fk", "category"."id", "category"."name", "category"."weekly_goal", "category"."metacat_fk" FROM "activity" INNER JOIN "category" ON ("activity"."category_fk" = "category"."id") id name distance duration date note category_id 0 1382 Yoga - Wednesday June 19 2019 None None 2019-06-19 Yoga 3 1 1385 Yoga - Wednesday September 18 2019 None None 2019-09-18 Yoga 3 2 1388 Yoga - Tuesday October 08 2019 None None 2019-10-08 Yoga 3 3 1391 Yoga - Tuesday October 15 2019 None None 2019-10-15 Yoga 3 4 1394 Yoga - Saturday October 26 2019 None None 2019-10-26 Yoga 3 According to … -
how to update django databsae from html?
I want to only update the brand. So I want to see if I can get the post from the input. print(request.POST.get('brand')) didn't print anything, but I can get print(request.POST.get('url')). Does anyone know why? Here is my base.html code. <form action="{% url 'script' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group w-75"> <input type="text" name="url" id="url" class="form-control"> </br> <button type="submit" class="btn btn-success btn-lg btn-block">submit</button> </div> </br> {% if alldata %} <table class="table table-striped table-sm" id=""> <thead> <tr> <th>Price</th> <th>Asin</th> <th>Rank</th> <th>Brand</th> <th>CPU</th> <th>Update</th> </tr> </thead> <tbody> {% for data in alldata %} <tr> <td>{{ data.price }}</td> <td> <a href="{{ data.link }}">{{ data.asin }}</a> </td> <td>{{ data.rank }}</td> <td> <div> {{ data.brand }} <input type="text" name="brand" id="brand" value="{{data.brand}}"> <button type="submit">Update</button> </div> </td> <td>cpu</td> <td><button type="submit">Update</button></td> </tr> {% endfor %} </tbody> </table> {% endif %} </form> -
I want to show the Default pic to the user profile whenever a new user is registered using Signals without doing it manually from Django admin
I want to load the default pic of the user, whenever a new user is created using signals. But its not loading the default pic. I don't want to do this manually from Django admin, I want this to be done whenever a new user is created in the app. models.py from django.db import models from django.contrib.auth.models import User class userprofile(models.Model): user = models.OneToOneField(User,on_delete = models.CASCADE) profilepic = models.ImageField(default='pp.png',upload_to='profile_pic',blank = True) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import userprofile class ProfileUpdateForm(forms.ModelForm): class Meta: model = userprofile fields = ['profilepic',] views.py @login_required def profile(request): if request.method == 'POST': p_form = ProfileUpdateForm(request.POST,request.FILES,instance=request.user.userprofile) if p_form.is_valid(): p_form.save() return render(request,'profile.html') else: p_form = ProfileUpdateForm(instance=request.user.user) context = { 'p_form': p_form } return render(request,'profile.html',context) profile.html <form method ="POST" class="sm:w-1/3 text-center sm:pr-8 sm:py-8" enctype="multipart/form-data" > {% csrf_token %} <img id="profile_pic" alt="team" class="flex-shrink-0 rounded-lg w-full h-56 object-cover object-center mb-4" src="{{user.userprofile.profilepic.url}}"> {{ p_form|crispy }} <br> <input id="file-input" style="padding: 8px 93px;" class="text-white bg-green-500 border-0 py-2 px-8 focus:outline-none hover:bg-green-700 rounded text-lg" type="submit" value="Upload"> </form> signalspy from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import userprofile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: userprofile.objects.create(user=instance) @receiver(post_save, sender=User) … -
Django Google Analytics API / Get age and gender information
Is there a way to pull demographic information from Google to my Django website via API method? For example, I need to write 2 extra information in a post, gender and age. Is there a way for me to print this information to my own database via google analytics? like this; read this article 41% male and 59% female. -
Django MPTT how to create children for loop and remove standard li formatting in browser
I am trying to create a small form under each child that lets you create a subchild to that child. But when i run a standard django for loop it returns a strange result in the browser. This is what works, but as said i want to create a custom form for each child. {% load mptt_tags %} <ul> {% recursetree goal %} <li> {{ node.title }} {% if not node.is_leaf_node %} <ul class="children"> {{children}} </ul> {% endif %} </li> {% endrecursetree %} </ul> So this is what i tried which doesn't work {% load mptt_tags %} <ul> {% recursetree goal %} <li> {{ node.title }} {% if not node.is_leaf_node %} <ul class="children"> {% for child in children %} {{child}} #add subchild to child form here {% endfor %} </ul> {% endif %} </li> {% endrecursetree %} </ul> Also, how do a return only the title of each node without having MPPT creating it in a list format for me? Advice greatly appreciated! -
Can't authenticate Tag Manager API through OAuth in Django when deployed on Google App Engine
I have a Django app that access data from Google Tag Manager using its API. It works fine locally, but when it is deployed and I try to authenticate, I get this message: UserWarning: Cannot access tagmanager.dat: No such file or directory Your browser has been opened to visit: https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%........... If your browser is on a different machine then exit and re-run this application with the command-line parameter --noauth_local_webserver And the browser doesn't open a new window for authentication which leads to a timeout error. views.py import argparse import sys import os import httplib2 from apiclient.discovery import build from oauth2client import client from oauth2client import file from oauth2client import tools import pandas as pd def GetService(api_name, api_version, scope, client_secrets_path): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) flags = parser.parse_args([]) credentials = run_flow(flow, storage, args) flow = client.flow_from_clientsecrets( client_secrets_path, scope=scope, message=tools.message_if_missing(client_secrets_path)) storage = file.Storage(api_name + '.dat') credentials = storage.get() if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, flags) http = credentials.authorize(http=httplib2.Http()) service = build(api_name, api_version, http=credentials.authorize(http=httplib2.Http())) return service I have also tried to add flags.noauth_local_webserver = True as suggested here, but no luck. My API configuration is as follows: Client ID for Web Application Authorised JavaScript origins URI: https://myapp.appspot.com Authorised redirect … -
AttributeError: 'WSGIRequest' object has no attribute 'site' - wagtail, wagalytics
I'm trying to implement wagalytics within my new wagtail site (https://github.com/tomdyson/wagalytics). I'm my error pops up at line 138 of views.py site = Site.objects.get(hostname=request.site.hostname) AttributeError: 'WSGIRequest' object has no attribute 'site' When I change this to something like try: site = Site.objects.get(hostname=request.site.hostname) except: site = '127.0.0.1' It works - or at least gets me onto the next problem. Obviously I don't want to go chopping in a try/except block into the code in production - and I'd be better off for an understanding of what's happening here and how to resolve it.