Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to access any static file through functions in views.py in django?
I need to open an image file stored under static folder in views.py file. I am using PIL from PIL import Image im=Image.open('home/..../static/images/download.jpeg') it is giving error of no such file exits -
Django only get the data associated with that specific User (get_queryset)
So I have a django project were users can log in, when they have logged in I want them to see the data associated with them. Let's say an assignment is connected to a user with a ManyToManyField. That User should be able to se it, but people who are not connected should not. class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'All Users' def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_data(sender, update_fields, created, instance, **kwargs): if created: user = instance profile = UserProfile.objects.create(user=user) class Assignment(models.Model): name = models.CharField(max_length=100) canview = models.ManyToManyField(UserProfile, blank=True, related_name="canview") @login_required def DetailAssignment(request): obj = Assignment.objects.all() username = request.user.username context = { 'object': obj, 'MyName': username } return render(request, 'nav-side-project.html', context) def UserDetailAssignment(DetailAssignment): def get_queryset(self): return Assignment.objects.filter(canview__user=self.request.user) -
Having problem to migrate from fbv to cbv in django CreateView which my model is not submitted in my models
I'm trying to migrate from FBV to CBV and I encountered a problem which I completely don't know how to solve it, which is after enter a submit to insert a new news to my model, it doesn't do that, and it doesn't show anything. news/views from django.shortcuts import render , get_object_or_404 # Create your views here. from django.views.generic import ListView, DetailView , CreateView from .models import PreNews class NewsListView(ListView): model = PreNews template_name = 'news/main_news.html' queryset = PreNews.objects.order_by('-date') class NewsDetailView(DetailView): model = PreNews template_name = 'news/sub_news.html' #slug_url_kwarg = 'slug' def get_object(self): slug_ = self.kwargs.get('slug') return get_object_or_404(PreNews,slug=slug_) class NewsCreateView(CreateView): model = PreNews template_name = 'create/news_create.html' fields = '__all__' succes_url = '/news/' news/models from django.db import models from pages.models import LoginFormModel from django.urls import reverse # Create your models here. class PreNews(models.Model): hardware = 'chw' software = 'csw' politics_iran = 'pir' politics_international = 'pin' news_choice = [ (hardware,'computer hardware news'), (software,'computer software news'), (politics_iran,'iran politics'), (politics_international,'international politics'), ] author = models.ForeignKey('pages.LoginFormModel', on_delete = models.CASCADE ,) title = models.TextField(max_length=100,null=False) tags = models.TextField(default='sobhan esfandyari,') choice = models.CharField(max_length=3 , choices=news_choice , default=software) slug = models.SlugField(unique=True,blank=False,null=False) date = models.DateTimeField(auto_now_add=True) main_pic = models.ImageField(upload_to='images/',null=False) brief = models.TextField(max_length=255,null=False) article = models.TextField(null=False) def __str__(self): return (self.title," ---- ",self.date.year ,self.date.month … -
SQLite3 Database Locked When Deploying Django Project on Azure App Services
I'm attempting to deploy a Django project to Azure App Services (Linux), following this tutorial: https://stories.mlh.io/deploying-a-basic-django-app-using-azure-app-services-71ec3b21db08. The deployment works, but every time I try to write or read from the database, I get a 500 error something along the lines of: OperationalError at /api/articles/↵no such table: articles_article↵↵Request Method: GET↵Request URL: http://liquidplanet.azurewebsites.net/api/articles/... The sqlite3.db file in /wwwroot shows a size of 0. When I try to manually apply migrations through SSH, I get the following message in terminal: django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (database is locked) I'm skeptical that this is a concurrency issue, as suggested in Django docs, as this happens even on the most basic Django projects. Worth noting: when I first access the SSH terminal, I need to install Django and everything else in my requirements.txt (even though it says in logs that everything installs during deployment). Not sure if this is normal. Tried: - Redeploying, - Running simpler Django projects in different configurations, including just the basic webpage you get when you create a new Django project, - Deleting DB file and reapplying migrations, - Increasing the timeout in Django settings.py file Have not tried: - Switching to a different DB What am I doing … -
How To Use BeautifulSoup In Django?
So, I was trying to create a website in Django, which basically scrapes the data from google news and puts it on my website. But I didn't know how to use the data that I extracted from google news in my Django HTML file. Is there a way that I could do that. Also, It slows the website very much, so is this the best way to do it? The web scraping code: from bs4 import BeautifulSoup import requests url = "https://news.google.com/?hl=en-IN&gl=IN&ceid=IN:en" headers = { "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36' } page = requests.get(url, headers=headers) soup = BeautifulSoup(page.content, 'html.parser') n = 1 for link in soup.findAll('h3', {'class', 'ipQwMb ekueJc RD0gLb'}): title = link.string for a in link.findAll('a', {'class', 'DY5T1d'}): href = a.get('href') link_href = href.replace(".", "") print("(" + str(n) + ")" + title + "\n" + "https://news.google.com" + link_href) n += 1 -
How can I reach a subclass in HTML using django?
https://docs.djangoproject.com/en/2.2/intro/tutorial02/ link tells me that: Each Choice is associated with a Question. But how can I reach in HTML these each Choices values? I have Gallery model associated with Post model, but when I save each images from gallery model. Post model only shows the last image. It is saved in the media. I checked all are saved there and my settings file are ok. class Post(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE, default = 1 ) title = models.CharField(max_length= 100, null=True, blank=True, default="Başlık") content = models.TextField() image = models.ImageField(upload_to=user_directory_path, blank =True, null=True, default = "/") date_posted = models.DateTimeField(default=timezone.now) document = models.FileField(upload_to='{{ {nop} }}'.format(nop = "something"), default = "media/") thumbnail = models.FileField(upload_to='posts/', null = True, blank= True, default = "") status = models.CharField(max_length=10, choices=STATUS_CHOICES, default="draft") # category = models.ManyToManyField(Category, default = 0) # thumbnail = models.FileField(upload_to='posts/' gallery and thumbnail is different folders objects = models.Manager def __str__(self): return self.title def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.pk}) class Gallery(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_directory_path, blank =True, null=True, default = "/") author = models.ForeignKey(User, on_delete = models.CASCADE, default = 1) objects = models.Manager Views.py class PostCreateView(FormView, LoginRequiredMixin, CreateView): form_class = PostForm model = Post # category = Category.objects.all() def post(self, request, … -
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 …