Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I not redirect to a success_url in Django after I make a post using a modal form and stay on the current page?
Here is my problem, I have a model medication that has a foreignkey field drug. In the create view of medication if a certain drug is not found in the record, I would like to create it on the go. So I tried using django-bootstrap-modal-forms from PyPi which basically does what it says. However, when I make a post to create a new drug, I get redirected to the DetailView of the drug even I did not explicitly specify success_url in the DrugCreateView. I have tried searching for probable solutions on the internet and also some similar problems people have in stackoverflow. I have not found an answer to my question so far. I do not want this behavior. What I want is to stay in the medication create view and reload the page if necessary to update the foreignkey drug field as I have just added it in the database. I would really appreciate if you can help or at least give me a clue on how am I going to accomplish this. Please tell what other information I have to give and I will gladly provide it immediately. -
Is omitting imprts in python for performance reasonable?
So I've been wondering weather neglecting DRY rule instead of importing is good for performance in python and django. I know that when something is imported in python it needs to run it to search for bugs, so what I do here seems reasonable, but I also know that User is imported elsewhere in my project so do I actually gain anything by aproach shown below? # from django.contrib.auth.models import User class RegistrationForm(forms.ModelForm): """ Registration form for User. Import omitted for performance. """ password_1 = forms.CharField(required=True, widget=forms.PasswordInput) password_2 = forms.CharField(required=True, widget=forms.PasswordInput) username = forms.CharField() email = forms.CharField(widget=forms.EmailInput) # class Meta: # model = User # fields = ('username', 'email') -
In the Wagtail admin how to disable summary items of Images and Documents?
I know that I can get rid of the Pages summary by using the hook, however Images and Documents still remain. @hooks.register("construct_homepage_summary_items") def hide_images_and_documents_from_partners(request, summary_items): if request.user.groups.filter(name="Partners").exists(): summary_items.clear() -
Django fetch from dictionary based on F('pk') failing because it expects int or slice, not F?
this has got me really confused. I wanted to make recurring Events, and so I decided to use Django's RecurrenceField, and then realized there is no way to filter on the field. In order to get upcoming events, I have to do many queries instead of just a minimum, and it's driving me crazy. Below is a function (which doesn't work) I drafted to fetch the upcoming events. def get_future_events(): future_events = None non_recurring_today_events = Events.objects.filter(is_deleted=False, status='Live', event_date=timezone.now().date(), event_time__gt=datetime.now(), recurrences__isnull=True).annotate(next_date=F('event_date')).order_by('event_date', 'event_time') non_recurring_future_events = Events.objects.filter(is_deleted=False, status='Live', event_date__gt=timezone.now().date(), recurrences__isnull=True).order_by('event_date', 'event_time') future_events = non_recurring_today_events | non_recurring_future_events recurring_events_ids_for_future = list() recurring_events_dates = dict() recurring_events = Events.objects.filter(is_deleted=False, status='Live', event_time__gt=datetime.now(), recurrences__isnull=False).order_by('event_time'); for event in recurring_events: if(event.recurrences.count(dtstart=datetime.now()) > 0): recurring_events_ids_for_future.append(event.event_id) recurring_events_dates[event.pk] = event.recurrences.after(datetime.now(),inc=True) # This line gives the error: recurring_events_for_future = Events.objects.filter(is_deleted=False,event_id__in=recurring_events_ids_for_future).annotate(next_date=recurring_events_ids_for_future[Value(F('pk'), output_field=IntegerField())]).order_by('next_date', 'event_time') future_events = future_events | recurring_events_for_future future_events = future_events.order_by('next_date', 'event_time') return future_events I thought I was good to go, but then I got this error: list indices must be integers or slices, not F. If anyone has any other ideas, please help me out. Thank you in advance. These are the important fields in the Events model: class Events(models.Model): event_id = models.BigAutoField(primary_key=True) event_date = models.DateField(null=True) event_time = models.TimeField(null=True) TYPE = (('Live', 'Live'), ('Archived', 'Archived')) … -
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.