Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can AWS SQS be Used in a Django Project with django-celery-results Backend?
Pre-warning: there is A LOT I don't understand My Requirement I need to be able to get the result of a celery task. I need the status to change to 'SUCCESS' when completed successfully. For example: I need to be able to get the result of x + y after executing add.delay(1,2) on the task below. myapp/tasks.py from celery import shared_task from time import sleep @shared_task def add(x, y): sleep(10) return x + y Is AWS SQS the right tool for my needs? I read Celery's Using Amazon SQS and understand at the bottom it says this about the results. Results Multiple products in the Amazon Web Services family could be a good candidate to store or publish results with, but there’s no such result backend included at this point. Question: Does this mean django-celery-results can't be used with AWS SQS? More Context Below What I am doing executionally? I look at my AWS queue (shows messages available as 3) In my local terminal, I do celery -A ebdjango worker --loglevel=INFO (see celery output below) In my PyCharm Python console connected to my Django project, I do r = add.delay(1,2) r is an AsyncResult object: >>> r = add.delay(1,2) >>> … -
Django - How to access POST data in GET method part of a view without saving the data in the database?
I have something like: def my_view(request): if request.method == POST #upload a json file and parse data from it parsed_data = parser.parse() else: #define some forms and variables context = { 'parsed_data' = !what do I put here??! } return render(request, 'file.html', context=context) What shoud I put in the context? If method is GET, parsed_data will not exist, if it is POST, parsed_data will exist but won't go to db. How do I keep its value without storing it in db? -
Remove helper text in Django forms
I have a form in Django for adding an object to an app. On the form I want to remove the helper text from the form. I have done this already in another form, but I can't seem to replicate the removal. Any ideas, my code is below: from django import forms from .models import Node class DateInput(forms.DateInput): input_type = 'date' class NodeCreateForm(forms.ModelForm): class Meta: model = Node fields = ('nickname', 'address', 'date') help_texts = { 'nickname': None, 'address': None, 'date': None } widgets = { 'date': DateInput(), } -
How can I remove "multiple" attribute from django_filters form select field?
Im trying to create a filter form for a table using django-filter. I have the filter working for the fields I want, however for the two ManyToMany fileds in my model, django_filters is creating a select field with the multiple attribute, I do not want that multiple attribute how can I remove it? Here is my model (partial) class Employee(models.Model): ... ... abilities = models.ManyToManyField("capa.CapaType" blank=True) responsibilities = models.ManyToManyField(Responsibilities, blank=True ... ... Class Responsibilities(models.Model): ... title = models.CharField(max_length=30) description = models.CharField(max_length=256) ... capa.CapaType is similar to roles just elsewhere in the project filter.py import django_filters from .models import Employee class EmployeeFilter(django_filters.FilterSet): class Meta: model = Employee fields = ('abilities', 'responsibilities') From what I have read on various other stack overflow questions such as this Django_filters Widget Customize, I should be able to set the widget style in filter.py, but when I tried something similar to the following in the EmployeeFilter class; responsibilities = django_filters.MultipleChoiceFilter(choices=Employee.responsibilities.all(), widget=forms.Select(attrs={'class': 'form-control'})) I get this error in the server console; AttributeError: 'ManyToManyDescriptor' object has no attribute 'all' Removing "all()" gives me this error when I try to load the page 'ManyToManyDescriptor' object is not iterable Any ideas how I can make these fields non multiple? Thanks -
Nginx and Django not acting as expected
I am using Django and have created a custom user model, along with WSGI and Nginx to hand the webserver. All is working well but the user authentication is not working, and the admin login panel does not have any css in it. . -
Auto increment an element value when a URL is hit using API
I am new to DRF, so apologies if it's a trivial question. I want to create an API endpoint to auto-increment the value of a column in the database, whenever a specified URL is hit. For instance--> In the models.py file I have: models.py class User(models.Model): name = models.CharField(null=False, blank=False, max_length=250) error= models.IntegerField(null=False, blank=False) How should I write a view function so that whenever the associated URL hits, the value of error increments by 1? In the URL the ID of the row should also be passed such as: localhost:8000/users/error/2 Upon hitting the above URL the value of the error for user 2 should be increased by one. Thanks, -
How to add Item to cart on ListView Django/
I am making django app, adding items to cart in detail-view work fine but i struggle with implementation the same on ListView. What should I do? views.py class ShopListView(ListView): model = Item template_name = 'shop/home.html' context_object_name = 'items' def post(self, request, *args, **kwargs): pk = self.kwargs.get('pk') item = get_object_or_404(Item, id=pk) orderItem, created = OrderItem.objects.get_or_create(order_item=item) order, created = Order.objects.get_or_create(order_user=request.user) order.save() order.order_items.add(orderItem) return HttpResponse('Items added') Also if i do post(self,request,pk) as in DetailView i get an error one argument is missing 'pk'. class ShopDetailView(DetailView): model = Item template_name = 'shop/detail.html' context_object_name = 'item' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(item=self.object) context['form'] = CommentCreationForm() return context def post(self, request, pk): if 'buy' in request.POST: item = get_object_or_404(Item, id=pk) orderItem, created = OrderItem.objects.get_or_create(order_item=item) order, created = Order.objects.get_or_create(order_user=request.user) order.save() order.order_items.add(orderItem) return HttpResponse('Items added to the database') if 'comment' in request.POST: form = CommentCreationForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.comment_user = request.user comment.item = Item.objects.get(id=pk) comment.save() return HttpResponse('post-created') else: return HttpResponse('post not created') DetailView works fine. -
BeautifulSoup - reading pages that require wait
quick question, I built a webcrawler class that fetches links from the page, I have problem with specific pages that dont load as a whole html, only load more content when you scroll down (if that makes sense). There's especially one specific page that I need for my project that does that Currently I load links with beatifulsoup in this way: #newurl is url passed into a function newurl = newurl.encode('ascii', 'ignore').decode('ascii') resp = urllib.request.urlopen(newurl) soup = BeautifulSoup(resp, self.parser, from_encoding=resp.info().get_param('charset')) links = [] return links But in result, number of fetched links differs every run! Is there an option for BeautifulSoup to 'wait' while opening url, maybe 10 sec, to get all more content loaded into the page and then fetch links? Or maybe completely different method? Thanks for any suggestions -
Cache router in Django - how to run python manage.py createcachetable properly for the related database
I am using Django for my project. I need to generate a new cache table in the database. The command python manage.py createcachetable doesn't work for db_my_project instead it works for the default one. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'db_my_project': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_db', 'USER': 'my_username', 'PASSWORD': 'my_password',, 'HOST': 'my_host', 'PORT': '3306', }, } I have the following cache settings in the settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'dataframe_cache', } } As you can see above from its location info, it is supposed to generate a the table 'dataframe_cache'. It is generating that table for the default database (db.sqlite3), but not for the db_my_project (mysql). I know that I should implement a cache router class like below. class CacheRouter: """A router to control all database cache operations""" route_app_labels = {'db_my_project'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'db_my_project' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'django_cache': return 'db_my_project' return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'db_my_project' return None My question is that where do I put this CacheRouter class in my Django project so that I can generate … -
Django - how to import sendgrid python library?
I would like to use Sendgrid's python library so I can use their Web API for sending email from Django. I installed the library and their example code says to from sendgrid import SendGridAPIClient. Django does not recognize this module though - import sendgrid could not be resolved. I am running django inside docker, I did docker-compose down and then docker-compose up -d --build after install sendgrid. I feel like I'm missing a fundamental step here. PS C:\Users\Doug\OneDrive\django\smartmark> pipenv install sendgrid Installing sendgrid… Adding sendgrid to Pipfile's [packages]… Pipfile.lock (1e7343) out of date, updating to (4cf710)… Locking [dev-packages] dependencies… Success! Locking [packages] dependencies… Success! Updated Pipfile.lock (1e7343)! Installing dependencies from Pipfile.lock (1e7343)… ================================ 37/37 - 00:00:02 PS C:\Users\Doug\OneDrive\django\smartmark> -
How do I make a button click change the django order_by?
Here's my views.py function. def publications(request): if request.method == 'POST': publications = UserPublications.objects.all().order_by('status_date') else: publications = UserPublications.objects.all().order_by('contributors') context = {'publications': publications} return render(request, 'users/publications.html', context) Here's my publications.html: <button type="submit" method="POST">Filter By Date</button> <ol class="text"> {% for publication in publications %} <div>{{publication.text}}</div> {% endfor %} </ol> I want a button to be clicked on and if someone clicks on it it changes to filter by date instead of by contributors (both attributes of my model). How would I do that? Right now I have no errors but when I click on the button it's not updating the sorting on my objects. Thanks in advance. -
Validation using clean method in models.Model Django
I try to use the clean method to validate fields so if the category equals to "cars" then the x field should't be entered. I tried something like this below, but it doesn't work at all. class Category(models.Model): name = models.CharField(primary_key=True, max_length=100) def __str__(self): return self.name class Product(models.Model): def clean(self): if self.category == "cars" and self.x is not None: raise ValidationError( _('information')) category = models.ForeignKey( Category, on_delete=models.PROTECT, default='cars') x = models.CharField( max_length=10, choices=X_OPTIONS, blank=True) When I am sending category: "cars", x: "sth", it doesn't hangle the error. -
Can't disconnect from Google OAuth2 using social-auth-app-django
I followed the official docs to set up the Disconnection pipeline in a Django project. Following other posts like, this and this I put in a Log out button a POST requisition to disconnect the Google OAuth2 account. So, in summary, I have: settings.py SOCIAL_AUTH_DISCONNECT_PIPELINE = ( # 'social_core.pipeline.disconnect.allowed_to_disconnect', 'social_core.pipeline.disconnect.get_entries', 'social_core.pipeline.disconnect.revoke_tokens', 'social_core.pipeline.disconnect.disconnect', ) template: <form action="{% url 'social:disconnect' 'google-oauth2' %}" method="post"> {% csrf_token %} <button>Sair</button> </form> But doing that, the Google Account is not logged out. The Home page is just refreshed. This is what I get in virtual webserver log: "POST /disconnect/google-oauth2/ HTTP/1.1" 302 0 "GET / HTTP/1.1" 200 4988 If I had another tab with Gmail logged in and refresh the page I keep logged in. Is there anything I'm missing? -
Django cannot resolve the name of the db service
I have a django application dockerized and a postgresql server. I'm using docker compose to put both them together. The problem is that I always get this error: web_1 | django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known This is my docker-compose.yml file: version: '3' services: web: image: "badger-dev" ports: - "8000:8000" volumes: - .:/app links: - db:db depends_on: - db db: image: "badger-postgres" container_name: db ports: - "5432:5432" I have also tried the following config with the same result: version: '2' services: web: image: "badger-dev" ports: - "8000:8000" volumes: - .:/app links: - db:db networks: - djangonetwork db: image: "badger-postgres" container_name: db ports: - "5432:5432" networks: - djangonetwork networks: djangonetwork: driver: bridge These are my settings: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'dbhvu01u3e3fug', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', # Use PgPool } } Any idea why it's not working? -
Django ForeignKey returning id instead of name
Api return Models Serializers And so i want to get the author name instead of id -
django formset template loop through fields disables delete featuer
Thank you for being here. I am not able to delete objects in django formset While i am looping through the fields in templates the. I can see the deletion box but when i hit submit the page refreshes and the object is exist. template.html {% for form in request_equipment_form %} <div class="card" style="width: 100% "> <div class="card-body"> <div class="d-flex flex-row" style="width:100%"> {{form.equipment}} {{form.quantity}} {{form.DELETE}} {{form.ORDER}} </div> </div> {% endfor %} But when i do not loop through the fields the delete feature works like charm {% for form in request_equipment_form %} <div class="card" style="width: 100% "> <div class="card-body"> <div class="d-flex flex-row" style="width:100%"> {{form.as_p}} </div> </div> {% endfor %} views.py if formset.is_valid(): instances = formset.save(commit=False) for d_obj in formset.deleted_objects: d_obj.delete() if not instances: return redirect(request.META.get('HTTP_REFERER')) for instance in instances: instance.user = request.user instance.flight = flight instance.station = flight.station instances = formset.save(commit=False) for instance in instances: instance.save() print(instance.date) return redirect(request.META.get('HTTP_REFERER')) -
Integrate BigBlueButton in Django
i installed BigBlueButton in my Django project and i create a meeting using the admin page. That's the meeting model showed in admin page. Meeting Name Meeting ID Created at Is running Actions Metting 2 Aug. 27, 2021, 4:17 p.m. False Create join link Start Now Metting 1 Aug. 27, 2021, 4:06 p.m. False Create join link Start Now But whenever i try to start a meeting an exception raise: RuntimeError at /admin/django_bigbluebutton/meeting/2/join/ No active exception to reraise Request Method: GET Request URL: http://127.0.0.1:8000/admin/django_bigbluebutton/meeting/2/join/ Django Version: 3.2.4 Exception Type: RuntimeError Exception Value: No active exception to reraise Exception Location: C:\Users\Galaxynet\AppData\Local\Programs\Python\Python39\lib\site-packages\django_bigbluebutton\bbb.py, line 221, in start this is the code of start function: def start(self, name, meeting_id, **kwargs): """ Start meeting with provided info. Most of BigBlueButton info is provided now. TODO: will add more configs for bigbluebutton later! """ call = 'create' attendee_password = kwargs.get("attendee_password", self.attendee_password) moderator_password = kwargs.get("moderator_password", self.moderator_password) # Get extra configs or set default values welcome = kwargs.get('welcome_text', _('Welcome!')) record = kwargs.get('record', BBB_RECORD) auto_start_recording = kwargs.get('auto_start_recording', BBB_AUTO_RECORDING) allow_start_stop_recording = kwargs.get('allow_start_stop_recording', BBB_ALLOW_START_STOP_RECORDING) logout_url = kwargs.get('logout_url', BBB_LOGOUT_URL) webcam_only_for_moderators = kwargs.get('webcam_only_for_moderators', BBB_WEBCAM_ONLY_FOR_MODS) voice_bridge = 70000 + random.randint(0, 9999) # Making the query string query = urllib.parse.urlencode(( ('name', name), ('meetingID', meeting_id), ('attendeePW', … -
where do these "not-found" wagtail errors come from?
This is a chunk of my HTTP logs from django v3.2 running wagtail. Looks as though django is trying to tell me where the missing media is but not able to. Because this is a thicket page with gallery sub-images of "featured pages" the view source in my browser doesn't reveal the image file attempt, but I am assuming it is the same issue as OP's with misconfigured MEDIA_ROOT. Strangely, not seeing any errors in the page's linked images when I bring the child page up in wagtail admin. Anyone have an idea why the missing image won't bubble up to the HTTP logs, or what causes the "media/not-found" substitution for the "real" item causing the 404, or how to unravel the error stack? I've found multiple instances of "not-found", but only in the wagtail "site-packages" /lib/python3.8/site-packages/wagtail folder. None of them give me an indication of why the page (or usually image) causing the 404 isn't returned in the HTTP logs but just the "not-found" URL. I could see what the missing image was (part of a block), and it actually wasn't missing, but possibly a cached copy of the page was causing the "not-found" error to be substituted. [25/Aug/2021 … -
How do I switch a dictsort in Django with a click of a button?
I'm trying to make a button that whenever someone clicks on it it'll change my dictsort to sort by a different attribute instead. Here's my code. I don't have any errors but the button isn't doing anything. I want the dictsort to switch to sorting by date if someone clicks on the button instead of sorting by authors which is the default. Thanks in advance. <button type="submit" onClick="{change text.for-loop|dictsort:'date'}"></button> <ol class="text"> {% for paragraph in paragraphs|dictsort:"authors" %} <div>{{paragraph.text}}</div> {% endfor %} </ol> -
How to add google 2factor authenticator in Django login?
is it possible to add google 2factor authenticator in Django login? if yes then how to add it? does any django package have for add google 2factor authenticator in django login? Many website using google 2factor authenticator in their login process. User need to install Google 2factor authenticator app in their phone and new code is generating after every few seconds. I am not interested to add otp login which send code to user phone via sms. I am looking somethings like google 2factor authenticator which generating code after every few seconds. -
Como evitar el resubmit de formulario al refrescar la pagina en django
buenas estoy haciendo una pequeña app de notas al guardar el formulario el views.py me devuelve a la misma pagina hasta hay todo bien, pero cuando actualizo la pagina me aparece un mensaje diciendo que el formulario sera enviado nueva mente def guardar(request): notas = noteblock.objects.all() note = formularionotes(request.POST) if note.is_valid(): note.save() return render(request,'notes.html',{'notas':notas}) alquien porfavor me explica como hago que esto no pase -
I have extended the default User table named UserProfile and want to access info from Product model but shown integrity error
UserProfile table: (Extended table of default User) from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE`enter code here` class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=CASCADE) k_name = models.CharField(max_length=100, default="krishok Name", null=True) k_address = models.CharField(max_length=300, default="Goes Krishok Address Here", null=True, blank=True) k_national_id_no = models.CharField(default="1", max_length=50) k_phone = models.CharField(default="01778956098", max_length=20) k_email = models.EmailField(default="xxx@gmail.com", max_length=254) k_image = models.ImageField(default = '', upload_to = 'upload/pkrishokImage/') national_id = models.ImageField(default= '',upload_to = 'upload/IDImage/') Product model code: from Store.models.userprofile import UserProfile from django.db import models from .categories import Category from .unit_type import Unit_Type class Product(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) unit= models.ForeignKey(Unit_Type, on_delete=models.CASCADE, default=1) Unit_price = models.IntegerField(default=0) #k_name = models.ForeignKey(UserProfile, on_delete=models.CASCADE)#this is the problem quantity = models.IntegerField(default=0) description = models.CharField(max_length=200, default='', null=True, blank=True) image = models.ImageField(upload_to = 'upload/productsImg/') @staticmethod def get_all_products(): return Product.objects.all() #Filtering by Category Id: # this method will bring all products by its categoryID @staticmethod def get_all_products_by_id(category_id): if category_id: return Product.objects.filter(category = category_id) else: return Product.get_all_products() #i am trying to get id from extended user table called UserProfile model and want to get access of #all data from Product model, so that i am trying to written my foreignKey at product table from UserProfile table but it's give me integrity … -
Align django crispy form with html headings
I have made a dynamic django crispy form in which users can add additional rows I only want headings on the first row i.e.: not: I have been able to remove the headings using a form helper and was then just going to add the headings separately in html but these do not align correctly: Does anyone have an idea as to either get it so only the first row has labels things align correctly? forms.py class MedFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_method = 'post' self.layout = Layout( Div( Div('med_name', css_class='col-3',), Div('dose', css_class='col-3',), Div('form', css_class='col-3',), Div('adherence', css_class='col-3',), css_class='row', ), Field('query', placeholder=kwargs.pop('query_placeholder', 'random text')), ) self.form_show_labels = False self.render_required_fields = True html <table id="currentmeds_table" border="0" cellpadding="0" cellspacing="5"> <thead> <tr> <div class="row" class="form-group"> <div class="col-3"> Medication </div> <div class="col-3"> Dose (mg) </div> <div class="col-3"> Formulation </div> <div class="col-3"> Adherence </div> </div> </tr> </thead> <tbody> <td> {% for form in currentmed_formset %} {% for fld in form.hidden_fields %}{{ fld }}{% endfor %} {% if form.instance.pk %}{{ form.DELETE }}{% endif %} {% crispy form med_formsethelper %} {% endfor %} </td> </tbody> </table> {{currentmed_formset.management_form}} -
How to Uninstall the Django-admin from Windows
By mistake, I installed Django-admin to my Windows instead of Virtualenv. Can anyone help me uninstalling this Django_admin from Windows?This is the version of Django-admin installed -
Django, HTML templates isn't rendering with debug True
My HTML templates are not rendering with I have my debug turned off/Debug False It throws a "Server Error 500" But if I try rendering a HttpResponse it works. My whole project works completely fine when I have my debug on True Please reply if you can help me. settings.py # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['{{ProjectName}}.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Custom Apps 'authSystem', 'posts', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'src.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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 = 'src.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') …