Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Integrity error at .... null value in column
New to Django, getting a violates not-null constraint, thats preventing it posting to my DB(elephantSQL), I cant seem to get around this issue even when passing the post.id in urls, in the 'buttons' and the view.... Im not sure what I'm doing wrong hopefully someone can point me in the right direction? I have very little experience with this and im trying to learn I have tried a good few things, tho I cant seem to get it to post. HELP!!!! Views def createReview(request): form = ReviewForm() if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): form.save() return redirect('market_posts/') context = {'form': form} return render(request, 'market/review_form.html', context) Models from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator from cloudinary.models import CloudinaryField STATUS = ((0, "Draft"), (1, "Published")) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="market_posts") updated_on = models.DateTimeField(auto_now=True) content = models.TextField() featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) likes = models.ManyToManyField(User, related_name='likes', blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() class Comment(models.Model): comment = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() … -
using mongodb with motor driver and django
i'm creating an App, using async driver(motor) for mongodb. I have a telegram bot app and django framework app. I want my telegram and web apps use same database. When i try to create User via integrated CreateView class, by default django uses it's standart auth processing and adds user to its default databases(sqlite, postgre etc.) But i'd like to use mongodb and use it asyncronous(as i understood djongo is syncronous driver) the ways I see to solve this: 1) separate users' auth data(to standart database) and other data, that'll be fetched and overwritten frequently(to mongo). 2) use standart view(e.g. TemplateView, FormView) and my own form, write MyOwnUserClass with hashing and all necessary methods. Shortly I want to use instruments of Django with mongodb, how can I reach that? Well don't know if this is needed here, a piece of my current code: forms.py: class RegisterUserForm(UserCreationForm): username = forms.CharField email = forms.EmailField password = forms.PasswordInput password_confirm = forms.PasswordInput telegram = forms.CharField(required=False) views.py: class Register(CreateView): template_name = 'AIsite/register.html' form_class = RegisterUserForm success_url = reverse_lazy('login-user') -
Django admin page looks primitive
for reference: i am learning django from this page:- https://www.w3schools.com/django/django_admin.php im using virtual environment and running this on a local machine: http://127.0.0.1:8000/admin/ Expected output Reality please help. i have tried asking in subreddit and discord but im not yet able to find a fix. any help is appreciated -
WARNINGS: ?: (staticfiles.W004) The directory '/var/www/static/' in the STATICFILES_DIRS setting does not exist
Estoy aprendiendo django y me aparece el error WARNINGS: ?: (staticfiles.W004) The directory '/var/www/static/' in the STATICFILES_DIRS setting does not exist. y no me deja realizar cambios en mis archivos estaticos y no se como solucionarlo intente probando con import os y cambiando STATICFILES_DIRS por STATICFILES_DIRS = \[os.path.join(BASE_DIR, "static")\] pero aun nada -
How to limit client IP of a Django app? (Through django and/or PaaS)
I am making a Django app and I wish to enhance the security as well as limit users by making sure only clients only from one IP (say a shared VPN) can access it. I plan to host the app on a PaaS like Digital Ocean App Platform or Heroku. How can I limit the client IP through: Django, to prevent other users from accessing the app, and The PaaS, so that potential attackers don't have access to the platform in the first place? (Hopefully some PaaS has this optiont) -
Model registration in django in admin.py multi model (choicefield selection)
here is my admin.py class ResumeAdmin(admin.ModelAdmin): def get_fields(self, request, obj=None): fields = ['category'] if obj: if obj.category == 'Summary': fields.extend(['summary_title', 'summary_description', 'summary_address', 'summary_phone', 'summary_email']) elif obj.category == 'Education': fields.extend(['edu_title', 'edu_course', 'edu_start_date', 'edu_end_date', 'edu_gpa']) elif obj.category == 'Experience': fields.extend(['exp_title', 'exp_date', 'exp_where', 'ext_explanation', 'exp_project_link']) elif obj.category == 'Projects': fields.extend(['project_title', 'project_description', 'project_link']) elif obj.category == 'Certifications': fields.extend(['cert_title','cert_date', 'cert_where', 'cert_explanation','cert_project_link']) return fields admin.site.register(Resume, ResumeAdmin) and this is my model.py class Resume(models.Model): CATEGORY = ( ('Summary', 'Summary'), ('Education', 'Education'), ('Experience', 'Experience'), ('Projects', 'Projects'), ('Certifications', 'Certifications'), ) # view different fields according to the category category = models.CharField(max_length=20, choices=CATEGORY, default='Projects') class Summary(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE) summary_title = models.CharField(max_length=100) summary_description = models.TextField() summary_address = models.CharField(max_length=200) summary_phone = models.CharField(max_length=20) summary_email = models.EmailField() # 2 Education option will have title, course, start_date, end_date, GPA class Education(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE) edu_title = models.CharField(max_length=100) edu_course = models.CharField(max_length=100) edu_start_date = models.DateField() edu_end_date = models.DateField() edu_gpa = models.FloatField() # 3 experience filed will have same as education filed class Experience(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE) exp_title = models.CharField(max_length=100) exp_date = models.CharField(max_length=100) # it holds the start and end year of the course exp_where = models.CharField(max_length=200) # college or school name ext_explanation = models.TextField() exp_project_link = models.URLField() # 4 projects filed will have … -
Heroku can't find styles.css
Trying to deploy a Django app to Heroku for the first time. When I view the app using Django, everything shows up correctly, but when I run it on Heroku, pieces of the UI are missing. I'm not too familiar with the frontend - this was a group project and I was working on backend - and my team isn't willing to help with deployment, so I'm unable to diagnose any frontend issues. Looking at the Heroku logs, I get this error "Not Found: /static/styles.css" - but there is a styles.css file under static. Does anyone know where the root problem might lie? Under settings.py I have specified this STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')] All functionalities work as expected, I think it has something to do with the base.html file - but this is just a stab in the dark. An example of what it's meant to look like, compared to what it looks like on Heroku. -
Django path not matching with urlpatterns in urls.py
Guys I am not a web developer, I have been learning django for a couple of hours now for my father's small business website and I am hitting a silly error for hours now. the name of the project is mysite and mysite urls.py looks like this from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("index.urls")), path("about/", include("about_page.urls")), path("polls/", include("polls.urls")), path("admin/", admin.site.urls), ] mysite's settings.py also includes the correct AppConfig for the app. about_page included. INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'index.apps.IndexConfig', 'about_page.apps.AboutPageConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] about_page's views.py is attached_below from django.shortcuts import render from django.http import HttpResponse from django.template import loader from django.http import Http404 # Create your views here. # return HttpResponse("website under construction !!!") def about_func(request): template = loader.get_template("about/about_page.html") context = { "about":"about_us", } return HttpResponse(template.render(context, request)) about_page's urls.py: from django.urls import path from . import views urlpatterns = [ path("about/", views.about_func, name="about_page"), ] polls and index apps have exact same pattern, i simply don't know why i cannot display about page. -
deploy project on my local machine with Apache
I built a website with Django, installed Apache and made all the adjustments. In addition, I bought a domain from GoDaddy for the site. I want to deploy the site on my computer. The problem is when I try to access the site via the internet I get to a page from GoDaddy with my domain. The steps I did: Add A record with my local IP DNS on GoDaddy Installing wsgi Updating the settings.py page with the new addresses. Update httpd-vhosts Update httpd.conf Resetting the Apache server open the ports in my firewall *I bought the domain two days ago. httpd.conf: ServerName DomainName LoadFile path LoadModule wsgi_module path WSGIPythonHome path httpd-vhosts: ServerName DomainName <VirtualHost *:80> ServerName DomainName ServerAlias www.DomainName WSGIScriptAlias / "path" ErrorLog "logs/DomainName-error.log" CustomLog "logs/DomainName-access.log" common <Directory "path"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "path" <Directory "path"> Require all granted </Directory> -
Please i want to generate username from user email in django that can be used in the url
I'm encountering an issue with populating the display_username field in my custom Django user model. Which i want to use as the username handle. My Model: class User(AbstractUser): # First and last name do not cover name patterns around the globe name = CharField(_("Name of User"), blank=True, max_length=255) first_name = None # type: ignore last_name = None # type: ignore display_username = CharField(_("Display Username"), blank=True, max_length=255) email = EmailField(_("email address"), unique=True) username = None # type: ignore USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self) -> str: """Get URL for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"pk": self.id}) My Manager: class UserManager(DjangoUserManager): """Custom manager for the User model.""" # def _create_user(self, email: str, password: str | None, **extra_fields): # """ # Create and save a user with the given email and password. # """ # if not email: # raise ValueError("The given email must be set") # email = self.normalize_email(email) # user = self.model(email=email, **extra_fields) # user.password = make_password(password) # user.save(using=self._db) # return user # def _create_user(self, email, password=None, **extra_fields): # if not email: # raise ValueError("The given email must be set") # email = self.normalize_email(email) # base_username = email.split('@')[0] # … -
What would be a better solution for storing data in a Django model?
Could you please give me a piece of advice? Context: I have a Django project in which each user stores many different variables linked to his profile. I created a model called Snapshot, that has a foreign key of user. Single user can have multiple Snapshots linked to his User instance, but only the latest one (by its ID, pk) is editable. Any other ones might be used to revert to past setup only. Typical use case: User modifies his setup stored in his latest Snapshot using API endpoints. Each function that an endpoint call has to query the latest Snapshot owned by user that called the function. Then it modifies some of the variables in the Snapshot and saves it. Once everything's done user approves the setup and the Snapshot is being duplicated. Now the new instance becomes the latest. Question: Is it a good idea to query the latest Snapshot this many times in each function? Wouldn't it be a good idea to link the latest Snapshot one-to-one with User, so that it's always available as User.latest_snapshot? This latest_snapshot would be automatically re-linked to User once user approves setup, thus creating a new Snapshot. -
Django tenants can't delete record from a shared model that has FK in tenant from public schema
I Have a custom user model shared between tenants and public HAS_MULTI_TYPE_TENANTS = True MULTI_TYPE_DATABASE_FIELD = 'type' TENANT_TYPES = { "public": { "APPS": [ 'django_tenants', 'clients', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'djoser', "corsheaders", 'accounts', ], "URLCONF": "server.urls_public", }, "menu": { "APPS": [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework.authtoken', 'accounts', 'products', ], "URLCONF": "server.urls_menu", }, "full-version": { "APPS": [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework.authtoken', 'accounts', 'products', 'order', ], "URLCONF": "server.urls_full", } } INSTALLED_APPS = [] for schema in TENANT_TYPES: INSTALLED_APPS += [app for app in TENANT_TYPES[schema] ["APPS"] if app not in INSTALLED_APPS] from the full-version order app, there is an FK to the user model that restrict me to delete any user from the public schema class Address(models.Model): user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) also, the issue appears in the menu type cuz the order models do not exist yet django.db.utils.ProgrammingError: relation "order_address" does not exist LINE 1: ...."user_type", "accounts_user"."phone_number" FROM "order_add... Is any work around or do I have to create an empty model for each type? -
How to clone github repository to azure blob
I'm trying to clone a github repository in my django application and write it to my server machine. And I have to serve that repository files to end users. I did it using below code "my implementation code"but "shutil.rmtree(repo_dir)" is taking very long time to remove existing repository files from my server machines. "Here is my implementation code" Please help and guide if there is any better way to do this. Thanks in Advance -
ploty theme change issue
I am using ploty py and django have two themes in my webapp dark and light. on light theme select graph is shown light theme and on dark theme select graphs are shown dark theme. the issue i am getting when one user change the theme it affect the other user graph theme when other user refresh or callback change. dark theme template import plotly.io as pio from plotly.graph_objs import Layout import plotly.graph_objects as go dark_template_layout = Layout( images=[ dict( source="/static/img/images/watermark/Anahit-SVG-LOGO-GreyScale-4.svg", name="Anahit", xref="paper", yref="paper", x=0.5, y=0.5, sizex=0.5, sizey=0.4, xanchor="center", yanchor="middle", layer="below", opacity=0.1, ) ], annotationdefaults={ "arrowcolor": "#f2f5fa", "arrowhead": 0, "arrowwidth": 1, }, autotypenumbers="strict", coloraxis={"colorbar": {"outlinewidth": 0, "ticks": ""}}, colorway=[ "#636efa", "#EF553B", "#00cc96", "#ab63fa", "#FFA15A", "#19d3f3", "#FF6692", "#B6E880", "#FF97FF", "#FECB52", ], font={ "family": "Mulish, sans-serif", "size": 16, "color": "#a9afc3", }, ### title ### title={ "font": { "family": "Poppins, sans-serif", "size": 15, "color": "white", }, ### control position of title # "y": 0.5, "x": 0.5, # "xanchor": "right", # "yanchor": "middle", }, hoverlabel={"align": "left"}, # Keep adding others as needed below hovermode="closest", mapbox={"style": "dark"}, **paper_bgcolor="#080a12",** **plot_bgcolor="#080a12",** shapedefaults={"line": {"color": "#a9afc3"}}, sliderdefaults={ "bgcolor": "#C8D4E3", "bordercolor": "rgb(17,17,17)", "borderwidth": 1, "tickwidth": 0, }, updatemenudefaults={"bgcolor": "#506784", "borderwidth": 0}, xaxis=dict( automargin=True, gridcolor="#283442", linecolor="#506784", title={"standoff": 15}, zerolinecolor="#283442", zerolinewidth=2, rangeselector={"activecolor": … -
Django: Make variable of child model depend on number of siblings associated with the same parent model
Assume I have two models, one modelling a Patient and another one modelling a tissue sample. To avoid confusing among lab members, instead of refering to the samples and the patients by a PK we transform the PK into a hashed string named displyed_id below. In the ideal case we would have a patient referred to as 'H6F4A' and the samples to be 'H6F4A-1', 'H6F4A-2', etc. (be labelled by a suffix of the sample number belonging to that patient). As a requirement we would need that if a sample is deleted that the sample numbering doesn't change for the suceeding samples (as the samples have physical barcodes printed onto them). As this is kind of hard to do (probably one would need a counter for every patient counting how many samples there are) we have opted to use the tissuesample pk as the suffix which is not really what we want as this is global and not per patient. Even if this new counter would not be a pk, combined with the hashed id of its parent e.g. sample 1 of patient 1 being 'H6F4A-1' it would need to be an injective mapping as staff will always refer to this … -
How to make on update record pass the signal in Django Model?
Hello I'm trying to make on update trigger in Django Model. Model.py class Item(models.Model): status_type = ( ('a','Active'), ('d','Deactive') ) code = models.CharField(max_length=100, null=True, blank=True, unique=True) name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) gsts = models.ForeignKey(Gst, on_delete=models.CASCADE) sgst = models.DecimalField(max_digits=10, decimal_places=2,null=True,blank=True) cgst = models.DecimalField(max_digits=10, decimal_places=2,null=True,blank=True) net_amount = models.DecimalField(max_digits=10, decimal_places=2,null=True,blank=True) status = models.CharField(max_length=1, choices=status_type, default = 'a') create_at = models.DateField(auto_now_add=True) update_at = models.DateField(auto_now=True) create_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def ItemGenerator(sender, instance, created, *args, **kwargs): if created: id = instance query = Item.objects.get(id = int(id.id)) #gst calculation gst_cal = query.price * query.gsts.gst/100 #net amount calculation net_amounts = query.price + gst_cal #item number generate temp_count = Item.objects.all().count() no = str('ITEM') + '/' +str(temp_count) query = Item.objects.filter(id = id.id).update(code = str(no), cgst = round(gst_cal/2), sgst=round(gst_cal/2), net_amount = round(net_amounts)) When I'm insert to the data post_save signal is call and my price and gst calculation save into data base but problem is that when I'm update the record post_save signal is not working -
product.models.Products.DoesNotExist: Products matching query does not exist
product.models.Products.DoesNotExist: Products matching query does not exist. i have this problem in my site when i ran this url it show me this error please help in django and this is my views.py: class GetListProduct(APIView): def get(self, request): products = Products.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) class Getproduct(APIView): def get_object(self, brand): comment = Products.objects.get(brand=brand) serializer = ProductSerializer(comment) return Response(serializer.data) class Topsellsviews(APIView): def get(self, request): topsellsproduct = TopSells.objects.all() serializer = Topsellsserializer(topsellsproduct, many=True) return Response(serializer.data) class Getdetailproduct(APIView): def get(self, request, productid): detail = Products.objects.get(productid=productid) serializer = ProductSerializer(detail) return Response(serializer.data) and this is my url: from django.urls import path from.views import GetListProduct, Topsellsviews, Getdetailproduct, Getproduct urlpatterns = [ path('product/', GetListProduct.as_view()), path('topsells/', Topsellsviews.as_view()), path('product/<str:productid>/', Getdetailproduct.as_view()), path('product/<str:brand>/', Getproduct.as_view()), when i run /product/productid it worked but when i run /product/brand it not worked -
Using field in Trunc's kind property
I use PostgreSQL in my project and have three related models: class Timer(models.Model): start = models.DateTimeField() end = models.DateTimeField() task = models.ForeignKey( Task, models.CASCADE, related_name="timers", ) class Task(models.Model): name = models.CharField(max_length=64) wanted_duration = models.DurationField() frequency = models.ForeignKey( Frequency, models.CASCADE, related_name="tasks", ) class Frequency(models.Model): class TimeUnitChoices(models.TextChoices): DAY = "day", "day" WEEK = "week", "week" MONTH = "month", "month" QUARTER = "quarter", "quarter" YEAR = "year", "year" events_number = models.PositiveIntegerField() time_unit = models.CharField(max_length=32, choices=TimeUnitChoices.choices ) I want to get a start of timespan (day, week - a value of Frequency's time_unit) according to start date (field of Timer). I tried execute next code: task.timers.annotate(start_of=Trunc('start', kind='task__frequency__time_unit')) But Django doesn't accept field in kind argument of Trunc class. Error: psycopg.ProgrammingError: cannot adapt type 'F' using placeholder '%t' (format: TEXT) If I execute a following query in raw SQL: SELECT DATE_TRUNC(schedules_frequency.time_unit, timers_timer.start)::date as start_of FROM public.tasks_task INNER JOIN public.schedules_frequency ON tasks_task.frequency_id = schedules_frequency.id INNER JOIN public.timers_timer ON timers_timer.task_id = tasks_task.id; Everything works as wanted. Is there workaround without using raw SQL directly in the Django project? -
I/O Operation on closed file while using boto3 library for S3 file upload
Here is the traceback Internal Server Error: /api/v1/vehicle/ss-image-upload/ Traceback (most recent call last): File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\vehicle_management\views.py", line 462, in patch i.save() File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\base.py", line 814, in save self.save_base( File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\base.py", line 877, in save_base updated = self._save_table( ^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\base.py", line 981, in _save_table values = [ ^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\base.py", line 985, in <listcomp> (getattr(self, f.attname) if raw else f.pre_save(self, False)), ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\fields\files.py", line 317, in pre_save file.save(file.name, file.file, save=False) File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\fields\files.py", line 93, in save self.name = self.storage.save(name, content, max_length=self.field.max_length) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\core\files\storage\base.py", line 38, in save name = self._save(name, content) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\storages\backends\s3boto3.py", line 446, in _save content.seek(0, os.SEEK_SET) ValueError: I/O … -
Error after removing slug from Page.promote_panels [Django Wagtail]
I am getting the following error after removing the 'slug' field from Page.promote_panels. I am using wagtail 5.1. KeyError at /admin/pages/add/blog/blogdetailpage/10/ "Key 'slug' not found in 'BlogDetailPageForm'. Choices are: category, classes, comment_notifications, container_size, containerized, content, expire_at, go_live_at, publish_at, search_description, seo_title, site, title." I am autogenerating the slug with the following piece of code, so I do not see a need for keeping it around. def save(self, request=None, *args, **kwargs): ... slug = slugify(f"{self.title}-{self.created_at}") if not self.slug or self.slug != slug: self.slug = slug if not self.publish_at: self.publish_at = datetime.now() super().save(*args, **kwargs) Is anyone familiar with doing something along the lines of this? -
Connect a Reddit app to Django and get permission to make a post
As a developer, I'd like to create a Reddit app and use it in Django. I'd like to get authorization to get the posts that the user has authorized. Imagine: A user clicks a button on my website and goes directly to the authorization screen and then he will be able to see his Reddit posts on my website -
How reset the user password in django
I have make canteen invoice making app and also admin can create user, update user and change the user's password But admin can't change user password form.py class PasswordChange_Form(UserCreationForm): class Meta: model = User fields = ["username","password1","password2"] widgets = { "username":forms.TextInput(attrs={'class':'form-control','placeholder':'Username', 'readonly':'readonly'}), "password1":forms.TextInput(attrs={'class':'form-control',"placeholder":"Password"}), "password2":forms.TextInput(attrs={'class':'form-control','placeholder':'Confirm Password'}), } View.py @login_required(login_url='/') def UserChangePassword(request,pk): id = User.objects.get(id = pk) user_id =request.user heading_name = "user" rights, main_heading, page_menu, form_btn_data = RightLoader(user_id, heading_name) try: auth_check = rights.form_btn.get(heading_name = heading_name, btn_type = "Password")# fetch form btn right if request.method == 'POST': form = PasswordChange_Form(request.POST, instance=id) try: if form.is_valid(): form.save() form = PasswordChange_Form(instance=id) #update_session_auth_hash(request, ) # Important! messages.success(request, 'Your password was successfully updated!') except: messages.error(request,str(form.errors)) else: form = PasswordChange_Form(instance=id) context = { 'form':form, 'page_menu':page_menu, 'main_heading':main_heading, 'btn_type':'fa fa-regular fa-plus', 'title':'iCateen | User', 'page_title':'Password Change', 'tree_title_1':'User', 'tree_url':'user', 'tree_title_2':'Add Form', 'view':'yes', } return render(request, 'base/user/change_password.html',context) except: return HttpResponseRedirect("/") Admin user can change user's password ? -
PyCharm does not accept my Python interpreter
I'm working with Python framework Django. I used Pycharm's terminal created virtual environment. {.\venv\Scripts\activate} It was created, and i run the server with this python manage.py runserver But the system responds: No Python at "C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe But i installed and using Python 3.11.2 And i have file manage.py in project1 folder What should i do? The code PS D:\binkw32.dll\djangomorning> .\venv1\Scripts\activate (venv1) PS D:\binkw32.dll\djangomorning> cd project1 (venv1) PS D:\binkw32.dll\djangomorning\project1> python manage.py runserver No Python at 'C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe' (venv1) PS D:\binkw32.dll\djangomorning\project1> -
Web and Daphne always restarting and not working properly
I've checked all I've seen, yet nothing is working. Please, I'm trying to make use of docker and all for the first time. This is my docker-compose.yml services: cache: image: redis:7.0.4 restart: always volumes: - ./data/cache:/data db: image: postgres:15.0 restart: always volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=samuel - POSTGRES_USER=samuel - POSTGRES_PASSWORD=*** web: build: . command: ["./wait-for-it.sh", "db:5432", "--", "uwsgi", "--ini", "/code/config/uwsgi/uwsgi.ini"] restart: always volumes: - .:/code environment: - DJANGO_SETTINGS_MODULE=chollosite.settings.prod - POSTGRES_DB=samuel - POSTGRES_USER=samuel - POSTGRES_PASSWORD=samuel101 depends_on: - db - cache daphne: build: . working_dir: /code/chollosite/ command: ["../wait-for-it.sh", "db:5432", "--", "daphne", "-u", "/code/chollosite/daphne.sock", "chollosite.asgi:application"] restart: always volumes: - .:/code environment: - DJANGO_SETTINGS_MODULE=chollosite.settings.prod - POSTGRES_DB=samuel - POSTGRES_USER=samuel - POSTGRES_PASSWORD=samuel101 depends_on: - db - cache nginx: image: nginx:1.23.1 restart: always volumes: - ./config/nginx:/etc/nginx/templates - .:/code ports: - "80:80" - "443:443" this is my base.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'pex0v$*b!kjl-bk2p%1y8rf!&jh+bqa!9t5e4@xnac-(nbi2wc' # Application definition INSTALLED_APPS = [ 'chollo_main.apps.CholloMainConfig', 'chollo_cart.apps.CholloCartConfig', 'orders.apps.OrderConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.postgres', 'channels', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', … -
Possible security risks for the following form submission in Django
I am trying to create the page for a livetime chat app using Django and some Ajax. I have always used django forms, since it is more secure and clean if you are not very familiar with javascript. The below html and views.py don't use django forms, but instead go with the traditional method of using javascript. However, I am concerned that there might be security leaks with this following form, which I copied from another website. I believe I added the csrf token correctly, but is there anything else I need to consider? Thank you, and please leave any comments. <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script> </head> <body> <h2>{{room}} - DjChat</h2> <div id="display"> </div> <script> $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url : "/getMessages/{{room}}/", success: function(response){ console.log(response); $("#display").empty(); for (var key in response.messages) { var temp="<div class='container darker'><b>"+response.messages[key].user+"</b><p>"+response.messages[key].value+"</p><span class='time-left'>"+response.messages[key].date+"</span></div>"; $("#display").append(temp); } }, error: function(response){ alert('An error occured') } }); },1000); }) </script> <div class="container"> <form id="post-form"> {% csrf_token %} <input type="hidden" name="username" id="username" value="{{username}}"/> <input type="hidden" name="room_id" id="room_id" value="{{room_details.id}}"/> <input type="text" name="message" id="message" width="100px" /> <input type="submit" value="Send"> </form> </div> </body> <script type="text/javascript"> $(document).on('submit','#post-form',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/send', data:{ username:$('#username').val(), room_id:$('#room_id').val(), message:$('#message').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, …