Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Celery tasks repeated multiple times in production
I'm new to Celery, and I created a simple app that connects to a web socket server to receive tasks and schedule them using Celery. My Celery queue display tasks based on the type of the message (text messages first, and then buttons that run the next task if one of them is clicked). Locally, everything run as expected. But, some tasks are repeated multiple times in production, especially the triggers (buttons). In my production environment, I created a web service for Django and one Celery background worker with a Redis database. Here are the commands I used to run Celery worker and beat in production: # Start command (celery worker and beat) celery -A bot.celery worker --beat --scheduler django --loglevel=info --concurrency 4 # Start command (Django) daphne -b 0.0.0.0 bot.asgi:application My Django and Celery settings: CELERY_BROKER_URL = "redis://localhost:6379/0" # localhost replaced with the internal Redis URL in production CELERY_RESULT_BACKEND = "redis://localhost:6379/1" # localhost replaced with the internal Redis URL in production TIME_ZONE = 'UTC' CELERY_ENABLE_UTC = True CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' ASGI_APPLICATION = 'bot.asgi.application' Some of the worker output: Nov 1 09:00:15 AM [2022-11-01 08:00:15,178: INFO/MainProcess] missed heartbeat from celery@srv-cdcl4202i3msb94icl70-5469f7b9d8-gzks7 Nov … -
Django how to hyperlink to images in static folder by ticker symbol?
I have a table of ETF tickers, ETF names, and their Index names. I want each entry in the table to be clickable and linked to their associated images in the static/images folder. Each image is named after each ETF's index ticker. So when a user clicks on, for example, the first entry ETF ticker "PSCD" links to 'static/myapp/images/sample_regression_S6COND.jpg'. The substring in the link "S6COND" is the part I need as a relative link. Each ETF ticker has a different Index ticker. These Index tickers are in a model associated with the table. In my table.html page, when I hardcode the link to the static image <td><a href="{% static '/myapp/images/sample_regression_S6COND.jpg' %}" target="_blank">{{i.etf_ticker}}</a></td> (see how I typed "S6COND" into the link?), it works, but not when I try to turn it into a relative link {{i.index_ticker}} like <td><a href="{% static '/myapp/images/sample_regression_{{i.index_ticker}}.jpg' %}" target="_blank">{{i.etf_name}}</a></td>. My static files in correctly placed inside my app folder and includes images, css, and js folders. All images are inside the static/myapp/images folder. table.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ETF Table</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'myapp/css/table_style.css' %}"> <style type="text/css"></style> </head> <body> <div class="container"> <table id="table" class="table table-dark table-hover table-striped table-bordered … -
Django DateField returns error: str' object has no attribute 'day'
I'm not sure why I'm getting this error. I'm happy to provide add'l info! I've been working through a Django tutorial that makes articles for a blog. I've got the page up and the admin setup. When trying to add an article, the error is generated. In my model I have a DateField with auto_now_add=True. I would think that would pull the datetime, but it's returning the error on date.day. AttributeError at /admin/post/article/add/ 'str' object has no attribute 'day' Request Method: POST Request URL: http://xxx.x.x.x:8000/admin/post/article/add/ Django Version: 4.1.2 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'day' Exception Location: /Users/user/PycharmProjects/assembly_tracker/venv/lib/python3.10/site-packages/django/db/models/base.py, line 1338, in _perform_date_checks Raised during: django.contrib.admin.options.add_view Python Executable: /Users/user/PycharmProjects/assembly_tracker/venv/bin/python Python Version: 3.10.3 Python Path: ['/Users/user/PycharmProjects/assembly_tracker', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python310.zip', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/lib-dynload', '/Users/user/PycharmProjects/assembly_tracker/venv/lib/python3.10/site-packages'] Server time: Tue, 01 Nov 2022 19:37:30 +0000 The error is coming in on the following lines in _perform_date_checks when it hits date.day lookup_kwargs = {} # there's a ticket to add a date lookup, we can remove this special # case if that makes it's way in date = getattr(self, unique_for) if date is None: continue if lookup_type == "date": lookup_kwargs["%s__day" % unique_for] = date.day … lookup_kwargs["%s__month" % unique_for] = date.month lookup_kwargs["%s__year" % unique_for] = date.year else: … -
How to store list of tuples in django model
I am working on a food recipe database web app in Django 4 and want to store an unknown number of ingredients required for a recipe within a given model. The ingredient is described by a name, a volume, and a measuring unit - eg: Sugar 400 grams, Eggs 2 pieces, etc. I am using PostgreSQL What is the best practice to store such data within a given model while preserving the ability to query the data or do arithmetic operations on the volumes of the ingredients please? I have found two options so far, but since I am very new to web development, I do not know if they could work: Create a separate model for ingredient and use a many-to-many relationship to connect the models but this would create a new object for every instance that for instance volume is different Just use TextField() and then use some crazy Regex to separate the ingredients out Given that I am new to web development, I have no clue what is the most suitable option. Thanks -
Django unit tests. Post data with duplicate keys
I'm writing a Django unit test against an app I inherited. In the context of a unit test I am doing something like: data = {'foo':'bar','color':'blue'} self.client.post(url,data=data) However, the app expects muiltiple form data for "color" in the same key in the HTTP request, such as: foo: bar color: orange color: blue What's the best and most pythonic way to handle this? Is there a django class I should be using that already covers this? I obviously can't create a python dict with duplicate keys, so I am not sure what I should use to get the above desired HTTP POST. I can't change the underlying app, I'm interfacing with something that already exists! -
Need an explination to why a Form with method post is not callin the action correctly with django url tag?
While trying to create a simple search form using method="POST" and action linking to a url that should trigger a view to render a different template I have come across it not working all it does is tag on the csrf to my index url and acts like I am using GET not POST any thoughts on why? View: @login_required(login_url='login_register') def search_site(request): if request.method == "POST": searched = request.POST['searched'] context = { 'searched': searched } return render(request, 'bugs/search_site.html', context) else: return render(request, 'bugs/search_site.html') URL: path('search_site/', views.search_site, name='search_site'), Search bar template: <div class="input-group"> <form method="POST" action="{% url 'search_site' %}"> {% csrf_token %} <input class="form-control" type="search" placeholder="Search for..." aria-label="Search for..." name="searched"> <button class="btn btn-primary" type="submit"><i class="fas fa-search"></i></button> </form> </div> Search result template: {% extends 'bugs/base.html' %} {% block content %} <div class="container-fluid px-4"> {% if searched %} <h4 class="mt-4">results for {{ searched }}</h4> {% endif %} </div> {% endblock %} I have tried changing method to get, I have tried to change my url and my view to no avail. -
Django ManyToMany relationship on unioned queryset from different models
I'm unable to join ManyToMany relationship records using a serializer to a unioned queryset from different DB modals. I have two similar DB models, A and B both with a ManyToMany relationship with another model, Tag. from django.db import models class Tag(models.Model): name = models.CharField(max_length=100) class A(models.Model): name = models.CharField(max_length=100) tags = models.ManyToManyField(Tag) class B(models.Model): name = models.CharField(max_length=100) tags = models.ManyToManyField(Tag) I want to union A and B, and join the data from Tag via a Serializer. Here's my serializer: from rest_framework import serializers from union.models import A, B, Tag class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' class ABUnionSerializer(serializers.Serializer): name = serializers.CharField() tags = TagSerializer(many=True) When I create a queryset that unions A and B, then pass that to ABUnionSerializer, the serializer does not join the Tag data from B correctly. Example: from django.test import TestCase from union.models import A, B, Tag from union.serializers import ABUnionSerializer class UnionTestCase(TestCase): def test_union(self): ta = Tag.objects.create(name='t-a') tb = Tag.objects.create(name='t-b') a = A.objects.create(name='aaa') a.tags.add(ta) b = B.objects.create(name='bbb') b.tags.add(tb) u = A.objects.all().union(B.objects.all()) s = ABUnionSerializer(u, many=True) print(s.data) The Serializer attempts to use relationship table from A instead of B. In this example, this causes the serialized record "bbb" to have tag "t-a" … -
How do I set(repeatedly) a Foreign Key Model, on multiple fields in another Model ? + Django
Trying to build a Model -> Trip, with multiple Hotel entries per region -> denoted by variables _pb, _hv, _nl. class Trip(models.Model): hotel_pb = models.ForeignKey(Hotel, on_delete=models.PROTECT, blank=True) hotel_hv = models.ForeignKey(Hotel, on_delete=models.PROTECT, blank=True) hotel_nl = models.ForeignKey(Hotel, on_delete=models.PROTECT, blank=True) How do I achieve this without creating region specific Hotel models ? I have tried using the same Foreignkey, but throws error. -
Not able to configure any URLs in Django; going to localhost:8000 shows the congratulations page
As title - I've been going through the official tutorial (part 1) and have gotten to the point where we wire an index view into the URLConf. However, when I run python manage.py runserver I only see the "congratulations! the installation was successful!" page, not the HTTPResponse that's supposed to return. It says that I haven't configured urls, but there are like 3 steps to follow so far and I'm confused on how I managed to go wrong when copying some code into views.py and creating a urls.py file. Going to localhost:8000/polls gives me 404 not found error. I made sure to create urls.py within the "polls" directory (which in turn is within the project "mysite" directory); the `view.py My urls.py code is as follows: from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path(' ', views.index, name='index'), path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] My views.py code is as follows: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") When I do python manage.py runserver, I'm inside the mysite directory (that contains the polls and mysite apps' directories). I'm really not sure where I might be going wrong; any … -
Master - Detail - Child in Django
I am new to django, need suggestions/help, we have the following requirement, need to design html template/form using Bootstrap 5 etc.. This need to be a single page CRUD application. Is this possible in django? 1 Master Table 1 Detail Table Foreign Key References to Master Table 1 Child Table Foreign Key References to Detail Table if anybody tried this type of requirement, kindly help me by providing reference articles/documents/blogs to achieve this. We have similar two applications to build, we have done application based on single table only till now, but in the above requirement we have dependent tables this is where I got struck and need help. Tried single table forms/model/view architecture which are working fine. -
How to add permission for users who have staff status
I need something that only admins and staff could delete users. When I use this, only admins can do it, if I try to delete a user with staff status, I get an error 403, how i can fix it? ty.` class DriverDeleteView(LoginRequiredMixin, PermissionRequiredMixin, generic.DeleteView): model = Driver success_url = reverse_lazy("taxi:driver-list") permission_required = "taxi.delete-driver" ` i`m try add sum permission in admin panel, but its work only in admin page. -
How to you data from model as choices for another model
I would like to have the information entered into one model used as choices in the next model. #Model 1 will have staff information #Example: John - HSE class staff_information(models.Model): Name_of_staff =models.CharField(max_length=50) Designation =models.CharField(max_length=20) def __str__(self): return self.Name_of_staff #model 2 will contain information collected on a questionaire #example: Sex (Yes or No) class form_information(models.Model): Sex =models.CharField(max_length=50) Name_of_staff =models.ForeignKey("staff_information",on_delete=models.CASCADE) supervisor =models.ForeignKey("senior",on_delete=models.CASCADE) ``` #Model 3 will have staff information #Example: Dan class senior(models.Model): Name =models.CharField(max_length=50) def __str__(self): return self.Name #views def home(request): form = form_information() if request.method == 'POST': form = form_information(request.POST) print(request) if form.is_valid(): form.save() context = { 'form':form } return render(request, 'form/home.html', context) <form action="" method="post"> {% csrf_token %} #form What is your sex: {{form_information.sex}} Name of Staff: {{form_information.name_of_staff}} Supervisor: {{checklist_form.supervisor}} <button type="submit" value="Submit" class="btn btn-primary">Submit</button> </form> When I try to submit i get this IntegrityError at / NOT NULL constraint failed: Please help!! -
markdown2 not returning html object
I was working on a Django project and when I try to change a markdown file to HTML it doesn't return html file instead it returns <markdown2.Markdown object at 0x00000239F71FEB00> when I change detail.html to {{detail|safe}} it return nothing `def detail(request, title): contents = util.get_entry(title) if contents == None: return render(request, "encyclopedia/error.html",) content_converted = Markdown(contents) print(content_converted) return render(request, "encyclopedia/detail.html", {'detail': content_converted, 'title': title})` detail.html {% extends "encyclopedia/layout.html" %} {% block title %} {{title}} {% endblock%} {% block body %} <h1>{{detail}}</h1> <a class="btn btn-info" href="{% url 'edit' title%}">Edit</a> {% endblock %} I tried to change a markdown element to html content using markdown2 in django project but the converter is returning unexpected outcome -
Django - Sitemap Reverse URL with parameters from list
I'm looking at creating a sitemap based on a list of parameters, but seem to be running into issues. I can get it to work with a single parameter, but not iterate over a list of parameters. Here is the working code, for a single parameter: class FinancialViewSitemap(sitemaps.Sitemap): changefreq = 'weekly' priority = 0.8 def items(self): return ['financials:annuals', 'financials:keymetrics', 'financials:quarterly','financials:peratio'] def location(self, item): return reverse(item, kwargs={'ticker': 'AAPL'}) and here is my attempt at iterating over a list, which does not work: class FinancialViewSitemap(sitemaps.Sitemap): changefreq = 'weekly' priority = 0.8 tickers = ["AAPL", "GOOG", "META"] for ticker in tickers: def items(self): return ['financials:annuals', 'financials:keymetrics', 'financials:quarterly','financials:peratio'] def location(self, item, tickers=tickers, ticker = ticker): return reverse(item, kwargs={'ticker': ticker}) -
how to pass temporary decrypted data to django template
I have an application that can upload files in every format I want to be encrypted and saved to database I also created decrypt functionality but I dont know how to show this decrypted file to the user or django templates. i have tried many ways like TemFile library but still I cant pass my decrypted data to the templates here is my code for encryption def encrypt (request): if request.method == 'POST': upload_file = request.FILES.get("like") # key generation key = Fernet.generate_key() encode_key = urlsafe_base64_encode(force_bytes(key)) print(encode_key) document = FileEncrypt.objects.create(document = upload_file,key=encode_key) # using the generated key fernet = Fernet(key) # opening the original file to encrypt with open(document.document.path, 'rb') as file: original = file.read() # encrypting the file encrypted = fernet.encrypt(original) with open(document.document.path, 'wb') as encrypted_file: encrypted_file.write(encrypted) document.save() return redirect("decrypt_and_show", id=document.id) else: return render(request,"index.html",{ }) after redirecting to decrypt page it's not showing the file here is my decrypt def def decrypt(request,id): document = FileEncrypt.objects.get(pk=id) decode_key =force_text(urlsafe_base64_decode(document.key)) print(decode_key) fernet = Fernet(decode_key) # opening the encrypted file with open(document.document.path, 'rb') as enc_file: encrypted = enc_file.read() # decrypting the file decrypted = fernet.decrypt(encrypted) tmpfile = tempfile.NamedTemporaryFile(delete=False,suffix='.JPEG') tmpfile.seek(0) tmpfile.write(decrypted) return render(request,"index2.html",{ "d" : tmpfile.name }) in my template is {% load static %} … -
How to group_by Queryset distinct by id and append values Django
In Django i have the results i want but it returns separated data in same ids How to groupby ids in a list of dicts? Use pandas to fix this, but it doesn't work quite right. What I need is a simple dictionary list where if there is a repeated id, the information that is different is added as the value of that key and if there are several values, it is stored in a list. So as I show below in the result I want i have this: < QuerySet[{ 'id': 7086098, 'action_plan': None, 'comment': None }, { 'id': 7105838, 'action_plan': 'foo', 'comment': None }, { 'id': 7105838, 'action_plan': 'foos2', 'comment': None }, { 'id': 7169339, 'action_plan': 'xxxxxx', 'comment': None }, { 'id': 7169346, 'action_plan': 'report', 'comment': None }, { 'id': 7169346, 'action_plan': 'zxczxczxczc', 'comment': None }, { 'id': 7622793, 'action_plan': 'foofoo', 'comment': None }, { 'id': 7622793, 'action_plan': 'role play', 'comment': None }, { 'id': 7723661, 'action_plan': 'google', 'comment': 'chrome' }, { 'id': 7723661, 'action_plan': 'netscape', 'comment': None }, { 'id': 7723661, 'action_plan': 'urra', 'comment': 'firefox' }, { 'id': 7723661, 'action_plan': 'sdasd', 'comment': None }] > i want to get this: [{ 'id': 7086098, 'action_plan': None, 'comment': None … -
How to remove error messages when form is successfully submitted in Django?
I made a Django form. If the user tries to submit the form when entering wrong data then error is showed in the form and it is not submitted but when the user enters correct data and submit the form it gets submitted. The problem is that when the user presses the back button, he can still see that error in the form. The error message still stays. What can I do about it? The below screenshots will help you understand my problem. In the above image I have entered the number of rooms as 0. As expected, I got an error. So I changed the number of rooms to 1. Now when I pressed the 'search availability' button I got the desired page. The problem arises if I press the browser back button. As you can see the error is still shown in the form. forms.py class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ['check_in_date', 'check_in_time', 'check_out_time', 'person', 'no_of_rooms'] widgets = { 'check_in_date': FutureDateInput(), 'check_in_time': TimeInput(), 'check_out_time': TimeInput(), } """Function to ensure that booking is done for future and check out is after check in""" def clean(self): cleaned_data = super().clean() normal_book_date = cleaned_data.get("check_in_date") normal_check_in = cleaned_data.get("check_in_time") normal_check_out_time = … -
Django WebSocket not working inside a container but works outside of it
I am trying to do a connection to a websocket from a html page in django. This works when i run it outside a container but it stops working inside of it . My server inside my docker compose. server: stdin_open: true # docker run -i tty: true # docker run -t build: dockerfile: server.Dockerfile context: ./ volumes: - /home/$USER/.ssh:/root/.ssh ports: - '8000:8000' networks: drone_net: ipv4_address: 10.10.10.2 the url I use in my html page let url = `ws://localhost:8000/ws/socket-server/` The error i get: WebSocket connection to 'ws://localhost:8000/ws/socket-server/' failed: This is my routing for the websocket : websocket_urlpatterns=[ re_path(r'ws/socket-server/',consumers.ChatConsumer.as_asgi()) ] I first thought it was localhost not working but my http request works in the containe as well. I tried to change the value of the url with different ones. I thought it was localhost that wasnt working properly but i also use local host for http request and they were fine in the container. I was expecting it to work. -
Cannot assign "1": "Refund.order" must be a "Order" instance
So, this here is a dirty production-level code, and I am stuck at this. I am designing a Return API but I am not good at this, help is much appreciated. views.py: class RefundViewSet(ModelViewSet): http_method_names = ['get', 'post', 'delete', 'head', 'options'] def get_permissions(self): if self.request.method == 'POST': return [IsAdminUser()] return [IsAuthenticated()] def create(self, request, *args, **kwargs): serializer = RefundOrderSerializer( data=request.data, context={'user_id': self.request.user.id}) serializer.is_valid(raise_exception=True) order = serializer.save() serializer = OrderSerializer(order) return Response(serializer.data) def get_serializer_class(self): if self.request.method == 'POST': return RefundOrderSerializer return OrderSerializer def get_queryset(self): user = self.request.user if user.is_staff: return Order.objects.all() customer_id = Customer.objects.only('id').get(user_id=user.id) return Order.objects.filter(customer_id=customer_id) I don't think this part has any problems. serializers.py: class RefundOrderSerializer(serializers.Serializer): order_id = serializers.IntegerField() ###validator methods to ensure that only a customer with an order can request a refund.### def validated_order_id(self, order_id): if not Order.objects.filter(pk=order_id).exist(): raise serializers.ValidationError('No order with given id was found.') return order_id def save(self, **kwargs): with transaction.atomic(): order_id = self.validated_data['order_id'] message = serializers.CharField(max_length=500) email = serializers.EmailField() refund = Refund() refund.order = order_id refund.reason = message refund.email = email refund.save() return refund This is the Problem Part models.py: class Customer(models.Model): MEMBERSHIP_BRONZE = 'B' MEMBERSHIP_SILVER = 'S' MEMBERSHIP_GOLD = 'G' MEMBERSHIP_DIAMOND = 'D' MEMBERSHIP_CHOICES = [ (MEMBERSHIP_BRONZE, 'BRONZE'), (MEMBERSHIP_SILVER, 'SILVER'), (MEMBERSHIP_GOLD, 'GOLD'), (MEMBERSHIP_DIAMOND, 'DIAMOND') … -
Django Unit Testing - How to load once a DB for multiple tests.py files?
I have a folder named "test" in my Django project. Inside this folder I have multiple files named "test_xyz.py". My goal: loading the DB only once and share it across all test*.py files. What I currently do: class OneTestCase(APITestCase): @classmethod def setUpTestData(cls): ''' Init database ''' from myapp.init import init_my_db # a python script loading the db class TwoTestCase(APITestCase): @classmethod def setUpTestData(cls): ''' Init database ''' from myapp.init import init_my_db # a python script loading the db # same goes for each test*.py file... In other words I am reloading the database from scratch for each test*.py file slowing down the testing execution time. Is there a way to avoid this, loading the database only one time and for all the test*.py files? -
HTMX not triggering correct query on pickadate.js selection
I use django-forms-dynamic package and htmx to dynamically load available options on a MultipleChoiceField. The options are based on a date field, for which I use pickadate.js by Amsul. The initial query gets the correct choices from the database. However, if the date is changed, the query is lagging one step behind. So, let's asume 1.11.2022 is initially selected. If changed to 4.11.2022, the query is made for the 1.11.2022. If 28.11.2022 is selected, 1.11.2022 is queried, etc. reservation_form.html <div class="col-lg-6"> <div class="form-floating"> {% render_field reservation_form.date class="datepicker form-control mb-3" hx-get="/reservation/filter-seats" hx-include="#id_dinner" hx-trigger="click change" hx-target="#id_seat_reservation" %} <label for="id_date">Dinner Date</label> </div> <div class="form-floating"> {% render_field reservation_form.amount_guests class+="form-control" placeholder="" %} <label for="id_amount_guests">Guests</label> </div> <div class="visually-hidden"> {% render_field reservation_form.dinner %} </div> <div class="form-check"> {% render_field reservation_form.seat_reservation class+="form-select" %} <label for="id_seat_reservation">Select Seats</label> </div> </div> pickadate script <script> var $input = $('.datepicker').pickadate({ format: 'yyyy-mm-dd', formatSubmit: 'yyyy-mm-dd', min: 0, max: 90, disable: {{ blocked_dates }}, firstDay: 1, }) var picker = $input.pickadate('picker') </script> What am I missing? -
inactive page after signin to social media on django allauth
Iam trying to develope a website that use socail media for authentication based on google and facebook. I used django-allauth library for it. but I have problem with this when user create account or signin via google. after successfully signin return inactive page. I want to redirect to my home page there is my custom model there is my custome models class Account(AbstractBaseUser): USERNAME_FIELD = "email" first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=100, unique=True) username = models.CharField(max_length=100, unique=True) profile_pic = models.ImageField( null=True, upload_to=image_path_generator, blank=True ) total_storage = models.FloatField( default=20, validators=[MinValueValidator(0.0), MaxValueValidator(20.0)] ) used_storage = models.FloatField( default=0, validators=[MinValueValidator(0.0), MaxValueValidator(20.0)] ) phone_no = models.IntegerField(default=0) user_key = models.CharField(max_length=100, blank=True, null=True) joined_date = models.DateTimeField(default=timezone.now) two_auth = models.CharField( choices=twoAuth_choices, max_length=20, default=twoAuth_choices[1][1] ) files = models.ManyToManyField( "fileuploads.NewFile", related_name="file_owner", ) folders = models.ManyToManyField( "folders.Folder", related_name="folder_owner", ) # required date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) REQUIRED_FIELDS = ["username", "first_name", "last_name"] objects = AccountManager() i have also setup my settings.py to like this # SOCIAL CONNECTION SITE_ID = 1 SOCIALACCOUNT_LOGIN_ON_GET = True ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = "none" LOGIN_REDIRECT_URL = "/" LOGOUT_REDIRECT_URL = logout_url could you please help me … -
Django third party data migrations how to?
I am trying to migrate data from a node.js app to my django app, luckily they both use postgresql but I don't know how the access the node.js database and get the model, I have entered the second database in my settings.py but .get_model() cant take database name as an attribute only app name and model name, and since the app is in node.js I am running in a problem before even starting, is there a way to get the model directly from the node.js side database and what is the syntax ? this is my code so far: class Migration(migrations.Migration): def migrate_items(self, schema_editor): old_item_model = self.get_model("inventory", "Item") # THIS NEEDS TO COME FROM THE NODE.JS SIDE DATABASE. items = old_item_model.objects.using('inventory').all() print(items) def reverse_migrate_items(self, schema_editor): pass dependencies = [ ('items', '0022_merge_0020_alter_history_event_0021_alter_assign_item'), ] operations = [migrations.RunPython(migrate_items, reverse_code=reverse_migrate_items) ] Thanks. -
Error 405 when calling POST in my react native app
After installing SSL certificate to the backend web server (NGINX) of my React Native app, I started encountering Error 405 every time I use the POST method. I've tried multiple solutions offered online, like adding the following line to my NGINX config, but nothing seems to work. error_page 405 =200 $uri; I've attached my NGINX configuration below, # Upstreams upstream wsgiserver { ip_hash; server thebackend:80; } # Redirect to HTTPS server { listen 80; listen [::]:80; server_name thebackend.com; access_log /var/log/nginx/thebackend-access.log; error_log /var/log/nginx/thebackend-error.log; return 301 https://thebackend.com$request_uri; } # HTTPS server server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name thebackend.com; access_log /var/log/nginx/thebackend.com.log; error_log /var/log/nginx/thebackend.com.log; ssl on; ssl_certificate /etc/ssl/thebackend/thebackend.com_bundle.crt; ssl_certificate_key /etc/ssl/thebackend/thebackend.com.key; ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; #ssl_dhparam /etc/ssl/certs/dhparam.pem; ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH'; ssl_prefer_server_ciphers on; ssl_session_cache shared:SSL:10m; # WSGI server location / { proxy_pass https://wsgiserver/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-NginX-Proxy true; proxy_set_header Access-Control-Allow-Credentials true; proxy_set_header Content-Encoding gzip; proxy_set_header Host $http_host; proxy_set_header Cookie $http_cookie; proxy_set_header Upgrade $http_upgrade; proxy_pass_header X-CSRFToken; proxy_ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; proxy_ssl_server_name on; proxy_read_timeout 5m; proxy_redirect default; error_page 405 =200 $uri; } } Did I miss something? Any suggestions would be greatly appreciated. -
Skip FIleNotFoundError in django templates
I encountered the following error in the template. How can skip this error. My code: {% if obj.profile_pictures %} <img src="{{ obj.profile_pictures.url }}" > {% else %} <img src="{% static 'assets/img/alt_img.jpg' %}""> {% endif %}