Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Change all other Boolean fields except one
I have a model which has a boolean field: class Library(SocialLinksModelMixin): """ Represents book shelves and places where people have / leave books. """ user = models.ForeignKey(...) is_main = models.BooleanField(default=False) User can have multiple Libraries and I would like to allow setting the main one to ease the flow in the app. What is the easiest way for switching only one Library is_main to True and all others to False (There is always only 1 Library for a user that is main) I'm thinking about querying for all libraries and updating each and every one. Maybe there is another way to do that functionality? -
Rendering items in a multipage django web application
I am trying to make two pages with items that can be added/edited/deleted from the admin panel. I have 2 pages which are Store and School Uniform. The issue is that when I am adding to the cart the items from the School Uniform page, the cart shows items from the store page. A similar thing happens when I am viewing details of the items on the School Uniform page. The detail view shows items from the store page. I think that the problem is in the id of items, but I don't know how to fix it. The full project source code: https://github.com/MARVLIN/Eshop.git The repository is called Eshop views.py def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store/store.html', context) def school_uniform(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] product2 = SchoolUniform.objects.all() context = {'products': product2, 'cartItems': cartItems} return render(request, 'store/school_uniform.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'store/cart.html', context) def checkout(request): data = cartData(request) cartItems = data['cartItems'] order = … -
Django - How to render a form field as a table with only some of the items that match a specific criteria?
I have this form: forms.py from django.forms.models import ModelForm from .models import Order class OrderForm(ModelForm): class Meta: model = Order fields = '__all__' From this model: models.py from django.db import models from django_countries.fields import CountryField from django.core.validators import MaxValueValidator class Category(models.Model): name = models.CharField(max_length=255) description = models.TextField(blank=True) image = models.ImageField(blank=True) def __str__(self) -> str: return f"{self.name}" class Product(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(to=Category, on_delete=models.CASCADE) description = models.TextField(blank=True) price = models.DecimalField(max_digits=8, decimal_places=2) image = models.ImageField(blank=True) vat_percentage = models.DecimalField(max_digits=4, decimal_places=2, blank=True) @property def price_with_vat(self): if self.vat_percentage: return (self.price / 100 * self.vat_percentage) + self.price else: return self.price def __str__(self) -> str: return f"{self.name} / {self.price} EUR" class Address(models.Model): street = models.CharField(max_length=255) city = models.CharField(max_length=255) country = CountryField() zip_code = models.PositiveIntegerField(validators=[MaxValueValidator(99999999)]) def __str__(self): return f"{self.street} / {self.city}" class DeliveryAddress(models.Model): street = models.CharField(max_length=255) city = models.CharField(max_length=255) country = CountryField() zip_code = models.PositiveIntegerField(validators=[MaxValueValidator(99999999)]) def __str__(self): return f"{self.street} / {self.city}" class Order(models.Model): name = models.CharField(max_length=255) surname = models.CharField(max_length=255) address = models.ForeignKey(Address, on_delete=models.PROTECT) delivery_address = models.ForeignKey(DeliveryAddress, on_delete=models.PROTECT) company_name = models.CharField(max_length=255) company_ico = models.PositiveIntegerField(validators=[MaxValueValidator(9999999999)]) company_dic = models.PositiveIntegerField(validators=[MaxValueValidator(999999999999)], blank=True) company_vat = models.PositiveIntegerField(validators=[MaxValueValidator(999999999999)], blank=True) products = models.ManyToManyField(Product) And this is my view: views.py def create_order(request): if request.method == 'GET': context = { 'form': OrderForm } return render(request, 'eshop/create_order.html', context=context) … -
Why is my model instance not serializable?
I have the following model class class Club(models.Model): """ A table to store all clubs participating """ name = models.CharField(max_length=30) logo = models.ImageField(upload_to='images/') goals_last_season = models.IntegerField() points_last_season = models.IntegerField() def __str__(self): return F'{self.name}' and try to serialize it with htis encoder class ExtendedEncoder(DjangoJSONEncoder): def default(self, o): if isinstance(o, ImageFieldFile): return str(o) else: return super().default(o) as follows: def get_offer_details(request): """ View to get the queried club's data :param request: :return: """ # Get the passed club name club_name = request.POST.get('club_name') # Query the club object club_obj = Club.objects.get(name=club_name) # Create dict data = { 'club_obj': club_obj } # Return object to client return JsonResponse(data, safe=False, cls=ExtendedEncoder) which raises TypeError: Object of type Club is not JSON serializable. How can I basically serialize this? -
Please stuck for two days on this custom class detail class view is not display record
Please can anyone help me out on this issue Please stuck for two days on this custom class detail class view is not display record, i think is reverting back to the logged in user data instead of the detail from the list my code below not error even printed out the variable but still blank view.py class ListOfEnrolledCandidate(View): def get(self, request, **kwargs): users = CustomUser.objects.filter(user_type=6).select_related('candidates') context = { 'users': users } return render(request, 'superadmin/candidates/list-enrolled.html', context) class CandidateProfile(View): def get(self, request, **kwargs): user = CustomUser.objects.get(id=int(kwargs['id'])) print(user) return render(request, 'superadmin/candidates/profile-detail.html',{'users':user.id}) models.py class Candidates(models.Model): admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name="candidates") profile_pic = models.ImageField(default='default.jpg', upload_to='upload') middle_name = models.CharField(max_length=255) gender = models.CharField(max_length=255) country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True) state = models.ForeignKey(State, on_delete=models.CASCADE) local = models.ForeignKey(Local, on_delete=models.CASCADE) dob = models.CharField(max_length=100) candclass = models.CharField(max_length=100, null=True) parentno = models.CharField(max_length=11, null=True) exam_year = models.CharField(max_length=100, null=True) profile_pic = models.ImageField(default='default.jpg', upload_to='media/uploads') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() def __str__(self): return self.middle_name class CandidateSubject(models.Model): admin = models.OneToOneField(CustomUser, null=True, on_delete=models.CASCADE) subject1 = models.CharField(max_length=255, null=True) subject2 = models.CharField(max_length=255, null=True) subject3 = models.CharField(max_length=255, null=True) subject4 = models.CharField(max_length=255, null=True) subject5 = models.CharField(max_length=255, null=True) subject6 = models.CharField(max_length=255, null=True) subject7 = models.CharField(max_length=255, null=True) subject8 = models.CharField(max_length=255, null=True) subject9 = models.CharField(max_length=255, null=True) subject10 = models.CharField(max_length=255, null=True) created_at … -
How to add images to a Pdf file from static files using borb library and Django
I want to add an image to a pdf file, the images are in the static directory: 'static/images/logo.png' Settings file: STATIC_URL = '/static/' Part of the Code: from borb.pdf.canvas.layout.image.image import Image page_layout.add( Image( "/static/images/logo.png", width=Decimal(128), height=Decimal(128), )) Error Code: MissingSchema: Invalid URL '/static/images/Logo.png': No schema supplied. Perhaps you meant http:///static/images/Logo.png? I do not want to show it in a front end template, instead is a backend function to generate pdfs. Do i have to provide/generate any kind of url link to the Image function?? how to do it? Thanks ! -
Django: "bash: npm: command not found" error when installing Tailwind CSS
I'm trying to install TailwindCSS on my Django App using this tutorial, unfortunly I'm stuck at this part $ npm init -y && npm install tailwindcss autoprefixer clean-css-cli && npx tailwindcss init -p When I try I get back this error: bash: npm: command not found I've downloaded and installed node.js and when I check using npm -v it seems that I have the 8.3.1 version and with node -v I got v16.14.0. I've tried installing again TaiwindCSS and I still get the error bash: npm: command not found Can somebody help me understand what I'm doing wrong? Thank you all -
How to return django ibject instance to client via ajax
I'm struggling to use an async (ajax) returned Django model instance on the client side. Something doesn't make sense with parsing the object to json / dict back and forth I assume. # views.py def get_offer_details(request): """ View to get the queried club's data """ # Get the passed club name club_name = request.POST.get('club_name') # Query the club object club_obj = Club.objects.get(name=club_name) # Transform model instance to dict dict_obj = model_to_dict(club_obj) # Serialize the dict serialized_obj = json.dumps(str(dict_obj)) # Return object to client return JsonResponse({'club_obj': serialized_obj}, safe=False) # .js function get_offer_details(club_name) { $.ajax({ url : "/get-offer-details/", // the endpoint headers: {'X-CSRFToken': csrftoken}, // add csrf token type : "POST", // http method data : { club_name : club_name }, // data sent with the post request // Update client side success : function(data) { // Grab the returned object let obj = data.club_obj // Parse it into an object let parsed_obj = JSON.parse(obj) // console.log(typeof) returns "string" // Access the data of the object let prev_goals = obj.goals_last_season // console.log(prev_goals) returns undefined ... console.log(data.obj) --> {'id': 2, 'name': 'FC Bayern Munich', 'logo': <ImageFieldFile: images/fcb_logo.png>, 'goals_last_season': 79, 'points_last_season': 71} -
Django jwt auth: How to override "Invalid or expired token" Error Message
How can i override default expired token message? example: right now im getting { "error": { "message": "Given token not valid for any token type", "status": 401, "error": "Invalid or expired token", "error_code": 6, "description": "The access token used in the request is incorrect or has expired. " } } in response message How can i change it -
Django Rest Framework user auth with React
Can anybody tell me the updated way to use User Authentication for Django Rest Framework? Each tutorial seems outdated. I would like to sign up, login logout using React with fetch function. Please share your experience. -
Bootstrap Modal Box Not showing in multiple events
I am trying to use Bootstrap modal box in my blog post website. On my Index page I am showing multiple posts and for each post on a button I want to open a modal box but I am not able to make it work. can some one point out where I am making the mistake {% for i in post %} <button type="button" class="btn btn-primary" data-toggle="modal" data- target="#exampleModal{{i.post_id}}"> Launch demo modal </button> <div class="modal fade" id="exampleModal{{i.post_id}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <h1>Yes</h1> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data- dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> {% endfor %} -
How do I create unique log filenames using thread local in a gunicorn wsgi app?
I have a Django app with logging configured using dictConfig. Within dictConfig I call a custom filehandler that returns an instance of FileHandler with a filename. The filename is obtained by making an instance of thread local and giving it a uuid attribute. The app is served via gunicorn. When I test the app making two calls via postman, logs are written to the same file. I thought wsgi created a unique Django process, but I think it creates a process per worker that shares memory space, which I believe is why the filename remains the same after Django sets up the logger. How do I create unique log filenames using thread local in a gunicorn wsgi app? -
query ManyToManyfield for requested user
I have two models, a user model and a sport model. These two models have a m2m relationship as a user can do multiple sports and a sport can be played by more than one user. I want to get a query set of a user's sports, so only the sports a specific user does shows up for that user. I have created a context_processors.py file so that the information is available on all pages of the site. The problem is that I don't know how to query the database to get this information. These are my models: class Sport(models.Model): name = models.CharField(max_length=100, null=False) class User(AbstractUser): ... sports = models.ManyToManyField(Sport) Right now, I get all the sports available, like this def test(request): sports = Sport.objects.all() return { 'x': sports } I just want to get the sports the requested user is assigned to in the sports variable. -
Internal server [closed]
I m having the this issues after deploying an app on DigitalOcean. I Set Up a wagatail app with Postgres, Nginx, and Gunicorn on Ubuntu 20. And after the the configurations, here is what I get when I send a message from the contact app. Internal server error Sorry, there seems to be an error. Please try again soon. I have sentry running and telling me the errors like this: 1- ConnectionRefusedError /{var} New Issue Unhandled [Errno 111] Connection refused 2 - Invalid HTTP_HOST header: '${ip}:${port}'. The domain name -
python name '_mysql' is not defined
I build a virtual environment with python 3.7.10, by installing mysql and mysqlclient It is mysql 8.0.28, mysqlclient 2.1.0. When running python manage.py migrate It comes out like this: (test) ➜ backend git:(main) python manage.py migrate Traceback (most recent call last): File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 0x0002): symbol not found in flat namespace '_mysql_affected_rows' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/db/models/base.py", line … -
Why is django adding two slashes at the end of my urls?
I'm new to django and I'm trying to develop my first website. I've searched for similar questions but I couldn't find any (or maybe I've only searched the wrong query). What I'm here to asking is why django is adding a final slash into my url? and why is it doing this just in few occasions? I'd want to explain you better what it's happening to me. This is my urls.py (a portion) urlpatterns = [ path('admin/', admin.site.urls), path('', home, name='home'), path('new/', new, name="new"), path('attachements/<str:pk>/<str:var>/', attachements, name="attachements"), path('new_2_4/<str:pk>/<str:var>/', new_2_4, name="new_2_4"), path('new_4e2/<str:pk>/<str:var>//', new_4e2, name="new_4e2"), # others ] In my template.html I've created tag which allows me to go from a page to others, for example: <ul class="nav nav-tabs"> <li class="nav-item" style="background-color:powderblue;"> <a class="nav-link" href="{% url 'attachements' att.id var%}">Allegati</a> </li> <li class="nav-item" style="background-color:powderblue;"> <a class="nav-link" href="{% url 'new_2_4' att.id var %}">4</a> </li> <li class="nav-item" style="background-color:powderblue;"> <a class="nav-link" href="{% url 'new_4e2' att.id var %}">4.2</a> </li> </ul> <div style="position:relative; left:20px;"> <a class="btn-sm btn-info" href="{% url 'new_2_4' att.id var %}">&#x2190;</a> <a class="btn-sm btn-info" href="{% url 'new_4e3' att.id var %}">&#x2192;</a> </div> When I first have designed the whole thing, my url for 'new_4e2' didn't have two final slashes: I've had to add one final manually because … -
Ajax requires Basic authentication again
I have project with django and nginx and nginx has the basic authentication Accessing top page / the basic authentication works well. server { listen 80; server_name dockerhost; charset utf-8; location /static { alias /static; } location / { auth_basic "Restricted"; auth_basic_user_file /etc/nginx/.htpasswd; proxy_pass http://admindjango:8011/; include /etc/nginx/uwsgi_params; } } but in template, I use ajax to local api /api/myobj/{$obj_id} $.ajax({ url:`/api/myobj/${obj_id}/` It requires the authentication again and pop up appears. I wonder /api/myobj/ is under / Why it requires authentication again?? And even I put the id/pass correctly, it is not accepted. I tried like this ,but it also in vain. $.ajax({ url:`/api/myobj/${obj_id}/`, username: "myauthid", password: "myauthpass", -
Saving and displaying multiple checkboxes to Django ModelMultipleChoiceField
I am a beginner on django 2.2 and I can't correctly send multiple choices in the database. In my field table the days are stored like this: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] My form : CHOICESDAY = (("Monday", "Monday"), ("Tuesday", "Tuesday"), ("Wednesday", "Wednesday"), ("Thursday", "Thursday"), ("Friday", "Friday"), ("Saturday", "Saturday"), ("Sunday", "Sunday") ) class FgtScheduleForm(forms.ModelForm): days = forms.MultipleChoiceField(required=True, choices=CHOICESDAY, widget=forms.CheckboxSelectMultiple( attrs={'class': 'checkbox-inline'})) class Meta: model = FgtSchedule fields = ('name','days') widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control form-form ' 'shadow-none td-margin-bottom-5'}), } fields = ('name', 'days') My model class FgtSchedule(models.Model): days = models.CharField(max_length=100, blank=True) My view : def fg_schedule_list(request): list_fg_sch = FgtSchedule.objects.all() return render(request, 'appli/policy/fg_schedule.html', {'list_fg_sch': list_fg_sch}) My template {% for fg_sch_list in list_fg_sch %} <tr> <td>{{ fg_sch_list.id }}</td> <td>{{ fg_sch_list.name }}</td> <td>{{ fg_sch_list.days|replace_days }}</td> </tr> {% endfor %} My custom tags : @register.filter def replace_days(value): CHOICESDAY = {"Monday": "Monday", "Tuesday": "Tuesday", "Wednesday": "Wednesday", "Thursday": "Thursday", "Friday": "Friday", "Saturday": "Saturday", "Sunday": "Sunday"} return CHOICESDAY[value] The problem is when I want to display later all the days I have KeyError at "['1', '2']" -
is there a way to find duplicated value that has both the same address and pickup date in two different table?
I am currently working on a delivery app. Basically, what I am trying to achieve here is to have a counter that display out any potential duplicated jobs that the customer might have accidently double entered. The criteria to be considered as a duplicated job is as such: Has to have same delivery_address and same pickup_date. This is my postgresql tables: class Order(models.Model): id_order = models.AutoField(primary_key=True) class OrderDelivery(models.Model): order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) delivery_address = models.TextField() class OrderPickup(models.Model): order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) pickup_date = models.DateField(blank=True, null=True) This is what I have came up with so far: def dashboard_duplicated_job(orders, month): # This function finds for jobs that has # (1) exact pickup_date # (2) exact delivery address # and mark it as duplicated job. # Find current month, if not take current year now = timezone.localtime(timezone.now()) month = "12" if month and int(month) == 0 else month if month == 12 or month == '12': now = timezone.localtime(timezone.now()) last_month = now.today() + relativedelta(months=-1) start_date = last_month.replace(day=1).strftime('%Y-%m-%d') year = last_month.replace(day=1).strftime('%Y') month = last_month.replace(day=1).strftime('%m') last_day = calendar.monthrange(int(year), int(month))[1] string_start = str(year) + "-" + str(month) + "-01" string_end = str(year) + "-" + str(month) + "-" + str(last_day) start_date = … -
Update Boolean field and Integer fields from Django view
Can someone please point me in the right direction here. I have a quiz app where I want to implement some user progress objects. I have a QuizResult model which foreignkeys to user, quiz and lesson. What I want is to be able to update a couple of fields: score (integer field) and complete (boolean field) from my views.py function. when I try to update these fields from my frontend I get a no errors, but the object shows complete and score fields as null. Here is my model: class QuizResult(models.Model): student = models.ForeignKey(User, related_name="results", on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, related_name="results", on_delete=models.CASCADE) lesson = models.ForeignKey(Lesson, null=True, blank=True, related_name="results", on_delete=models.CASCADE) score = models.IntegerField(blank=True, null=True) complete = models.BooleanField(default=False) and my view.py function: @api_view(['POST']) def post_progress(request, pk): data = request.data score = data.get('score') complete = data.get('complete') quiz = Quiz.objects.get(pk=pk) user_progress = QuizResult.objects.create(quiz=quiz, score=score, complete=complete, student=request.user) serializer = QuizResultSerializer(user_progress, data=data) return Response(serializer.data) -
How to have multiple Auth models in django
I have an application where I've two models both models have same fields client buyer I'm using separate models because client can also signs up as a buyer using the same email and vice versa. I don't want to use single model for both client and buyer with some checks like is_buyer/is_client. How do I achieve something like class Client(AbstractUser): email = Field() password = Field() class Buyer(AbstractUser): email = Field() password = Field() AUTH_USER_MODEL=app.Client AUTH_USER_MODEL=app.Buyer Also I'm using simpleJWT library, so I can generate jwt when the client or buyer logins in. -
Compress an image to less than 1MB (one) and than allow users to download the image using Python in Django project
I'm working on a Django project. All I need is to take a image as an input from user than I have to compress it in less than 1MB or specific size without losing too much quality. Then allow users to download the image -
Run Tasks on Celery with Django Error: raised unexpected: ConnectionRefusedError(111, 'ECONNREFUSED')
I just run Redis on my VPS with no problem: -------------- celery@s1550.sureserver.com v5.2.3 (dawn-chorus) --- ***** ----- -- ******* ---- Linux-5.15.19-sure2-x86_64-with-debian-10.11 2022-03-08 17:22:46 *** --- * --- ** ---------- [config] ** ---------- .> app: web_edtl:0x7c2374cc52e8 ** ---------- .> transport: redis+socket:///home/$USER/private/redis/redis.sock ** ---------- .> results: socket:///home/hamutuk/private/redis/redis.sock *** --- * --- .> concurrency: 2 (eventlet) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . imagekit.cachefiles.backends._generate_file [2022-03-08 17:22:46,248: INFO/MainProcess] Connected to redis+socket:///home/$USER/private/redis/redis.sock [2022-03-08 17:22:46,252: INFO/MainProcess] mingle: searching for neighbors [2022-03-08 17:22:47,267: INFO/MainProcess] mingle: all alone [2022-03-08 17:22:47,284: INFO/MainProcess] pidbox: Connected to redis+socket:///home/$USER/private/redis/redis.sock. [2022-03-08 17:22:47,292: WARNING/MainProcess] /home/$USER/private/project/project_env/lib/python3.7/site-packages/celery/fixups/django.py:204: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! leak, never use this setting in production environments!''') [2022-03-08 17:22:47,293: INFO/MainProcess] celery@s1550.sureserver.com ready. But web i run some task to Send Email i got a Error : raised unexpected: ConnectionRefusedError(111, 'ECONNREFUSED') This is log off error: [2022-03-08 17:04:44,527: ERROR/MainProcess] Task appname.tasks.task_name[892f4462-2745-4bb7-9866-985cd3407c86] raised unexpected: ConnectionRefusedError(111, 'ECONNREFUSED') Any Ideia how to Fix it? Thank You -
Running a command from a command line tool from another app in django
I am building a Webapp using Django and want to generate some comments from a command-line tool present in the same directory as the web app. What are the different methods to call this tool from the web app and run commands in the terminal and extract output from it and display it in a web app? -
How I can show selectbox from models in my form?
How I can show selectbox from models in my form. Output for below code does not show options for selectbox. #models.py class Reg(models.Model): options = ( ('one', 'option1'), ('two', 'option2'), ) types = models.CharField(max_length=30, choices=options,null=True) company = models.CharField(max_length=50,null=True) #form.py from django import forms from .models import Reg class Regform(forms.ModelForm): class Meta: model = Reg fields = ['types','company'] types = forms.CharField( widget=forms.Select( attrs={'class': 'form-control'} ), label="Type", )