Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python supervisord error: <class 'ConnectionRefusedError'>
I am trying to run my celery tasks in background using supervisor. I foolowed this article to setup celery and supervisor. However when I try to run below command : sudo supervisorctl reread I am getting following error : error: <class 'ConnectionRefusedError'>, [Errno 111] Connection refused: file: /usr/local/lib/python3.6/dist-packages/supervisor/xmlrpc.py line: 560 My environment details : Python 3.6.5 Django 1.11 (In a virtual environment) supervisord --version 4.0.4 -
How to use validate_unique validation in django form
Anyone know how to use validate_unique validate in django i used in view.py, it raise an validation error, that's good but this error is not showing me properly regist = UserModel(username=uname, email=email, name=name, password=password, status=1) regist.validate_unique() -
How to connect a Django rest framework into android app in testing environment?
I have built a django website for blog posts, and i have built rest APIs for it also so i can use it into my android app, but that website is working in my local host, now i have tried to connect it with an android app using retrofit and tried to make a simple call from the android app but it doesn't work, i just need the very basic steps to connect that local host to my android app and i will take care of retrofit calls and other coding stuff. I have already tried to create retrofit client passing BASE_URL = "http://127.0.0.1:8000" but it doesn't work too private static final String BASE_URL = "http://127.0.0.1:8000/api/"; private static RetrofitClient instance; private Retrofit retrofit; private RetrofitClient(){ retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } public static synchronized RetrofitClient getInstance(){ if(instance == null){ instance = new RetrofitClient(); } return instance; } public Api getApi(){ return retrofit.create(Api.class); } When making a simple call it the onFailure method triggers -
django images cannot be updated from defaults
I have an image upload function in django. However, images cannot be uploaded. The page is redirected to successURL. I don't understand the cause. The view is current because it uses multiple forms. #view def UserEdit(request): if request.method == 'POST': form = forms.UserUpdateForm(request.POST, instance=request.user) subform = forms.ProfileUpdateForm(request.POST, instance=request.user.profile) if all([form.is_valid(), subform.is_valid()]): user = form.save() profile = subform.save() return redirect('person:myaccount', username=request.user) else: form = forms.UserUpdateForm(instance=request.user) subform = forms.ProfileUpdateForm(instance=request.user.profile) return render(request, 'accounts/accounts_edit.html', { 'form': form, 'subform': subform, }) #form class ProfileUpdateForm(BaseModelForm): class Meta: model = profile fields = ('first_name','last_name','birthday','image',) class UserUpdateForm(BaseModelForm): class Meta: model = User fields = ('username','email',) #model class profile(models.Model): image = models.ImageField(upload_to='profile/',default='profile/default.jpg') #html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="text-center col-lg-6 col-md-6 col-sm-10 mx-auto"> <div class="form-group"> {{ form }} </div> <div class="form-group"> {{ subform }} </div> <button type="submit" class="fadeIn fourth btn btn-light">Submit</button> </div> </form> -
initializing Foreign Key models in code has no effect
I have a foreign key model like this: invite_discount_owner = models.ForeignKey('self', verbose_name='aaa', null=True, blank=True, on_delete=models.CASCADE, related_name='invited_customer') and in some part of my code, I want to initialize it with a correct data type: request.user.invite_discount_owner = discount_owner but it has no effect and this field stays empty! -
django: while files are preparing for download , show loading animation
I use Django , When files are preparing for download , I want to show loading circle animation , How can i understand files preparing finish time ? I try this code but its useless because it calculate is long for response request.start_time = time.time() print("start") print(request.start_time) print("final") print(time.time()) total = time.time() - request.start_time print("total unclear") print(total) print("total") print(int(total * 1000)) No error -
How to print the string value of a choices field
I have an integer field that provides 3 choices for a blog post: class Post(models.Model): STATUS_DRAFT = 0 STATUS_PUBLISHED = 1 STATUS_DELETED = 2 STATUS_CHOICES = ( (STATUS_DRAFT, 'draft'), (STATUS_PUBLISHED, 'published'), (STATUS_DELETED, 'deleted'), ) status = IntegerField(choices=STATUS_CHOICES, default=STATUS_DRAFT) When I render this in a template with {{ blog.status }} it prints the integer value (0, 1, 2). How can I call it to print the string value (draft, published, deleted)? -
Authorization model for REST API for ReactJs and Django
Hi I am trying to create an rest api using Django Framework and there is independent frontend part of ReactJs .Basically Reactjs will consume the Django rest_api .But I want to have authentication also provided to our api.So how can we proceed with it.Can anyone please explain? -
1054, "Unknown column 'user_account_id_fk_id' in 'field list'"
I focusing in insert log table that relate with user account and i have got a problem about inserting new row using django in views file. So it may came from my models. I Have no idea how to fixed this problem. I was change both of models settings and in views file by change queryset using get all and filter Models file class user_account(models.Model): user_account_id = models.IntegerField(primary_key=True, max_length=11, unique=True, null=False) username = models.CharField(max_length=50) password = models.CharField(max_length=255) display_name = models.CharField(max_length=100) mobile_no = models.CharField(max_length=50) email = models.CharField(max_length=255) is_delete = models.SmallIntegerField(max_length=1) create_date = models.DateTimeField() create_user_account_id = models.IntegerField(max_length=11) modify_date = models.DateTimeField() modify_user_account_id = models.IntegerField(max_length=11) delete_date = models.DateTimeField() delete_user_account_id = models.IntegerField(max_length=11) last_login = models.DateTimeField() is_authenticated = models.SmallIntegerField(max_length=1) class Meta: app_label = 'users' db_table = 'user_account' class user_account_log(models.Model): user_account_log_id = models.BigIntegerField(primary_key=True, max_length=20) user_account_id_fk = models.ForeignKey(user_account, unique=True, on_delete=models.DO_NOTHING, related_name = 'user_acc') action = models.CharField(max_length=100) title = models.CharField(max_length=100) description = models.TextField() refer_id = models.CharField(max_length=50) refer_table = models.CharField(max_length=50) class Meta: app_label = 'users' db_table = 'user_account_log' Views file user_log = user_account_log() user_log.action = "aaaa" user_log.title = "" user_log.description ="" user_log.refer_id = "AAAA" user_log.refer_table = "" user_log.user_account_id_fk_id = str(user_account.objects.get(user_account_id=request.user.user_account_id).user_account_id) # Save user_log.save() -
Django OperationalError: Parser Stack Overflow
I have a multi-page form for an accounting app in my project. The first page allows the user to select multiple creditors, the second to select multiple debtors, and the third generates a table so they can input the credit from each debtor to each creditor. Each page of the form passes the selected data to the next page via POST (using the UUID of the accounts in question), and the final page has the "submit" button that actually generates the transaction object in the database. When I use the form with a large number of debtors or creditors selected, I get an "OperationalError: Parser Stack Overflow." From the only other question on this topic I can find (django.db.utils.OperationalError: parser stack overflow) it looks like I need to either find a slimmer way of transmitting that data (perhaps by creating an "intermediary" model in the database to hold the data from each page so that each page need only be passed a single object). However, as you can see from the error below, it is the "account_list" that causes the overflow. This list comes from the query: Account.objects.all().order_by('type') So I am unsure that this would solve the problem. Alternatively, I … -
DRF formatting XLSX content
I am trying to set a different color on every second row in XLSX file. From the documentation I see that I can pass some conditions using body property or get_body() method, but this only allows me to set somewhat "static" conditions. Here is the ViewSet config responsible for rendering the XLSX file: class MyViewSet(XLSXFileMixin, ModelViewSet): def get_renderers(self) -> List[BaseRenderer]: if self.action == "export": return [XLSXRenderer()] else: return super().get_renderers() @action(methods=["GET"], detail=False) def export(self, request: Request) -> Response: serializer = self.get_serializer(self.get_queryset(), many=True) return Response(serializer.data) # Properties for XLSX column_header = { "titles": [ "Hostname", "Operating System", "OS name", "OS family", "OS version", "Domain", "Serial number", "Available patches", ], "tab_title": "Endpoints", "style": { "font": { "size": 14, "color": "FFFFFF", }, "fill": { "start_color": "3F803F", "fill_type": "solid", } } } body = { "style": { "font": { "size": 12, "color": "FFFFFF" }, "fill": { "fill_type": "solid", "start_color": "2B2B2B" }, } } -
form.is_valid() not working when using django forms for updating information to the databse
So I wanna be able to update information of a router in the database using a form, I wanna have a form pre-populated with that specific router details. The problem is that form.is_valid() is not working I tried using {{ form.errors }} {{ form.non_field_errors }} and print(form.errors) but none of them worked views.py (incomplete) def info_router(request, pk): rout = Routers.objects.get(sn=pk) if request.method == 'GET': # Insert the info in forms form = UpdateRouter() rout = Routers.objects.get(sn=pk) args = {'router': rout} return render(request, "router_info.html", args) if request.POST.get('delete'): # Delete router rout.delete() messages.warning(request, 'Router was deleted from the database!') return redirect("db_router") if request.method == 'POST': #Updating the form form = UpdateRouter(instance=Routers.objects.get(sn=pk)) print(form) print(form.errors) if form.is_valid(): data = UpdateRouter.cleaned_data mac = data['mac'] print(mac) return HttpResponseRedirect('db_router') else: print("Invalid form") return render(request, "db_router.html", {'form': form}) forms.py class UpdateRouter(ModelForm): class Meta: model = Routers fields = ['model', 'ip_addr', 'name', 'sn', 'mac'] template <form class="form-horizontal" action="" method="post"> {% csrf_token %} <div class="form-group"> <!-- Form with the router details --> <label class="control-label col-sm-2" for="text">Serial number:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="text" name="sn" value="{{ router.sn }}" readonly> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="text">Model:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="text" value="{{ router.model }}" name="model" readonly> </div> </div> <div … -
Django HoneyPot Change Password Issue
I would appreciate if you could give me any clue! As I don't have experience in this, probably I've misunderstood smth. I'm using honeypot, more specifically honeypot.middleware.HoneypotMiddleware with HONEYPOT_FIELD_NAME in my API (settings.py). As for the moment it's enough, I'm using the basic implementation for login, password change, reset from django.contrib.auth. In login I did a small customization so I added it in the url (authentication_form=CustomAuthenticationForm). So I don't konw what I'm missing because the login page works (it is also a form), but the password change, reset ones are returning 400 Bad Request. Honey Pot Error (honey_pot_fieldname). Request aborted. django: 2.1.2 django-honeypot: 0.7.0 Thanks in advance! -
django not responding via submit in frontend using post request in form
front end is not giving response to djangi function call via forms <form method="post" action="choose" class="login100-form validate-form" id="loginFrm"> {% csrf_token %} <span class="login100-form-title p-b-59"> Sign In </span> <div class="wrap-input100 validate-input" data-validate = "Valid email is required: ex@abc.xyz"> <!-- <span class="label-input100">Email</span> --> <input class="input100" type="text" name="email" placeholder="Email address..."> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input" data-validate = "Password is required"> <!-- <span class="label-input100">Password</span> --> <input class="input100" type="text" name="pass" placeholder="Password"> <span class="focus-input100"></span> </div> <div class="flex-m w-full p-b-33"> <div class="contact100-form-checkbox"> <span class="txt1"> <a href="javascript:void(0)" class="txt2 hov1" id="goForgot"> Forgot Password? </a> </span> </div> </div> <div class="container-login100-form-btn"> <div class="wrap-login100-form-btn"> <div class="login100-form-bgbtn"></div> <button type="submit" class="login100-form-btn"> Sign In </button> </div> <a href="javascript:void(0)" class="dis-block txt3 hov1 p-r-30 p-t-10 p-b-10 p-l-30" id="goSignup"> Sign Up <i class="fa fa-long-arrow-right m-l-5"></i> </a> </div> </form> -
Django - How to use the exact same clean() method on multiple forms
I have multiple forms that uses the same clean() and clean_<field_name>() methods. My problem is that i write the exact same code for all my forms, something like: forms.py class FirstForm(forms.Form): ... clean(): <long clean code that repeats on all forms> clean_field1(): <clean_field1 code that repeats on all forms> class SecondForm(forms.Form): ... clean(): <long clean code that repeats on all forms> clean_field1(): <clean_field1 code that repeats on all forms> class ThirdForm(forms.Form): ... clean(): <long clean code that repeats on all forms> clean_field1(): <clean_field1 code that repeats on all forms> So my question is what it the best approach to write those clean() methods on 1 place and just call them on different forms? -
Upload multiple images Django admin and associate to another model
I am creating a property app and want to associate multiple images to one property. I want the images to be uploaded when the property is being created in the admin panel. Also, I want to return the array containing URLs of the images associated with the property when I return the properties details from the endpoint. How do I do this? Below is the code I have so far. # models.py from django.contrib.postgres.fields import ArrayField from django.db import models from django import forms class ChoiceArrayField(ArrayField): """ A field that allows us to store an array of choices. Uses Django's Postgres ArrayField and a MultipleChoiceField for its formfield. """ def formfield(self, **kwargs): defaults = { 'form_class': forms.MultipleChoiceField, 'choices': self.base_field.choices, } defaults.update(kwargs) # Skip our parent's formfield implementation completely as we don't # care for it. # pylint:disable=bad-super-call return super(ArrayField, self).formfield(**defaults) class Property(models.Model): DURATION = ( ('Short Term', 'Short Term'), ('Long Term', 'Long Term') ) RENT_TYPE = ( ('Shared Home', 'Shared Home'), ('Entire Home', 'Entire Home') ) FURNISHING = ( ('Fully Furnished', 'Fully Furnished'), ('Semi Finished', 'Semi Furnished'), ('Unfurnished', 'Unfurnished') ) AMENITIES = ( ('Free Parking', 'Free parking space'), ('Clean Water and Treated Water', 'Clean and Treated Water'), ('Security', 'Security'), ('Ensuite', … -
Using supervisord for Celery for duplicate django projects
Goal On my server, I have two "identical" Django projects: one for staging and one for production (they both have their own MySQL database). I am trying to set up Celery using supervisord for both of these projects but I can't manage to do it. What I currently have Production: project-production/project/settings.py # Celery BROKER_URL = 'redis://localhost:6379/0' CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE CELERY_DEFAULT_QUEUE = 'production' CELERY_DEFAULT_ROUTING_KEY = 'production' Production: project-production/project/celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project', broker='redis://localhost:6379/0') app.config_from_object('project.settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) Production: project-production/supervisord.conf [program:celeryd0] directory=/absolute/path/to/project-production command=/absolute/path/to/project-production-virtualenv/bin/celery worker --app=project -l info stdout_logfile=/absolute/path/to/project-production-logs/celeryd.log stderr_logfile=/absolute/path/to/project-production-logs/celeryd.log autostart=true autorestart=true startsecs=10 stopwaitsecs=600 Staging: project-staging/project/settings.py # Celery BROKER_URL = 'redis://localhost:6379/1' CELERY_BROKER_URL = 'redis://localhost:6379/1' CELERY_RESULT_BACKEND = 'redis://localhost:6379/1' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE CELERY_DEFAULT_QUEUE = 'staging' CELERY_DEFAULT_ROUTING_KEY = 'staging' Staging: project-staging/project/celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project', broker='redis://localhost:6379/1') app.config_from_object('project.settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) Staging: project-staging/supervisord.conf [program:celeryd1] directory=/absolute/path/to/project-production command=/absolute/path/to/project-production-virtualenv/bin/celery worker --app=project -l info stdout_logfile=/absolute/path/to/project-staging-logs/celeryd.log stderr_logfile=/absolute/path/to/project-staging-logs/celeryd.log autostart=true autorestart=true startsecs=10 stopwaitsecs=600 What I tried Using different BROKER_URL for redis (/0 & /1), setting different CELERY_DEFAULT_QUEUE and CELERY_DEFAULT_ROUTING_KEY for each project, launching celery with or without supervisord. The problem Everything works fine when I use the supervisord command for … -
How to customize the "description" of the manytomany inline in the admin panel
I have those extremely simple models: class Activity(BaseModel): name = models.CharField(max_length=200, blank=True, null=True) class Person(BaseModel): activities = models.ManyToManyField('Activity', related_name='persons') In the admin.py I've made an inline for this and it works, like this: class PersonActivitiesInlineAdmin(admin.StackedInline): model = Profession.persons.through fk_name = 'person' class PersonAdmin(admin.ModelAdmin): inlines = (PersonActivitiesInlineAdmin, ) My problem is that the string describing the inline, in the admin interface, is like Profession: Person_activities object (831) Profession: Person_activities object (832) Profession: Person_activities object (835) Profession: Person_activities object (838) So how to customize the "description" of the manytomany inline in the admin panel? -
form is not valid to django why
the model: class authentifier(models.Model): matricule =models.CharField(max_length=254, blank=True, null=True) password = models.CharField(max_length=254, blank=True, null=True) nom =models.CharField(max_length=254, blank=True, null=True) prenom=models.CharField(max_length=254, blank=True, null=True) statut = models.CharField(max_length=254, blank=True, null=True) the code forms.py for authentification : from django import forms class UserLoginForm(forms.Form): print(666) matricule = forms.CharField(required=True , widget=forms.TextInput) password = forms.CharField(required=True , widget= forms.PasswordInput) template html : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width , initial- scales=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> </head> <body> <form> <form method="POST"> {% csrf_token %} <tr><th><label for="id_matricule">Matricule:</label></th><td><input type="text" name="matricule" id="Matricule"></td></tr> <tr><th><label for="id_password">Password:</label></th><td><input type="password" name="password" id="password"></td></tr> <input type="submit" value="Se Connecter"> </form> </body> </html> I found that form.is_valid() = false - but i have no idea how to get the reason WHY... i need to do authentification with matricule and password -
Django - dynamic form from Model with choices
I'm trying to implement dynamic form which displays a few option from database's choices. The form should display names of CASES (i.e. "Option 1") for given lawyer_id. For example: user selects lawyer with ID = 6 and this lawyer_id has "Option 1" and "Option 2" in LawyersSpec model. In the form I want to display only "Option 1" and "Option 2" as possible options. How can I achieve that? I have tried dynamic forms with overriding the queryset in init def __init__(self, *args, lawyer_id, **kwargs): super().__init__(*args, **kwargs) lawyer_spec = LawyersSpec.objects.filter(lawyer_id=lawyer_id) but it returns the whole name of the record from the database, not only the choice value. models.py class LawyersSpec(models.Model): lawyer_id = models.ForeignKey('MyUser', on_delete=models.PROTECT) lawyer_spec = models.SmallIntegerField(choices=CASES) CASES = ( (1, 'Option 1'), (2, 'Option 2'), (3, 'Option 3'), (4, 'Option 4'), ) -
VSCode debug Celery worker
After some frustrating days of running this, I'm needing to look at debugging a celery worker process in VSCode. This is following the suggested process in the Celery docs for creating a message handler, rather than pub/sub from the same application. The celery.py file: from __future__ import absolute_import, unicode_literals import os import json from celery import Celery, bootsteps from kombu import Consumer, Exchange, Queue dataFeedQueue = Queue('statistical_forecasting', Exchange('forecasting_event_bus', 'direct', durable=False), 'DataFeedUpdatedIntegrationEvent') # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') app = Celery('statistical_forecasting') app.config_from_object('django.conf:settings', namespace='CELERY') # Not required yet as handler is within this file #app.autodiscover_tasks() class DataFeedUpdatedHandler(bootsteps.ConsumerStep): def get_consumers(self, channel): return [Consumer(channel, queues=[dataFeedQueue], callbacks=[self.handle_message], accept=['json'])] def handle_message(self, body, message): event = json.loads(body) # removed for brevity, but at present echo's message content with print message.ack() app.steps['consumer'].add(DataFeedUpdatedHandler) My abbreviated project structure is: workspace - vscode - - launch.json config - __init__.py settings - local.py venv - celery.exe statistical_forecasting - __init__.py celery.py farms - __init__.py handlers.py # ultimately handler code should live here... From terminal with venv enable I'm running celery -A statistical_forecasting worker -l info which does appear to succeed in setting up and running the basic message handler. What I've tried thus far with VSCode … -
How to update ordering in a model
I have a model that sets the display order of books. I want users to be able to change the order books are displayed in, so I am not using book.id: class Books(models.Model): title = models.CharField(max_length=30) order = models.IntegerField(max_length=255, unique=True) This works ok, but say I have 3 books with order values 4, 5, 6 and I want to move the first book from position 4 to 5, pushing the second book from 5 to 4. If I try to do this in steps, then I trigger an error on changing the value of the first book to 5 because value 5 already exists for the second book (before it is changed to 4). How do I handle this use case? Is there some way to update records together, or a better way to handle ordering like this? -
Django how to display list users with some data in template
I want to display the list of users with some objects in 2 modelapps created. these are the models. first model: class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) indirizzo = models.CharField(max_length=50) citta = models.CharField(max_length=50) paese = models.CharField(max_length=50) ecap = models.CharField(max_length=4) descrizione = models.CharField(max_length=100, default='') image = models.ImageField(upload_to='profile_image', blank=True,null=True) second model: class Ore(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ore",null=True,) data = models.DateField(default=timezone.now) oret = models.CharField(max_length=3,) contrattiok = models.PositiveSmallIntegerField() contrattiko = models.PositiveSmallIntegerField(default=0,) nomecognome = models.CharField(max_length=100,blank=True) my view: def inizio(request): users = User.objects.all() return render (request, "base.html", {"users":users}) my template: {% for users in users %} <tbody> <tr> <td> <img src="{{ users.userprofile.image.url }}"class="thumbnail"> <h4 class="small font-weight-bold">{{users}}</h4> </td> <td><h4 class="small font-weight-bold">{{users.last_name}}</h4></td> <td class="text-center"> <h4 class="small font-weight-bold" class="btn btn-primary btn-circle">{{ users.ore.contrattiok }}</h4> <<<<<(does not work) </td> </tr> {% endfor %} -
How many Apps can i use in one Django Project
i have a Django Project which i'm working on. Now the Project gets bigger. I think there will be in the end approximately 40 Apps. I'm not sure if this is too much Apps for one Django project? Maybe one of you have some Experience with large Projects? Thank you -
How to update code in dist folder in pyarmor?
I deployed a project using Pyarmor. I took a reference from the below link https://pyarmor.readthedocs.io/en/latest/project.html#managing-obfuscated-scripts-with-project. It is working fine.But,if i do any changes in my script file i'm unable to update the code. How can i update the code?