Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
502 Bad Gateway : gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
I was trying to deploy a Django app on aws using postgres, gunicorn and nginx After the initial setup, I added the Django app from a git repository after that I am getting a 502 Bad Gateway Here is the gunicorn status ubuntu@ip-172-31-4-106:~/myproject$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Thu 2021-01-07 01:08:56 UTC; 2h 25min ago TriggeredBy: ● gunicorn.socket Process: 54260 ExecStart=/home/ubuntu/myproject/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind uni> Main PID: 54260 (code=exited, status=1/FAILURE) Here is the nginx error log: Jan 07 01:08:56 ip-172-31-4-106 gunicorn[54260]: File "/home/ubuntu/myproject/myprojectenv/lib/python3.8/site-package>Jan 07 01:08:56 ip-172-31-4-106 gunicorn[54260]: self.reap_workers() Jan 07 01:08:56 ip-172-31-4-106 gunicorn[54260]: File "/home/ubuntu/myproject/myprojectenv/lib/python3.8/site-package>Jan 07 01:08:56 ip-172-31-4-106 gunicorn[54260]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Jan 07 01:08:56 ip-172-31-4-106 gunicorn[54260]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Jan 07 01:08:56 ip-172-31-4-106 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Jan 07 01:08:56 ip-172-31-4-106 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jan 07 01:08:56 ip-172-31-4-106 systemd[1]: gunicorn.service: Start request repeated too quickly. Jan 07 01:08:56 ip-172-31-4-106 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jan 07 01:08:56 ip-172-31-4-106 systemd[1]: Failed to start gunicorn daemon. Couldn't find any solution for this problem please help -
Why is docker-compose creating files with a root owner and how can I modify the docker-compose.yml file to stop it?
I am building a Django app to run using Docker. In the docker-compose.yml file, I am using volumes to save changes. services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 When I create a new application within the Django project, I use... docker-compose exec web python manage.py startapp app_name Docker-compose writes the app (app_name) to my local file, as expected, but with a root owner. This is causing problems, because, if I want to then create a new file within the app, I don't have permission. If I exit docker-compose and create the app as a user, then there are no issues. How can I change the .yml file to fix this? -
How to check if the email id is private in django?
I want to give a validation in django for email ids, If a user enters a email from free email service provider then a validation error must popup that "This is not a business email id".. Only User having private email ids or business email ids can be eligible. How can this be possible using Django python version : 3.7.9 django version : 2.2.3 -
FAILED SQL: ('ALTER TABLE "app_employee" ADD COLUMN "industry_id" int NULL',)
I am working on a project in Django with mongoDB. my app's name is app. my models.py: class myCustomeUser(AbstractUser): #id = models.AutoField(primary_key=True) username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Employee = models.BooleanField(default=False) is_Inspector = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) def __str__(self): return self.username class Industry(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user') name = models.CharField(max_length=200, blank=True) owner = models.CharField(max_length=200, blank=True) license = models.IntegerField(null=True, unique=True) industry_extrafield = models.TextField(blank=True) def __str__(self): return self.name class Employee(models.Model): user = models.ForeignKey(myCustomeUser, null=True, blank=True, on_delete=models.CASCADE) industry = models.ForeignKey(Industry, null=True, blank=True, on_delete=models.CASCADE) i_id = models.IntegerField(unique=True) name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) rank = models.CharField(max_length=20, blank=False, null=True) employee_varified = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.name class Inspector(models.Model): user = models.ForeignKey(myCustomeUser, on_delete=models.CASCADE, related_name='inspector_releted_user') name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) nationalid = models.IntegerField(null=True, blank=False, unique=True) inspector_extrafield = models.TextField(blank=True) def __str__(self): return self.name class Admin(models.Model): user = models.ForeignKey(myCustomeUser, on_delete=models.CASCADE, related_name='admin_releted_user') name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) admin_extrafield = models.TextField(blank=True) def __str__(self): return self.name class PrevJob(models.Model): employee = models.ForeignKey(Employee, null=True, blank=True, on_delete=models.CASCADE) industry = models.ForeignKey(Industry, null=True, blank=True, on_delete=models.CASCADE) i_id = models.IntegerField(unique=True) #name = models.CharField(max_length=200, blank=False, null=True) rank = models.CharField(max_length=20, blank=False, null=True) def __str__(self): return self.employee.name in … -
Django - How to differentiate between users in the database?
I'm building a Django server for my company and I'm still unfamiliar with some processes. I'm sure this is super simple, I'm just completely unaware of how this works. How do I differentiate between user's data so it doesn't get mixed up? If Jill is a user and she requests a page of her profile data, how do I not send her Jack's profile data, especially if there are multiple models invovled? For example, the code in the view would look like this: def display_profile(request) profile = Profile.objects.get(???) # What do I put in here? I understand that I can do: def display_profile(request, user) profile = Profile.objects.get(user_id=user) But that's not my design intention. Thank you in advance. -
GeoDjango OpenLayers.js don't display correct
I have Problem with Open Layers here it and it display correctly when i remove Jet Admin but it's OK ... now it happen in my frontend like the oic bellow -
How to change rest-framework form format in django?
My Application is working. but As in the photo below, I have not been able to change the date form format provided by django-rest-framework. show Image how to change date format?? -
Django Querying chained Foreign Key
Hello I am learning Django ORM queries and come to figure out reverse relationship in Foreign Key. I cannot visualize _set in foreign key field hope I will be cleared here. Here are my model I have been working. class Location(BaseModel): name = models.CharField( max_length=50, validators=[validate_location_name], unique=True, ) I have Route model linked with Location as FK: class Route(BaseModel): departure = models.ForeignKey( Location, on_delete=models.PROTECT, related_name='route_departure' ) destination = models.ForeignKey( Location, on_delete=models.PROTECT, related_name='route_destination' ) Similarly I have Bus Company Route linked Foreign key with Route class BusCompanyRoute(BaseModel): route = models.ForeignKey(Route, on_delete=models.PROTECT) Finally I have Schedule Model linked with BusCompanyRoute as Fk class Schedule(BaseModel): bus_company_route = models.ForeignKey(BusCompanyRoute, on_delete=models.PROTECT) Problem is I want to query from views being on Schedule model want to link with departure and destination how will I do that? I have only done this so far on view.py schedule = Schedule.objects.all() I am stuck on querying Chained foreign key -
No name 'DjangoWhiteNoise' in module 'whitenoise.django' Error
I'm currently in the process of deploying my django app to Heroku, and the walkthrough I'm following is having me add the following code to my wsgi file. Only issue is that I'm getting an error that No name 'DjangoWhiteNoise' in module 'whitenoise.django' I have whitenoise 5.1.0 installed, but can't figure out how to install whitenoise.django or what the issue is. Any ideas? wsgi.py from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(application) -
Manipulate bokeh plot using javascript
I have a long plot which the user is supposed to be able to pan in the x direction, but I want to add buttons to position the user in an specific region of the plot. How can I do this? I guess using javascript but I have no idea how to manipulate an already rendered bokeh plot. -
Django best practice for views.py files?
Large companies obviously have huge request loads and tons of information to render, so where in a Django project does that information get processed? Does it happen in the views.py file? A separate .py file that's called by the views.py file? I'm asking because my views.py files become thousands of lines long very quickly... does this matter or am I missing something here? I have a couple of views in my project that processes a lot of data from the database, what is the best practice for where to put the code? -
Django Model @property To Check if One User is a Subscriber / Follower Of Another User
I have a simple Subscriber model: class Subscriber(models.Model): """ User.subscribers.all() - all my subscribers User.subscriptions.all() - all the users I am subscribed to """ user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='subscribers') subscriber = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='subscriptions') created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.subscriber.username In a template, I want to be able to write: {% if user.is_subscribed %} where user could be any authenticated (logged-in) user. Is it possible to add a @property method to either this Subscriber model or the User model? OR Is it best to put this logic in the the view and passed to the template through context? End-goal: check if the user making the request is subscribed to another user and return True or False. -
Posts list page, Django Wagtail
I am making a news site, there is a page where all articles are displayed. But if there are many articles, then the page will be huge. my code : {% block content %} <div class=" container" style="margin-top: 60px;"> {% for post in posts %} <div class="row" style="padding-top: 30px "> <div class="col-sm-3"> {% image post.preview_image fill-250x250 as blog_img %} <img style="border-radius: .3525rem" href="{{ post.url }}" src="{{ blog_img.url }}"> </div> <div class="col-sm-9"> <a href="{{ post.url }}"> {{ post.title }} </a> <br/> <p> {{ post.intro }}</p> </div> </div> {% endfor %} </div> {% endblock content %} what i want to do -
Heroku Push Failing Module dj_database_url Not Found
I am trying to push my simple Django app onto Heroku (using Windows) and I am running into an error related to dj_database_url. It says that the module is not found, but I do have everything installed and confirmed through pip. Any ideas why this isnt working? requirements.txt Django>=2.2.13,<3.0 dj-database-url==0.5.0 gunicorn>=20.0.4 whitenoise>=5.1.0 error: -----> Python app detected -----> Installing python-3.6.12 -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip Collecting Django<3.0,>=2.2.13 Downloading Django-2.2.17-py3-none-any.whl (7.5 MB) Collecting sqlparse>=0.2.2 Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB) Collecting pytz Downloading pytz-2020.5-py2.py3-none-any.whl (510 kB) Installing collected packages: sqlparse, pytz, Django Successfully installed Django-2.2.17 pytz-2020.5 sqlparse-0.4.1 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 204, in fetch_command app_name = commands[subcommand] KeyError: 'collectstatic' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 211, in fetch_command settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in … -
Django Crontab not writing csv file
I am trying to run some jobs in django-crontab. They have been added successfully. Here is the code snippet. CRONJOBS = [ ('0 0 * * *', 'landingpage.my_crons.get_users','>> /home/root_user/scheduled_job.log'), ('0 0 * * *', 'landingpage.my_crons.data_collector'), ] crons appear when i do crontab show 8e70613793052f5793f86106c92994fe -> ('0 0 * * *', 'landingpage.my_crons.get_users', '>> /home/root_user/scheduled_job.log') d72fb010328cdc02e4b984fdc5f7db05 -> ('0 0 * * *', 'landingpage.my_crons.data_collector') when I run these using hashes they run fine and write files fine but when they run as scheduled they don't write files Even though it is empty but log file is being generated which means jobs are running but they are unable to write files that are being generated by script. Files are csv files based on bigquery data -
Django Heroku Commit Failure at Requirements
I am receiving the following error when I try and deploy my new app to Heroku. It looks like it's failing when it tries to install all of my requirements.txt line items, specifically at PyAudio which I am not using in my app at all. My requirements file was generated using pip freeze > requirements.txt which has 155 line items (seems way high for my simple app). Is this what's causing the issue? -----> Python app detected -----> Installing python-3.6.12 -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip ERROR: PyAudio-0.2.11-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. ! Push rejected, failed to compile Python app. ! Push failed -
How to pass arguments to QueryDicts and consecutively pass it to a django form to be used inside it
Description: I'm playing with django forms to fill in Completed_Exercise Model instances for those users that have completed successfully a determined exercise by use of ModelForm class, but since a Completed_ExerciseForm has three fields, two of which correspond to ForeignKey fields, i dont need to render them on template but the score one (hilariously user can do self-qualification), so the thing is i decided to pass both of them as arguments to ModelForm instance through a request.GET copy. I googled for an hour and tried & corrected stuff... but even so im making the same mistake, as far as i know this can be done likewise by passing them as kwargs to the form, but its not the intended way. Any help is really appreciated. Result: I cant access to QueryDict from inside of the form Models: class Completed_Exercise(models.Model): possible_scores = list(zip(range(1,8), range(1,8))) exercise = models.OneToOneField(Exercise, default=None, on_delete=models.CASCADE) points = models.IntegerField(default=0, choices=possible_scores) student = models.ForeignKey('accounts.Student', on_delete = models.CASCADE, related_name='completed_exercises') def __str__(self): return self.name #Student belongs to other django app, despite its placed alongside the first one. class Student(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE, related_name="student") pui = models.CharField(max_length=20, blank=True, default='') grade = models.CharField(max_length=1, blank=True, default='') score = models.IntegerField(default=0) reputation = models.IntegerField(default=0) … -
Trouble using letsencrypt with Django, Heroku, and Google Domains
I'm having trouble setting up my custom domain. I'm learning all this for the first time so there's a lot of confusion right now. Right now I can load my site at the custom domain, but none of the forms work. I think that's because it's HTTP right now, so I'm trying to get SSL. I'm using Heroku's free tier at the moment, so I can't use Heroku's SSL. I'm trying to get SSL using letsencrypt and I get this error running "certbot certonly --standalone": Detail: Invalid response from http://www.example.com/.well-known/acme-challenge/PIA0KiB2f7I5qVssgGY_3dbMuOgdlu0URheGUqbal0Y [34.196.106.64]: My settings.py DEBUG = False SECURE_SSL_REDIRECT = False if DEBUG: SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False else: SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True Finally, I'm not sure if I set up DNS correctly, so here's what I have right now: A synthetic record with subdomain @.example.com -> www.example.com, Temporary redirect, Do not forward path, Disable SSL A custom resource record with Name: www, Type: CNAME, TTL: 1hr, Data: DNS Target from heroku -
django , Not Found The requested resource was not found on this server
I'm using django 3.1.4 keep having problem "Not Found The requested resource was not found on this server" when try to open the orders details in orders.html I'm use <td><a href="{{ order.get_absolute_url }}" class="btn btn-primary d-inline">Details</a></td> in the urls.py using from django.urls import path from . import views from .models import OrderStatus path('market/orders/', views.VendorOrders.as_view(), name='market_orders'), path('orders/<int:pk>/', views.OrderDetail.as_view(), name='order_detail'), -
Django DetailView + Delete Item from Ajax Form
So here is my issue. The user can create a Client using a form. Once created, the created client appears in a DetaiLView In this DetailView, I put a form to add specific events related to the client, thanks to an ajaxified form so that new events appear without refreshing the page. So far everything is okay. Now I would like to allow the user to delete one event if he wants to. So I have done the HTML/AJAX parts. However, since it is a DetaiLView, I am having troubles to delete a specific event. Here is my Views.py : class CollectionDetail(LoginRequiredMixin, FormMixin, DetailView): model = Collection form_class = ImportantFactsForm template_name = 'taskflow/collection_detail.html' success_url = None def get_context_data(self, **kwargs): context = super(CollectionDetail, self).get_context_data(**kwargs) context['important_facts'] = ImportantFactsForm() return context def post(self, request, *args, **kwargs): form = ImportantFactsForm(request.POST) tgt = self.get_object() if form.is_valid(): new_fact = form.save(commit=False) new_fact.collection_important_facts = tgt new_fact.save() return JsonResponse({'new_fact': model_to_dict(new_fact)}, status=200) else: return redirect('taskflow:collection_all') #here I need to implement the delete function. Here is my collection_detail.html <div class="card-body"> <div class="tab-content"> <div class="tab-pane active" id="Canal1"> <form class="justify-content-center mx-3" id="createFactForm" method="post" data-url="{% url 'taskflow:collection_detail' pk=object.pk %}"> {% csrf_token %} <div class="form-group"> {{important_facts.doc_ref|as_crispy_field}} </div> <div class="form-group"> {{important_facts.note|as_crispy_field}} </div> <button type="submit" class="btn btn-outline-success" … -
How to modify computed queryset values ? (Reversed many - to - one relationship)
class Style(Model): id .... name .... class Song(Model): ... style = ForgeignKey(Style, related_name="songs") queryset = Style.objects.all() queryset[0].songs = queryset[0].songs.filter(something=1) #or queryset[0].songs.set(queryset[0].songs.filter(something=1)) This is my actual code, but it does not work except for filtering... I would like to assigned queryset.songs new filtered songs... or is there another way how to efficiently filter in this case ? -
Hi everyone! Where in pycharm do i need to paste this code.... {"python.linting.pylintArgs": [ "--load-plugins=pylint_django" ],}
** I know that in VS it's muck easy but i'm new to coding and i like pycharm. Please help! ** File "/Users/alexe/PycharmProjects/pythonProject1/btre_project/listings/views.py", line 3, in <module> from .models import listing ImportError: attempted relative import with no known parent package ``` -
Django: Select a valid choice. That choice is not one of the available choices
I have a nested choice field: The top one is used to select a smartphone brand and the bottom one is used to select a smartphone model of the said brand. The problem I face is such that when restricting the bottom choice using AJAX, my form is invalid. However, the POST request with and without restriction are exactly the same: No restriction: {'name': 'Ok iPhone 12 Mini', 'price': Decimal('345'), 'color': <Color: Red>, 'condition': <Condition: Refurbished by manufacturer>, 'storage': <StorageChoice: 128>, 'phone_model': <PhoneModel: iPhone 12 Mini>, 'description': '...', 'image': <InMemoryUploadedFile: pic.jpg (image/jpeg)>} With restriction: {'name': 'Ok iPhone 12 Mini', 'price': Decimal('345'), 'color': <Color: Red>, 'condition': <Condition: Refurbished by manufacturer>, 'storage': <StorageChoice: 128>, 'description': '...', 'image': <InMemoryUploadedFile: pic.jpg (image/jpeg)>, 'phone_model': <PhoneModel: iPhone 12 Mini>} The only difference I can see is order, which should not matter in the case of a dictionary. views.py: def product_add(request): form = AddProductForm() if request.method == "POST": form = AddProductForm(request.POST, request.FILES) form.is_valid() form.cleaned_data['phone_model'] = PhoneModel.objects.get(id=request.POST['phone_model']) form.cleaned_data.pop('make', None) print(form.cleaned_data) if form.is_valid(): form.cleaned_data['seller'] = request.user.customer Product.objects.create(**form.cleaned_data) else: print(form.errors) cart = get_cart(request) context = {'form': form, **cart} return render(request, 'store/product_add.html', context) def load_models(request): make_id = request.GET.get('make') models = PhoneModel.objects.filter(phone_make=make_id) return render(request, 'part/product_add_model_options.html', {'models': models}) forms.py: class AddProductForm(forms.ModelForm): class Meta: … -
Removing username from UserCreationForm and auto generating username for user based on email, first name and last name
I am trying to auto generate username for users as they sign up, however, I do not know where to set the username. I do not want to user signals, so therefore I want to set the username for users when the user signs up. In my UserCreationForm I have remove the username by: users = None and inside the SingUpForm(UserCreationForm) method I have: class SignUpForm(UserCreationForm): class Meta: fields = ( "first_name", "last_name", "email", ) However, I do not know how to set the username for the user, should I set the username for user inside the signup view? user = form.save(commit=False) user.username = generate_username(user.first_name, user.last_name, user.email) user.save() Or should I have the generate_username() method inside my custom creation form? -
How to know which users have seen certain post
I'm developing a Django web app in which I need to know which users have seen certain posts, I'd like to do this by adding a 'seen_by' field in the Post model, but I really don't know if it's possible to do it that way. The only way I can think of doing this is by making a function in which if an user visits an object, somehow send information to this object that the user visited it. Obviously I'm relatively new to programming in Django, I don't know if this can be done through signals or how, but I'd very much appreciate any help or advice specifically for this issue!