Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn issues on gcloud. Memory faults and restarts thread
I am deploying a django application to gcloud using gunicorn without nginx. Running the container locally works fine, the application boots and does a memory consuming job on startup in its own thread (building a cache). Approx. 900 MB of memory is used after the job is finished. Gunicorn is started with:CMD gunicorn -b 0.0.0.0:8080 app.wsgi:application -k eventlet --workers=1 --threads=4 --timeout 1200 --log-file /gunicorn.log --log-level debug --capture-output --worker-tmp-dir /dev/shm Now I want to deploy this to gcloud. Creating a running container with the following manifest: apiVersion: extensions/v1beta1 kind: Deployment metadata: name: app namespace: default spec: selector: matchLabels: run: app template: metadata: labels: run: app spec: containers: - image: gcr.io/app-numbers/app:latest imagePullPolicy: Always resources: limits: memory: "2Gi" requests: memory: "2Gi" name: app ports: - containerPort: 8080 protocol: TCP Giving the container 2 GB of memory. Looking at the logs, guniucorn is booting workers [2019-09-01 11:37:48 +0200] [17] [INFO] Booting worker with pid: 17 Using free -m in the container shows the memory slowly being consumed and dmesg shows: [497886.626932] [ pid ] uid tgid total_vm rss nr_ptes nr_pmds swapents oom_score_adj name [497886.636597] [1452813] 0 1452813 256 1 4 2 0 -998 pause [497886.646332] [1452977] 0 1452977 597 175 5 3 0 447 … -
Faker in Django: Instance of 'Generator' has no 'name' memberpylint(no-member)
I am new to Python. How do I resolve the following problem in Django and faker? import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings') import django django.setup() import random from first_app.models import Customer from faker import Faker fakegen=Faker() def populate(N=5): for entry in range (N): fake_name=fakegen.name() fake_street=fakegen.street_name() fake_suburb=fakegen.city() fake_city=fakegen.city() fake_phone=fakegen.phone_number() fake_email=fakegen.mail() fake_website=fakegen.url fake_bus=fakegen.company customer=Customer.objects.get_or_create(name=fake_name,street=fake_street,suburb=fake_suburb,city=fake_city,phone=fake_phone,email=fake_email,website=fake_website,bus_type=fake_bus)[0] if __name__=='__maine__': print('populating script') populate(20) print('population complete') I am getting this error: Instance of 'Generator' has no 'name' memberpylint(no-member) -
deploy to IBM bluemix
I created a project on the django and I want to deploy it at a free rate in IBM. I have the project files in the path: /home/permi/source/repos/eCommerce_Django/src/ and such a structure: -eCommerce_Django __init__.py ... settings.py urls.py ... views.py wsgi.py -pack1 module1.py ... moduleN.py -pack2 ... -packN ... manage.py db.sqlite3 requirements.txt -static_cdn ... it all works under a virtual environment Questions: 1. where do i put the manifest file? 2. what should I indicate in it? these questions are related, so I ask together Note: (file structure manifest.yml) applications: - name: <application-name> memory: 256M # This is command provided by cf -c option command: bash ./run.sh buildpack: https://github.com/cloudfoundry/python-buildpack path: . declared-services: <services-name>: label:postgresql plan:100 services: - <services-name> took from here: https://github.com/fe01134/djangobluemix -
How to migrate a project from another project
I have 2 django projects. Let's named them project-a and project-b. I'm trying to run migrate command from project-a to change project-b. I've also use os.system to run commands. this is my code def post(self, request, *args, **kwargs): os.system('django-admin migrate --settings=absolute/path/to/project-b/setting/module') return Response(status.HTTP_200_OK) Is it possible to set absolute path to --setting? -
how to add "search by usernane or email address" field in django forgot password
this is a django default forgot password form. how to modify to add "search by username" feature. for example "username/email". can someone help me with this. i am a noob in django. just started learning. def get_users(self, email): active_users = UserModel._default_manager.filter(**{ '%s__iexact' % UserModel.get_email_field_name(): email, 'is_active': True, }) return (u for u in active_users if u.has_usable_password()) def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None, html_email_template_name=None, extra_email_context=None): """ Generate a one-use only link for resetting password and send it to the user. """ email = self.cleaned_data["email"] for user in self.get_users(email): if not domain_override: current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override context = { 'email': email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'user': user, 'token': token_generator.make_token(user), 'protocol': 'https' if use_https else 'http', **(extra_email_context or {}), } self.send_mail( subject_template_name, email_template_name, context, from_email, email, html_email_template_name=html_email_template_name, ) -
How do I upload a file using ajax with django?
I'm new to this. Could you show me how to send a file to server using ajax. I could submit to my server a String, but I don't know how would ajax handle a File? upload_stuff.js $(document).on('submit', '#CustomerRequest', function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/create_request', data:{ ajax_file1:$('#html_file1').val(), ajax_file2:$('#html_file2').val(), ajax_file2:$('#html_file3').val(), ... view.py def create_request (request): if request.method == "POST": server_file1 = request.FILES('ajax_files1') server_file2 = request.FILES('ajax_file2') server_file3 = request.FILES('ajax_file3') I do have csrf_token and and enctype="multipart/form-data" on my html form -
django send_mail has insecure link to http://dpaste.com/
I am trying to send emails with django and for that I use send_email from django.core.mail, but it has a link to http://dpaste.com/, with HTTP and my website is in HTTPS. This is the message I get in my console: Mixed Content: The page at 'https://b...' was loaded over a secure connection, but contains a form that targets an insecure endpoint 'http://dpaste.com/'. This endpoint should be made available over a secure connection. It means that the standard send_mail from django blocks my secure connection? How can that be possible? What othe solutions do I have to send email with django? Thanks -
Reverse for "password_reset_confirm" not found. " Password_reset_confirm" is not a valid view function or pattern name
I'm implementating the custom password reset from this https://ruddra.com/implementation-of-forgot-reset-password-feature-in-django But it says reverse for "password_reset_confirm" not found. I am using Django 2.2.3 -
What;s the DISABLE_COLLECSTATIC=1
When I was trying to push files to heroku there was error and olution was to use this code heroku config:set DISABLE_COLLECSTATIC=1 But I don't pretty understand what it does and what is the collectstatic generally -
How to fix the error for django 'django.core.exceptions.ImproperlyConfigured' with urls?
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')), ] There is an error when i add url to url.py. when i run the code in terminal : 'python manage.py runserver' ; then the follwing error is displayed in the terminal - django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'polls.urls' from 'C:\\Users\\Administrator\\PycharmProjects\\website2\\mysite\\polls\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I searched everywhere for the solution but i couldn't find it. Please help me to get out of it. -
How to access Prfile object if I have User object
class MyUser(AbstractUser): mobile=models.TextField(max_length=10, blank=True) bio = models.TextField(max_length=500, blank=True) city = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True,related_name="userprofile") exam=models.ManyToManyField(Exam, blank=True, related_name="profile") education=models.TextField(max_length=20, blank=True) branch=models.TextField(max_length=20, blank=True) # My views.py code profile=Profile(user=user) context = { "user": request.user, "papers":Paper.objects.all(), "form":form, "profile":profile, } return render(request, "demo/user.html", context) I Have user object, I want to access profile object related to that. Please explain me. -
Django ORM filter with timezone.now() will make python process spike 100%
I am using django orm to filter two tables, lets say the table is User and Transaction. My goal is to get user that have transaction between 1 month. User table i use user_auth(provided by django) And for Transaction: in MySQL: +-------------------+---------------+------+-----+---------+-----------------+ | Field | Type | Null | Key | Default | >Extra | +-------------------+---------------+------+-----+---------+-----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | transaction_date | datetime | NO | MUL | NULL | | | user_id | int(11) | YES | MUL | NULL | | +-------------------+---------------+------+-----+---------+-----------------+ in Django models: class Transaction(models.Model): user = models.ForeignKey(User, blank=True, null=True, db_column='user_id') transaction_date = models.DateTimeField(db_index=True) class Meta: db_table = 'transaction' Then i select from table user using: from django.utils import timezone from dateutil.relativedelta import relativedelta today = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0) last_month = today - relativedelta(months=1) user_list = User.objects.all().values_list('id', flat=True) trx_user_list = Transaction.objects.filter(user_id__in=user_list, transaction_date__gte=last_month, transaction_date__lt=today).values_list('user_id', flat=True).distinct() This will make my python process spike into 100% if i using timezone.now() for filter. I am using Python 2.7 and django 1.1. The data for user is around 400k. Actually the issues has been solve when i use datetime.now() it will make python process back normal. But im just curious, … -
Django: Could not parse the remainder: '=' from '='
I am following this tutorial https://tutorial.djangogirls.org/en/extend_your_application/ but getting Templatesyntax error when trying to pass pk from html to url using path method. With what i have read about this error this has something to do with braces and quotes but in this case i am not able to figure out the exact problem with the syntax. This the listview.html {% for vehicle_list_load in vehicle_list_loads %} <tr> <td>{{vehicle_list_load.vehicle_num}}</td> <td>{{vehicle_list_load.Driver_name}}</td> <td>{{vehicle_list_load.BusinessUnit}}</td> <td>{{vehicle_list_load.CheckinTime}}</td> <td>{{vehicle_list_load.Type}}</td> <td> <a href= "{% url 'vehicle_movement:checkoutview' pk = vehicle_list_load.pk %}" class = "glyphicon glyphicon-pencil" aria-hidden ="true" > Edit</a> </td> </tr> {% endfor %} this is vehicle_movements urls.py from django.urls import path from vehicle_movement import views app_name = 'vehicle_movement' urlpatterns = [ path('checkoutview/<int:pk>/',views.checkout, name = 'checkoutview'), ] this is main urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include(('vehicle_movement.urls','vehicle_movement'),namespace = 'vehicle_movement')), ] This is the view def listView(request): vehicle_list_loads = list(Checkin.objects.all().filter(Type ='Loading')) vehicle_list_unloads = list(Checkin.objects.all().filter(Type ='Unloading')) current_time = datetime.utcnow().replace(tzinfo=utc) diff = current_time return render(request,'vehicle_movement/listView.html', {'vehicle_list_loads':vehicle_list_loads,'vehicle_list_unloads':vehicle_list_unloads,'diff':diff}) on clicking on edit this view needs to open def checkout(request,pk): post = get_object_or_404(Checkin, pk= pk) return render(request,'vehicle_movement/checkout.html',{'post':post}) -
Android + Django chatting , help me
I am currently developing an app using the Django framework. I need to implement chat, but I lack information using the django framework on Android. If you have any information or examples, please help. I'm developing using kotlin, but I also welcome examples using java. -
How to increment counter on button click using Django
New to Django, and I'm stuck on a problem. I have several buttons on a page, each is an instance of a simple Color object I created. The object has attributes of 'name'(string),'hex'(string), and 'count'(integer). I want to be able to keep track of how many times each button is pressed; so, for example, if someone presses the button associated with 'Red,' it will Post to the database that the 'count' attribute for Red should increment by 1. This is basically how the 'vote' function works in the app they show in the Django documentation, but I cannot figure out how to apply it to my program, even though mine is simpler. Any advice is appreciated. Please let me know if I've posted enough code to determine the issue. from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from .models import Color ### function in question ### def detail(request, colorname): bodybg = colorname colorslist = Color.objects.all() colorcount = 0 for color in colorslist: if colorname == color.hex: colorcount = color.count colorCounterObj = get_object_or_404(Color, pk=colorcount) selected_color = colorCounterObj.choice_set.get(pk=request.POST['choice']) selected_color.count += 1 selected_color.save() context = { 'bodybg' : bodybg, 'colorslist' : colorslist, 'colorcount' : colorcount, } template … -
How to Solve : Value Error invalid literal for int() with base 10: 'Shuk'?
Hello , so i have been realy struggling with that problem when trying to list all Animes Objects on my Database (api) class AnimesViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.AllowAny ] queryset = Animes.objects.all() serializer_class = AnimesSerializer @action(methods=['get'],detail=False) def types(self,request): return Response(getTypes()) @action(methods=['get'],detail=False) def _action(self,request): li = Animes.objects.all().filter(types__icontains='action') result_list = li.values('id', 'title', 'coverLink', 'yearProd', 'rates', 'types', 'story') return Response(result_list) when visiting : localhost:8000/api/animes/types/ => this works fine ! localhost:8000/api/animes/_action/ => this works fine ! localhost:8000/api/animes/ => this Does not work (shows the problem im having) ! serializer.py : class AnimesSerializer(serializers.ModelSerializer): class Meta: model = Animes fields = ('id', 'title', 'coverLink', 'yearProd', 'rates', 'types', 'story') router.py : from rest_framework import routers from .api import AnimesViewSet router = routers.DefaultRouter() router.register('animes', AnimesViewSet, 'animes') urlpatterns = router.urls models.py : class Animes(models.Model): title = models.TextField() animePageLink = models.TextField() pageNum = models.IntegerField() coverLink = models.TextField() yearProd = models.IntegerField() rates = models.DecimalField(max_digits=10,decimal_places=1) types = models.TextField(null=True) story = models.TextField() def types_to_list(self): return self.types.split(',') urls.py : path('api/',include('animes.router')), Example of single Instance of Animes : {"id":2,"title":"Mo Dao Zu Shi","coverLink":"https://xxx/test.jpg","yearProd":2018,"rates":"8.6","types":"action,adventure,historical,mystery,supernatural,comedy","story":"test story..."} Hopefully You guys could spot the problem and help me out solving this , Spent way tooo much days googling and trying diffrent solutions ! PS : im still new at Django … -
Piecing together DRF, auth, and registration
I want some advice on choosing right package in a REST Api django project For authentication:Which one of below I should choose ? django-oauth-toolkit: seems to be the most robust and recommended oauth library for DRF. This do not have account management. How can i implement account management with this package? If yes, can I get some guide. django-rest-auth: API endpoints for authentication, and basic account management for DRF. But seems not as robust as django-oauth as django-oauth allows token expiery etc. or i am missing some feature of rest-auth For authorisation: I will be going for django-guardian over django-role-permission. Later seems more like back end utility to control user roles. My deep desire is to use oauth-toolkit but it does not have basic user management. On the contrary rest-auth has user management but lacks (seems to be) roubustness of oauth. Please help me make a choice. -
Adding new values from forms to existing ones in django
I want to add up numbers of a numbers am getting from a form to existing ones in my model have. I have a model with integer field. i want any new data taken should sum up with the existing on in the model if. Let New-value + Old-value then save the answer. I tried using the update not i end up replacing the value and not add them up. But i want that anytime a new value is coming from my form, it should add up with already existing value in voters field. Model.py class Nomination(models.Model): Fullname = models.CharField(max_length=120) Nominee_ID = models.CharField(max_length=100) Category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to='nominations_images') slug = models.SlugField(max_length=150) votes = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.Fullname Views.py if res.status_code == 200 and int(amount[:-2]) > 0: Nomination.objects.filter(slug=slug).update(votes=amount[:-2]) return redirect('/success') else: # error page here return render(request, 'Payment.html') -
Django Production Site keeps going down after 3 weeks
I am running a website using Django, Gunicorn and Nginx off a Digital Ocean droplet. The website runs fine for about three weeks and then it random stops connecting users to the webpage. When I visit the webpage in my browser it returns: This site can’t be reached ERR_CONNECTION_RESET Restarting the droplet fixes the issue, but it will likely happen again after three weeks. When I check the Gunicorn worker it says its running fine and my Django logs are clean. Nginx reported this: 2019/08/31 23:11:56 [error] 28183#28183: *36352 open() "/home/projects/server/mysite/static/img/icon.jpg" failed (2: No such file or directory), client: 66.249.64.149, server: removedurl.com, request: "GET /static/img/icon.jpg HTTP/1.1", host: "removedurl.com.com" What else could I check? -
Gunicorn does not show Django static files
I've seen this question asked before but none of the responses have helped. I'm trying to deploy my Python3/Django project to AWS with gunicorn + nginx. The project name is vicver, and when I try to run $ gunicorn --bind 0.0.0.0:8000 vicver.wsgi I can see my site on the AWS public IP port 8000 but without any js/css or images. When I do the same with the runserver command it works fine. My settings.py contains the following paths: STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'vicver/static') ] And here's a screenshot of the terminal https://imgur.com/a/KhgcXeT -
Django: Slow loading icons, wrong icon briefly "flashed"
When I load my web template for the first time, for about 1/2 second one letter/icon is briefly flashed/shown, then later is replaced by the intended icon. How can I prevent this to happen, either by not show icons until they are fully loaded or show the correct one directly. In my base template I refer to a folder within which I have the icons <link rel="stylesheet" type="text/css" href="{% static 'product/slib/Ionicons/css/ionicons.css' %}"> Then I refer to the icon I would like to show <i class="icon ion-ios-compose-outline"></i> When I load the page for the first time (or reload cache), for about 1/2 second this text/sign is flashed Then the intended icon is showed: Please let me know if more information is needed in order to understand what is going on, and how to fix it. -
How to correctly configure volumes with docker-compose for a Django app using postgres?
I have a dockerized Django application using Postgresql. Everything runs find until I add volumes to the docker-compose file so I can have persistent data storage for the DB. docker-compose.yml : version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=dbpassword depends_on: - db db: image: postgres:10-alpine volumes: - ./postgres-data:/var/lib/postgresql/data environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=dbpassword ports: - "5432:5432" Error Message here: django.db.utils.OperationalError: could not connect to server: Connection refused app_1 | Is the server running on host "db" (172.26.0.2) and accepting app_1 | TCP/IP connections on port 5432? app_1 | recipe-api_app_1 exited with code 1 db_1 | 2019-08-31 22:52:35.969 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2019-08-31 22:52:35.969 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2019-08-31 22:52:35.972 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2019-08-31 22:52:36.042 UTC [18] LOG: database system was shut down at 2019-08-31 22:41:04 UTC db_1 | 2019-08-31 22:52:36.055 UTC [1] LOG: database system is ready to accept connections Once you add the volumes … -
style.background-image not event sending http request
Well i'm trying to set a background-image for div in a dynamic way from the backend, I am using django (djangorestframework) as backend I am sending a http request and this is the data I recv { "user": "1ad54d3c-a012-431a-9e7a-8630fd9fb566", "image": "api/media/users/1ad54d3c-a012-431a-9e7a-8630fd9fb566/tutorials/yyyy/_image/tutorialImage.png", "title": "yyyy", "description": "hgdhgdh", "level": "professional", "parts": 0, "offical": false } now this is the html <div class="tutorial-card"> <div class='tutorial-img' [style.background-image]="getTutorialImgURL(tutorial.image)"> </div> the getTutorialImageURL function: public getTutorialImgURL(path: string){ return `url("http://${config.backendDomain}/${path}")`; } // config.backendDomain is "localhost:8000" then is doesn't even send a get request to the backend (the url path is right) but when I changing the prefix from http to https it sends the request to the backend server but the backend doesn't yet supporting https only http and I have tried to stylebypass with DomSanitizer still same results correct URL but doesn't even send the get request (no I don't want to use <img [src]='...'>) -
how to create a set of classes and its vars and methods form a given text in python
i want to create a set of classes, its vars and methodes just form a given text configuration, espcially with django models, for exmaple i have a list of models classes=["users", "posts", "commnets"] vars= [{"a","b"},{"bb","vv"},{"aa"}] #methods=[{....},{....},{....}] not now in models.py i want to make something like this to create that classes for i,j in zip(classes,vars): create_classes_from_string(i,j) how can i program #create_classes_from_string assuring that it creates tables in my database with that configuration -
How to associate an avatar a user with cloudinary / Django?
I am trying to configure cloudinary on my Django project. The current configuration resizes avatars of users and hosts them on cloudinary servers. I would like to associate the public key of is avatar with the id of the users so that when a user wishes to change his avatar the old one is overwritten by the new one. I would also like that when a user deletes his account, the associated avatar either deletes cloud servers I do not know if this idea of associating the public key with the user identifier and a good practice or if there is another way to do it? Here is what I have naively tried to do for the moment: forms.py class ProfileUpdateForm(forms.ModelForm): image = forms.ImageField(label='', required=True, widget=forms.FileInput) class Meta: model = Profile fields = ['image'] views.py @login_required def account_edit(request): p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if request.method == "POST": if p_form.is_valid(): p_form.save() messages.success(request, _(f"Your image has been successfully uploaded!")) return redirect('account_edit') else: messages.error(request, _(f"Image files only")) return redirect('account_edit') else: p_form = ProfileUpdateForm(instance=request.user.profile) models.py from cloudinary.models import CloudinaryField class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = CloudinaryField("avatar", folder = "avatar/", public_id = request.user.pk, # NameError: name 'request' is not defined notification_url = "https://dashboard.heroku.com/apps/register-start/avatar", …