Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Copy edx-platform in local system
I applyed bellow cammand but it's not working. docker cp -L edx.devstack.lms:/edx/app/edxapp/edx-platform/ /vscode-platform It gives this error in powershell. symlink ....\common\static\common c:\users\gautamrathore\desktop\vscode-platform\edx-platform\cms\static\common: a required privilege is not held by the client. I want to copy edx-platform in local system. -
Exception in thread django-main-thread Traceback
I am getting this error while trying to run a Django project. This happened when I cloned the project and run it for this first time, I am running it using a virtual environment (env1) C:\Users\Chiam\Desktop\fyp\odyera>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Chiam\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\Chiam\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\Chiam\Desktop\fyp\odyera\env1\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Chiam\Desktop\fyp\odyera\env1\Lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Users\Chiam\Desktop\fyp\odyera\env1\Lib\site-packages\django\core\management\base.py", line 475, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "C:\Users\Chiam\Desktop\fyp\odyera\env1\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Chiam\Desktop\fyp\odyera\env1\Lib\site-packages\django\core\checks\urls.py", line 42, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Chiam\Desktop\fyp\odyera\env1\Lib\site-packages\django\core\checks\urls.py", line 61, in _load_all_namespaces url_patterns = getattr(resolver, "url_patterns", []) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Chiam\Desktop\fyp\odyera\env1\Lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Chiam\Desktop\fyp\odyera\env1\Lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Chiam\Desktop\fyp\odyera\env1\Lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Chiam\Desktop\fyp\odyera\env1\Lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Chiam\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Chiam\Desktop\fyp\odyera\client\views.py", line 3, in <module> import pyrebase ModuleNotFoundError: No module named 'pyrebase' Searched a … -
Calculate Business Days in Django Annotate
I wanted to calculate business days in Django annotate. For example, if an event was generated 7 days back, and I wanted to know how many business days had passed. As per the example, 7 days includes [Monday - Sunday], and I only wanted to include [Monday - Friday], which means 5 business days. I've done this logic via some pythonic hack, but I wanted to do this in Django annotate() method. So I can filter the results based on business days. Here is an example of what I've done so far: table_values = Table.objects.all().annotate(issue_severity=datetime.utcnow() - Max("event__created")) for table in table_values: date = datetime.now(timezone.utc) - table.issue_severity dates = (date + timedelta(x + 1) for x in range(table.issue_severity.days)) table.business_days = sum(day.weekday() < 5 for day in dates) -
Where should validation logic go in this DJANGO project
I have an existing python program which verifies coordinates are correct - by that I mean they are in the correct place, not a simple range check. In my Django project I want someone to be able to send these coordinates in, and use my existing code to verify they are correct before saving them to the model. My question is, where does this logic go? Do I put it in the view and reject the HTTP request, if the coordinates are invalid? - this seems simplest to me? Or does this go in the model somewhere, and I prevent invalid coordinates from being saved to the database? I'm new to Django, so not sure what is a good practice / idea. An issue I see with writing a custom validator(?) is these coordinates come in pairs. -
Django pass url context via function
I have a urlpattern in the urls.py file defined as path('profile/<str:uname>/', views.UserProfile, name='UserProfile'), I need to do the following at the return of my function in my views.py file, return render(request, 'UserProfile') How do I pass the 'uname' parameter in this return correctly? P.S. I don't know if this is even possible. -
Prevent people from seeing other user profile pictures
I created a field to allow a user to upload a profile picture. In the template I check if the user is logged in and there is a profile image, otherwise I display a generic one. How can you prevent someone from guessing other filenames to see another users profile picture? {% if user.is_authenticated and user.profile.image %} <span class="avatar avatar-sm" style="background-image: url({{ user.profile.image.url }})"></span> {% else %} <span class="avatar avatar-sm" style="background-image: url('/media/profile_pics/default.png)')"></span> {% endif %} -
Django - Programatically access property of model class (getattr throws Attribute Error)
I am overriding a Model's save method so I can log changes made to certain fields: class Model(models.Model): name = ... price = ... ... __original_name = None __original_price = None def save(self, force_insert=False, force_update=False, *args, **kwargs): for field in [ 'name', 'price', ]: print(self.__original_name) # works original_value = getattr(self, f"__original_{field}") # throws Attribute Error # other logic ... self.__original_name = self.name self.__original_price = self.price super(Model, self).save(force_insert, force_update, *args, **kwargs) Error thrown: AttributeError: 'Model' object has no attribute '__original_name' The method works correctly if I don't loop over the fields and access each field independently with self.__original_field, but I am trying to refactor the code so I can easily start tracking other fields as needed. Is there a different built in method I can use to access the value programatically? (cant use self[f"__original_{field}"] cause it is not subscriptable) -
These are the errors it gives me when I run my project
ModuleNotFoundError: No module named 'portfolio_project.wsgi' raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: WSGI application 'portfolio_project.wsgi.application' could not be loaded; Error importing module This is what I have in my settings: WSGI_APPLICATION = 'portfolio_project.wsgi.application' I'm not sure what to do I tried installing whitenoise and django-cors-headers but that didn't work. -
What is the best way to develop an Elastic Beanstalk Django application locally?
I have recently deployed my Django application on Elastic Beanstalk. I have everything working now, but I'm curious what the best way to develop locally is. Currently, after I make a change locally, I have to commit the changes via git and then run eb deploy. This process takes 1-3 minutes which is not ideal for making changes. The Django application will not run on my local machine, as it is configured for EB. -
Prevent Django health check endpoint logs from being sent to Sentry
I have a Django application with a health check endpoint that's using this repo. In the url_patterns I have added the following line: url(r'^ht/', include('health_check.urls')), The issue is that the health check is filling all the Sentry transaction limits. How can I exclude the health check endpoint in Sentry? -
How to save stripe webhook data to session variables in Django?
I am currently working on a 'success' page for my Django project (which uses Stripe to take payments). I would like to show their order total, with tax, on this page. My Stripe webhook is running and posting data, but for the life of me I can't use this data outside of the webhook's veiw. Normally, when I want to inform one view with data from another, I take advantage of Django's session variables. When I save the session variable, however, attempting to use it in my SuccessView returns 'None' rather than the value saved to it. Any help would be appreciated. Here is my relavent code: views.py def stripe_webhook(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_WEBHOOK_SECRET ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) # Handle the checkout.session.completed event if event['type'] == 'checkout.session.completed': session = event['data']['object'] customer_email = session["customer_details"]["email"] line_items = stripe.checkout.Session.list_line_items(session["id"]) print(line_items) stripe_price_id = line_items["data"][0]["price"]["id"] price = Price.objects.get(stripe_price_id=stripe_price_id) total_paid_cents = line_items["data"][0]["amount_total"] total_paid_dollars = total_paid_cents / 100 request.session['total_paid'] = total_paid_dollars return HttpResponse(status=200) class SuccessView(TemplateView): template_name = "musicstudios/success.html" extra_context = sidebar_context def get_context_data(self, **kwargs): context = super(SuccessView, self).get_context_data(**kwargs) order_id = … -
Error running migration after changing to spatialite db
I want to use geographical point in my django app therefor i changed the database engine to spatialite settings.py """ Django settings for server project. Generated by 'django-admin startproject' using Django 4.1.2. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-+r-63iiele&p+irgsm2ojoayyrk2^6($no8%x+^(32s3wvpk7b' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'django.contrib.gis', 'hiketracking.apps.HiketrackingConfig', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'server.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'server.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { "ENGINE": "django.contrib.gis.db.backends.spatialite", 'NAME': BASE_DIR / 'db.sqlite3', }, } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, … -
time data '2020–04–29 00:00:00' does not match format '%Y-%m-%d %H:%M:%S'
I am getting this error time data '2020–04–29 00:00:00' does not match format '%Y-%m-%d %H:%M:%S' input for start date is '2020–04–29' I am trying to srap tweets using twint and I am geting this error ` config = twint.Config() config.Pandas = True payload = json.dumps(request.GET) payload = json.loads(payload) config.Search = payload.get('keyword') config.Lang = payload.get('language','en') config.Limit = int(payload.get('limit',100)) startDate = payload.get("startDate",None) if startDate: config.Since = startDate endDate = payload.get("endDate",None) print(startDate,endDate) if endDate: config.Until = endDate twint.run.Search(config) ` -
django-filter how to add attribute to html tag under form
I'm using Django-filter,I tried to add attributes by using widget and attrs: filter.py: class MyFilter(django_filters.FilterSet): messageText = django_filters.CharFilter(widget=(attrs={'style':'width: 20px', 'class':'form-select form-select-sm'})) class Meta: model = Mymodel fields = ['messageText '] Then I got: SyntaxError: invalid syntax at here 'attrs={' Any friend can help ? -
Self-hosting multiple sites via one Django project + apache - Django Sites framework
I have a self-hosted (raspberry pi) website running on Django - one project with several apps all serving on one domain name. I'm more of a programmer than a server admin, but it works! Now, I'd like to break one of those apps out onto a second domain name, but still hosting from my pi. --I've looked into a lot of tutorials on how to do this as well as checked out answers like this one but the server-related instructions on everything I've found so far all go a bit over my head or don't seem to match up with my setup. --I've tried the Django Sites framework and I've also followed this tutorial. While I was able to get my site objects in the db, all requests seem just to go to SITE_ID=1, regardless of domain name. I've seen conflicting information here about whether or not SITE_ID should be present in settings.py, but whenever I remove it, I just get errors about it (even though I do have the CurrentSiteMiddleware installed as well as a custom middleware like indicated in that tutorial). Here's what I've got for Django (3.2.14, and py3.7.3), essentially: DjangoApps -mysite --settings.py (allowed_hosts includes mydomain) --urls.py … -
"Create a web library application.”
"Create a web library application. A library has books and for each book store id, the name and description, and the image. Each book has one author and many categories. For author store name and bio, for category store only name. Create an admin panel to add books, authors, and categories. The admin panel should require a login.bbjjnj -
SecretManagerServiceClient raises 403 Permission denied CONSUMER_INVALID in Google App Engine but `gcloud secrets versions access` works
Background: I'm trying to deploy a Django app to the Google App Engine (GAE) standard environment in the python39 runtime The database configuration is stored in a Secret Manager secret version, similar to Google's GAE Django tutorial (link) The app is run as a user-managed service account server@myproject.iam.gserviceaccount.com, which has the appropriate permissions to access the secret, as can be confirmed using gcloud secret versions access Problem: In the Django settings.py module, when I try to access the secret using google.cloud.secretmanager.SecretManagerServiceClient.access_secret_version(...), I get the following CONSUMER_INVALID error: google.api_core.exceptions.PermissionDenied: 403 Permission denied on resource project myproject. [links { description: "Google developer console API key" url: "https://console.developers.google.com/project/myproject/apiui/credential" } , reason: "CONSUMER_INVALID" domain: "googleapis.com" metadata { key: "service" value: "secretmanager.googleapis.com" } metadata { key: "consumer" value: "projects/myproject" } My Debugging I cannot reproduce the error above outside of GAE; I can confirm that the SA can access the secret: gcloud secrets versions access latest --secret=server_env --project myproject \ --impersonate-service-account=server@myproject.iam.gserviceaccount.com WARNING: This command is using service account impersonation. All API calls will be executed as [server@myproject.iam.gserviceaccount.com]. DATABASE_URL='postgres://django:...' SECRET_KEY='...' I've also confirmed I run the django app locally with service account impersonation and make the above access_secret_version(...) calls In desperation I even created an API … -
jango.db.utils.ProgrammingError: relation <relation_name> already exists
I am starting a project that is based on some already existing relational data. One problem is the data is not in the exact form I would want it. For example boolean fields are integers etc. What I though would be a good idea to start my project is the following: Download the data in the form they're provided (.csv). Create a database from the csv data, using pandas' dataframe.to_sql method. Create the django app and load the models from the database into models.py using manage.py inspectdb. Change all fields to whatever I want and remove the managed = False in each class Meta subclass of my models class. That's it. Now my project would turn to a normal project like all others. It would keep the data from the tables, but it would allow me to alter the schema however I want (*). The fact that I used dataframe.to_sql method made the data's form even more problematic, for example there are not foreign keys but just varchars or integers. So I had to turn this fields to ForeignKeys manually. The issue I am facing is that whenever I try to apply the migrations I get this error: django.db.utils.ProgrammingError: relation … -
How to handle multiple of multiple [[ids], [ids], [ids]] in django?
We have a use case where the django backend api endpoint has to take a [[ids], [ids], [ids]] as the GET endpoint input, any idea how to handle this in Django rest framework? -
How to add multiply photos to one website page with django?
I'm writing django project for Internet Shop. On the page which describes product I have several photos for this product and I cannot add it to the template. I use 2 models with Many to many relationship - for product and for photos, and added they to template.html. But I don't see any photo in the page. My code is below: models.py: class ProductPhoto(models.Model): def get_file_name(self, filename: str) -> str: ext_file = filename.strip().split('.')[-1] new_filename = f'{uuid.uuid4()}.{ext_file}' return os.path.join('product_photo/', new_filename) # product = models.ForeignKey(Product, on_delete=models.CASCADE) photo = models.ImageField(upload_to=get_file_name) description = models.CharField(max_length=20, blank=True) def __str__(self): return f'{self.description}' class Product(models.Model): slug = models.SlugField(max_length=200, db_index=True) title = models.CharField(unique=True, max_length=100, db_index=True) description_short = models.CharField(max_length=200) description = models.CharField(max_length=500) color = models.CharField(max_length=20) price = models.DecimalField(max_digits=8, decimal_places=2) sale = models.SmallIntegerField(max_length=2, blank=True) new_arrival = models.BooleanField(default=True) is_visible = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) photo = models.ManyToManyField(ProductPhoto) def __str__(self): return f'{self.title}' class Meta: index_together = (('id', 'slug'), ) def get_absolute_url(self): return reverse("shop:products", args=[self.id, self.slug]) views.py: def product_details(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, is_visible=True) cart = Cart(request) return render(request, 'single-product.html', {'product': product, 'cart': cart, }) template.html: <div class="product-details-left"> <div class="product-details-images"> {% for item in product.photo.all %} <div class="lg-image"> <img src="{{ item }}" alt=""> <a href="{{ item }}" class="popup-img venobox" data-gall="myGallery"><i … -
Forward slash "/" vs. os.path.join() for MEDIA_ROOT
I have a form (model form) that sends data(such as images, title, etc.) with POST request. In setting.py file, for MEDIA_ROOT, I tried 2 approach: 1- Forward slash "/" : MEDIA_ROOT = [ BASE_DIR / 'static/images' ] 2- os.path.join(): MEDIA_ROOT =os.path.join(BASE_DIR, 'static/images') When I use the first one(forward slash), I get the below error: TypeError at admin/projects/project/... _getfullpathname: path should be string, bytes or os.PathLike, not list Do you know why I can't use the forward slash "/" for MEDIA_ROOT while this way it completely works for STATIC_ROOT? -
Filter view based on the users Group
I am trying to filter the query further to only show records where the Groups matches the logged in users group. I am new to Python and not sure how to add an additional filter into the below view. View @login_required(login_url='login') def home(request): q= request.GET.get('q') if request.GET.get('q') != None else '' infs= Infringement.objects.filter(Q(name__icontains=q) | Q(infringer__name__icontains=q) ) Model class Infringement (models.Model): name = models.CharField(max_length=200) link = models.CharField(null=True, blank=True, max_length=200) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) infringer = models.ForeignKey(Infringer, on_delete=models.SET_NULL,null=True) player = models.ForeignKey(Player, on_delete=models.SET_NULL,null=True) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL,null=True) status = models.ForeignKey(Status, on_delete=models.SET_NULL,null=True) groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1) class Meta: ordering = ['-updated', '-created']` I tried adding the below but it doesn't work. infs= Infringement.objects.filter(Q(name__icontains=q) | Q(infringer__name__icontains=q|) (groups=request.user.groups) ) -
django.core.exceptions.ImproperlyConfigured: PASSWORD_RESET_TIMEOUT_DAYS/PASSWORD_RESET_TIMEOUT are mutually exclusive
I'm upgrading a django code and I faced this error when I runserver, I tryied already to ALLOWED_HOSTS = ["*"] and it doesn't work -
Edit data in the database that was recorded without a form
In my project, there is a form and a table with checkboxes, based on the data entered in the form and the checkboxes, I fill 2 databases and redirect the user to a page where information from one table is displayed, it all worked very well until I got to editing the records, I decided I do it with UpdateView, passing in template_name the same template as before adding records: here is the add function and the edit class: class CampaignEditor(UpdateView): model = Campaigns template_name = 'mailsinfo/add_campaign.html' form_class = CampaignsForm def add_campaign(request): if request.method == 'POST': addCampaignDataToDB(request.POST) data = list(Emails.objects.values()) data = MailsTableWithoutPass(data) form = CampaignsForm() data_ = { 'form': form, 'data': data } return render(request, 'mailsinfo/add_campaign.html', data_) But when calling the url to change my data table is empty and there are no selected checkboxes there, all processing of the form works fine Here is the template I use, and the function that writes the data into the tables: <div> <div class="container-campaign"> <div class="campaign-form"> <form method="post" id="newCampaign"> {% csrf_token %} {{ form.name }}<br> {{ form.subject }}<br> {{ form.body }}<br> {{ form.user_guid }}<br> </form> </div> <div class="campaign-table"> <table id="table" data-height="480" class="table table-dark"> <thead> <tr name="mails-info"> <th data-field="state" data-checkbox="true"></th> <th data-field="id">ID</th> … -
How to properly config a django application on cpanel
Before now, the main domain was serving a WordPress website but I needed to replace that with a new django application. I was able to successfully deploy the Django application to cPanel, and the application was served on a subdomain without any problems. But when I edit the application url to point to the main domain, the homepage renders without the static files. Initially, I thought it was a static file issue until I tried to access other pages, but all I keep getting is a 404 page that is being served by the old WordPress. Somehow the old wordpress website is conflicting with the django app. I'm not sure why the old wordpress is still trying to serve the new django pages except the homepage, even though static files are also missing on the homepage.