Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Twillio SMS not getting sent from Django python project
Twilio SMS not getting sent from Django python project I attempted to replicate the steps in blow article and send SMS using Twilio API https://www.twilio.com/blog/broadcast-sms-text-messages-python-3-django I keep geting HTTP/1.1" 401 16 printed to the console see my view method below from rest_framework.decorators import api_view, renderer_classes from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer from django.conf import settings from django.http import HttpResponse from twilio.rest import Client @api_view(('POST',)) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def SendPhoneCodeView(request): print('phone is') phone = request.data.get('phone') print(phone) message_to_broadcast = ("This is Me Testing the incredible Twilio SMS " "Not received yet? Wait for A Moment") client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) client.messages.create(to=phone, from_=settings.TWILIO_NUMBER, body=message_to_broadcast) return HttpResponse("messages sent!", 200) Also, all the print statements are NOT getting printed to console Can someone please advise me on what exactly I am doing wrong and how to resolve this Thanks -
how to depend on two fields to make a dropdown depend list django ajax
i'm trying to make an app for insert locations for a specific purpose , these my models : class City(models.Model): city = models.CharField(max_length=40) class Area(models.Model): city = models.ForeignKey(City,on_delete=models.PROTECT) area = models.CharField(max_length=40) class Street(models.Model): city = models.ForeignKey(City,on_delete=models.PROTECT) area = models.ForeignKey(Area,on_delete=models.PROTECT) street = models.CharField(max_length=40) def __str__(self): return self.street class Nearest(models.Model): city = models.ForeignKey(City,on_delete=models.PROTECT) area = models.ForeignKey(Area,on_delete=models.PROTECT) street = models.ForeignKey(Street,on_delete=models.PROTECT) nearest_place = models.CharField(max_length=40) my views.py def load_city_area_street(request): city_id = request.GET.get('city') city = City.objects.get(id=city_id) area = Area.objects.filter(city=city_id).all() area_id = request.GET.get('area') area_name = Area.objects.get(id=area_id) street = Street.objects.filter(area=area_name) return render(request,'locations/dropdown.html',{'city':city,'area':area,'street':street}) my template $('#id_city').change(function(){ const url = $('#post-form').attr("data-city-area-street-url"); const cityId = $(this).val(); $.ajax({ url : url, data:{ 'city':cityId }, success:function(data){ $('#id_area').html(data); } }) }) <form id="post-form" method="POST" data-city-area-street-url="{% url 'locations:load_city_area_street' %}"> {% csrf_token %} <div class="card-body"> <div class="row"> {{form.as_p}} </div> </div> <button type="submit" class="btn btn-success">save</button> </form> but it works only for the area field , i need to make a change for several fields for example $('#id_city #id_area #id_street').change(function() but it doesnt work ! isnt there a better way to achieve that please? thank you -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'User.User' that has not been installed
I wanna use my custom user in my Django project and I wanna use the OTP system for login in my project so I delete the username and password field of the user and the user should login with a phone number but I get an error. these are my codes: class UserManager(BaseUserManager): def create_user(self, phone_number): user = self.model( phone_number = phone_number ) if not phone_number: raise ValueError('Phone number is required') user.save(using = self._db) user.is_superuser = False user.is_admin = False user.name = "green user" return user def create_superuser(self, phone_number): user = self.create_user( phone_number = phone_number ) user.is_superuser = True class User(AbstractUser): username = None password = None email = models.EmailField(null = True, blank = True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) phone_number = models.IntegerField(unique=True) is_owner = models.BooleanField(default=False) is_advisor = models.BooleanField(default=False) name = models.CharField(max_length=40) image = models.ImageField(blank = True, null=True) data_join = models.DateTimeField(default = timezone.now) code_agency = models.IntegerField(null=True, blank=True, default=0) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = ['phone_number',] objects = UserManager() def __str__(self): return self.phone_number class MyUserAdmin(UserAdmin): model = User list_display = ('phone_number', 'email') list_filter = ('phone_number', 'email') search_fields = ('phone_number') ordering = ('phone_number') filter_horizontal = () fieldsets = UserAdmin.fieldsets + ( (None, {'fields': ('phone_number',)}), ) in my stting i … -
Django how to automatically save user in froms?
When I am passing "user" fields to my Model froms. I am getting all user details as dropdown. see the picture: I am trying to save current user instance without showing this dropdown because I want user will be automatically save without selecting or showing this dropdown. here is my froms.py: class ProfileFroms(forms.ModelForm): class Meta: model = UserProfile fields = ["user","profile_pic","mobile","country","website_link"] when I remove "user" froms fields then getting this error: "NOT NULL constraint failed: members_userprofile.user_id" I aslo tried this code for saving current user but getting same error. views.py if forms.is_valid(): forms.user = request.user here is my full code: models.py class UserManagement(AbstractUser): is_subscriber = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile") profile_pic = models.ImageField(upload_to='profile/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )],blank=True,null=True) mobile = models.IntegerField(blank=True,null=True) country = models.CharField(max_length=200,blank=True,null=True) website_link = models.CharField(max_length=3000,blank=True,null=True) views.py def UserProfileView(request): userinfo = UserManagement.objects.filter(username=request.user) forms = ProfileFroms(request.POST,request.FILES or None) if request.method == "POST": if forms.is_valid(): #forms.user = request.user #tried this line for save current user but didn't work forms.save() messages.add_message(request, messages.INFO,'Profile not updated sucessfully') return redirect("members:user-profile-private") else: messages.add_message(request, messages.INFO,'Somethings wrong. Profile not updated') print("invalid") context={"userinfo":userinfo,"forms":forms} return render(request,"members/privateprofile.html",context) -
how to patch only the foreign key of a nested serializer in django rest framework?
I have a nested serializer which binds some fields that are foreign keys to the related objects, when i make a get request I get the data as I want it, but when I make a patch request I would like to be able to only provide the foreign key id instead of the whole object representation. -
Docker Django Error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False
I've been trying to dockerise my django project with postgresql but have been running into this same problem time and time again. web_1 | CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. I've my environment variables in a .env set to: .env: DEBUG = True ALLOWED_HOSTS=localhost 127.0.0.1 0.0.0.0:8000 and use the python-decouple module to configure them in settings.py from decouple import config DEBUG = config('DEBUG', default=False) ALLOWED_HOSTS = config('ALLOWED_HOSTS').split(sep=' ') Running the project: python manage.py runserver works perfectly fine with no errors. However, when it comes to running: docker-compose up I get the following output Starting postgres_db ... done Starting project_web_1 ... done Attaching to postgres_db, project_web_1 postgres_db | postgres_db | PostgreSQL Database directory appears to contain a database; Skipping initialization postgres_db | postgres_db | 2021-07-30 17:58:52.695 UTC [1] LOG: starting PostgreSQL 13.3 (Debian 13.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit postgres_db | 2021-07-30 17:58:52.696 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres_db | 2021-07-30 17:58:52.696 UTC [1] LOG: listening on IPv6 address "::", port 5432 postgres_db | 2021-07-30 17:58:52.747 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" postgres_db | 2021-07-30 17:58:52.887 UTC [27] LOG: database system was shut down at 2021-07-30 17:58:34 … -
Django webserver automatic failover design
I am trying to build a Django backend system combined with Celery. The idea is that there is a list of 500+ websites that will be processed by Celery every 5 min. Since it involves a lot of network operations which can take any amount of time and we have time constraint of 5 min, we are planning to have multiple Django webservers running in parallel with each processing some amount of websites. The idea is that each Django web server will process (500+ list of websites) / (total number of Django websites instances running), this way we can distribute the workload and in case if anyone goes down then others can take over. I have created a heartbeat rest API which other Django webservers will use to check the status of other servers but how can I make it scalable? What I want is each web server will auto-detect how many others are running and then will process the list accordingly, for example, if there are 5 web servers running then each of them will process only 100 websites, the first server will process first 1-100, then the second one will process next 101-200, the third one will process … -
how to add values from view to url in django
I have to give values from view to url like the name is the value from view : how can i achieve that -
Django [WinError 10053] when loading up server
Whenever I start up my Django server i get the errors shown below. The weird thing is that sometimes the [WinError 10053] doesn't show up and I can develop normally but when it does show up the project seems to malfunction and .css and .js files also don't get loaded. I have already looked into other stackoverflow questions that seemed related such as setting the correct code page to use with postgres or the python bug mentioned here https://bugs.python.org/issue27682. But I'm using python 3.9 so that bug should be fixed. Does anyone know how to fix this? The project works just fine on the computers of some other people and everything that we compared seemed the same (settings, pycharm configuration,...). Exception occurred during processing of request from ('127.0.0.1', 59986) ---------------------------------------- Exception occurred during processing of request from ('127.0.0.1', 55047) Traceback (most recent call last): File "D:\DataDownloads\lib\socketserver.py", line 683, in process_request_thread self.finish_request(request, client_address) Traceback (most recent call last): File "D:\DataDownloads\lib\socketserver.py", line 683, in process_request_thread self.finish_request(request, client_address) File "D:\DataDownloads\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "D:\DataDownloads\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "D:\DataDownloads\lib\socketserver.py", line 747, in __init__ self.handle() File "D:\Documents - data drive\StepDB\gitlab\site\Site\venv\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle self.handle_one_request() … -
How to create Model with nested object in Django
I'm trying to create a small product manufacturing app with Django. There are two main models in the app. class Product(models.Model): name = models.CharField(max_length=100, blank=True, default='') class ProductionOrder(models.Model): created = models.DateTimeField(auto_now_add=True) entries = # not sure what goes here I would like ProductionOrder.entries to be a list of dictionaries which include the Product and a quantity value. The created ProductionOrder would appear as so (not exactly sure : productionOrder = { 'id': 2, 'entries': [ { 'product': 'product_1_ref', 'quantity': 10}, { 'product': 'product_2_ref', 'quantity': 10} ] } How can I accomplish this in a correct way? -
Database connection strings and running database dependency for testing stage in multi-stage Dockerfile
I'm building out a multi-stage Dockerfile and it is my first time doing so and have a couple questions related to it. Currently I'm working on the Django API with the following Dockerfile: # python-base stage FROM python:3.8-slim as python-base ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ PIP_NO_CACHE_DIR=off \ PIP_DISABLE_PIP_VERSION_CHECK=on \ PIP_DEFAULT_TIMEOUT=100 \ POETRY_HOME="/opt/poetry" \ POETRY_VIRTUALENVS_IN_PROJECT=true \ POETRY_NO_INTERACTION=1 \ PYSETUP_PATH="/opt/pysetup" \ VENV_PATH="/opt/pysetup/.venv" ENV PATH="$POETRY_HOME/bin:$VENV_PATH/bin:$PATH" # builder-base stage FROM python-base as builder-base RUN apt-get update \ && apt-get install --no-install-recommends -y \ curl \ build-essential ENV POETRY_VERSION=1.1.7 RUN curl -sSL https://raw.githubusercontent.com/sdispater/poetry/master/get-poetry.py | python WORKDIR $PYSETUP_PATH COPY ./poetry.lock ./pyproject.toml ./ RUN poetry install --no-dev # Development stage FROM python-base as development COPY --from=builder-base $POETRY_HOME $POETRY_HOME COPY --from=builder-base $PYSETUP_PATH $PYSETUP_PATH COPY ./docker-entrypoint.sh /docker-entrypoint.sh RUN chmod +x /docker-entrypoint.sh WORKDIR $PYSETUP_PATH RUN poetry install WORKDIR /app COPY . . EXPOSE 5000 ENTRYPOINT /docker-entrypoint.sh $0 $@ CMD ["python", "manage.py", "runserver", "0.0.0.0:5000"] # test stage FROM development AS test RUN coverage run --omit='manage.py,config/*,.venv*,*/*__init__.py,*/tests.py,*/admin.py' manage.py test I'm running into with two issues with the test stage: Django starts up and performs its system checks and sees the os.environ[] are empty because the env vars don't exist in the Docker image. And they don't exist there because, from what I understand, … -
Formatting datetime field with Django Rest Framework serializers
I need to add "am/pm" next to a formatted datetime field and it is not showing up. Here is what I have in my serializer. class MySerializer(serializers.ModelSerializer): join_date = serializers.DateTimeField(format="%b %d %I:%M %p") Which just outputs Mar 2 8:30 However, with the same field usiing datetime.strftime(join_date, "%b %d %I:%M %p") I get Mar 2 8:30 am Is there a different variable I need for DRF serializer to format the am/pm? -
Get pymongo error: pymongo.errors.OperationFailure: bad auth : Authentication failed
I have a problem: I wrote python code to communicate with other people through a database that runs on Pymongo. My program was able to connect to the database but could not send files (this is how I tried to get my variable to the database: db.insert_one (msg)). The computer gives me this error: Traceback (most recent call last): File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\pool.py", line 1394, in _get_socket sock_info = self.sockets.popleft() IndexError: pop from an empty deque During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Luis\PycharmProjects\PresentationGuru2021\main.py", line 133, in Startup() File "C:\Users\Luis\PycharmProjects\PresentationGuru2021\main.py", line 63, in Startup main() File "C:\Users\Luis\PycharmProjects\PresentationGuru2021\main.py", line 128, in main db.insert_one(msg) File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\collection.py", line 705, in insert_one self._insert(document, File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\collection.py", line 620, in _insert return self._insert_one( File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\collection.py", line 609, in _insert_one self.__database.client._retryable_write( File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\mongo_client.py", line 1552, in _retryable_write return self._retry_with_session(retryable, func, s, None) File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\mongo_client.py", line 1438, in _retry_with_session return self._retry_internal(retryable, func, session, bulk) File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\mongo_client.py", line 1462, in _retry_internal with self._get_socket(server, session) as sock_info: File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\contextlib.py", line 117, in enter return next(self.gen) File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\mongo_client.py", line 1308, in _get_socket with server.get_socket( File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\contextlib.py", line 117, in enter return next(self.gen) File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\pool.py", line 1331, in get_socket sock_info = self._get_socket(all_credentials) File "C:\Users\Luis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\pool.py", … -
multiple content in article model (blog)
I am designing a blog as my personal proj but having seen many blogs online I have noticed one trend, some of them are diverse with content put any type of content, (what I mean to say is) article will have heading then some description then some code snippet than some picture then again some code snippet, then maybe some video clip, now my query am I supposed to design my model such that it should have all that variety as fields inside my models? that's what I am confused about class Entry(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) picture = models.ImageField(upload_to='images', blank=True) video = models.FileField(upload_to='videos', blank=True) class Meta: verbose_name_plural = 'entries' @property def get_photo_url(self): if self.picture and hasattr(self.picture, 'url'): return self.picture.url else: return " " def __str__(self): return f'{self.text[:80]}...' should i add fields like ( code , and other type of stuff ) -
django.core.exceptions.FieldDoesNotExist: User has no field named 'username'
I'm trying to customize django's AbstractUser. When I try to reset username to None, I get the following exception: "django.core.exceptions.FieldDoesNotExist: User has no field named 'username'". Here is my code: class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError("L'adresse e-mail donnée doit etre definie") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True") return self._create_user(email, password, **extra_fields) class User(AbstractUser): username = None email = models.EmailField('email adress', unique=True) telephone = models.CharField(max_length=20) REQUIRED_FIELDS = [] What can i do to solve this probleme ? -
Django Limiting models based on status
I need to create a route to edit a purchase, but editing can only be done if the status of the purchase is "in validation". Does anyone know what Django tool I use to limit a status-based model? -
Error kernel Out of memory: Killed process (uwsgi) & consume too much memory
In the past few days, my site is crashing and OS message logs shows the OOM killer kills the process. Server have 32GB RAM but still we face Out Of Memory Issue due to uwsgi. OS: Gentoo Linux Here is my uwsgi.ini [uwsgi] chdir = /var/www/%n virtualenv = venv pythonpath = %(chdir)/python/ socket = /var/run/uwsgi/%n.sock logger = syslog:%n vacuum = true module = mysite.wsgi:application master = true threads = 32 enable-threads = true plugins = python27 spooler = %(chdir)/uwsgi_spooler spooler-processes = 5 spooler-frequency = 5 import = mysite.fork env = LC_ALL=en_US.UTF-8 env = LANG=en_us.UTF-8 Error Message logs /var/log/messages:Jul 20 06:31:39 ip-10-0-0-45 kernel: Out of memory: Killed process 16625 (uwsgi) total-vm:6933540kB, anon-rss:1988220kB, file-rss:3676kB, shmem-rss:68kB, UID:998 pgtables:12824kB oom_score_adj:0 /var/log/messages:Jul 20 16:02:48 ip-10-0-0-45 kernel: Out of memory: Killed process 25622 (uwsgi) total-vm:8216796kB, anon-rss:3184288kB, file-rss:4336kB, shmem-rss:72kB, UID:998 pgtables:15408kB oom_score_adj:0 /var/log/messages:Jul 20 18:22:25 ip-10-0-0-45 kernel: Out of memory: Killed process 27520 (uwsgi) total-vm:10033820kB, anon-rss:7766404kB, file-rss:4900kB, shmem-rss:72kB, UID:998 pgtables:18960kB oom_score_adj:0 /var/log/messages:Jul 20 18:41:47 ip-10-0-0-45 kernel: Out of memory: Killed process 26553 (uwsgi) total-vm:9450820kB, anon-rss:4271912kB, file-rss:0kB, shmem-rss:408kB, UID:998 pgtables:15804kB oom_score_adj:0 /var/log/messages:Jul 20 18:43:58 ip-10-0-0-45 kernel: Out of memory: Killed process 26988 (uwsgi) total-vm:9023384kB, anon-rss:4560056kB, file-rss:4896kB, shmem-rss:40kB, UID:998 pgtables:17080kB oom_score_adj:0 /var/log/messages:Jul 20 18:49:20 ip-10-0-0-45 kernel: Out of memory: … -
module not found error even though modules are in place
I had this error previously but at an instant, it was somehow fixed, but now it seems to crawl back,don't know where is the issue, thanks in advance Directory structure food_deliveryapp |- manage.py |- food_deliveryapp |- customers |- entries |- restaurants | |- __init__.py | |- admin.py | |- apps.py | |- models.py | |- City | |- Restraunts | |- views.py | |- tests.py | |- migrations | |- static |- templates my modules and models are in place but still getting this error 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 "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\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 "C:\Users\atif\PycharmProjects\my_proj_basic\food_deliveryapp\menus\models.py", line 3, in <module> from … -
How to convert from time stamp to a date time filed in dajngo
I 'm working on a django app and i have a model with a datetimefield and in my view i accept data in json format which has date in time stamp , when i try to save the date in my model i get this error "Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]." i tried to use this with no help : date_converted_to_date_time_field = datetime.utcfromtimestamp(due_in_time_stamp ) any help to achieve this ? -
Django - Celery - Heroku error: Redis is not responding
I would like my django to make a periodic task every 15 minutes. I've found out that celery would be a solution to my problem. I've created an heroku app, installed redis server addon there but it actually is not working anyway. While making a worker there is an output: ERROR/MainProcess] consumer: Cannot connect to redis://:pe8c9b5be760e533395873863fc98c469f126ca80574a04d6112a172d1756e2aa@ec2-34-194-101-94.compute-1.amazonaws.com:7140 My settings.py: # CELERY STUFF CELERY_BROKER_URL = 'redis://:pe8c9b5be760e533395873863fc98c469f126ca80574a04d6112a172d1756e2aa@ec2-34-194-101-94.compute-1.amazonaws.com:7140' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' tasks.py from celery import shared_task from time import sleep @shared_task def apiCalls(self, duration): #here I would like my function to execute - yet even print('abcdef') is not working return 'Done' What am I doing wrong? -
pytest cannot find database and tables
I am trying to speed up the test runtime by using pytest-xdist, previously I was using pytest, pytest-django to run the tests, After installing pytest-xdist, One is an issue which I am facing is most of the tests are failing with messages that relation does not exist pytest -n auto accounts/tests for example psycopg2.errors.UndefinedTable: relation "auth_user" does not exist I guess there is error which says database does not exist: django.db.utils.OperationalError: FATAL: database "test_dev" does not exist But the interesting thing is some of tests are passing :( -
Websocket disconnects immediately after handshake (guacamole)
Forgive bad formatting as it is my first question on here, and thanks in advance for reading! I am currently writing a remote web application that utilises Apache Guacamole to allow RDP, VNC, and SSH connections. The components I am using are: Django for backend server - API calls (database info) and Guacamole Websocket Transmissions; I am using Pyguacamole with Django consumers to handle Guacamole Server communication; Reactjs for frontend and proxy; Nginx for reverse proxy; All this is hosted on a Centos Stream 8 vm Basically, my websocket has trouble communicating through a proxy. When I run the application without a proxy (firefox in centos running localhost:3000 directly), the guacamole connection works! Though this is where the application communicates directly with the Django server on port 8000. What I want is for the react application to proxy websocket communications to port 8000 for me, so my nginx proxy only has to deal with port 3000 for production. Here is the code I have tried for my react proxy (src/setupProxy.js): const { createProxyMiddleware } = require('http-proxy-middleware'); let proxy_location = ''; module.exports = function(app) { app.use(createProxyMiddleware('/api', { target: 'http://localhost:8000', changeOrigin: true, logLevel: "debug" } )); app.use( createProxyMiddleware('/ws', { target: 'ws://localhost:8000' + … -
Django multiple parents and every parent may have the same children, but changing one children should be changed for this parent not the others?
I have a system for ambulance service built with Django, React for the API and dashboard and Android for the mobile app, where crew belong to an ambulance and ambulance has calls and every call has forms and every form has questions Now when crew login to mobile app he will see his ambulance details and its calls and inside each call he will see the forms Now crew need to do two things, submit forms and submit call In case submitting a form it should be showed on the admin dashboard a list of submitted forms and in case to submit a call, crew must submit first all required forms inside that call, and submitted calls should be showed on the admin dashboard Also I need to make checkbox done on the mobile app to the submitted call or form To solve this, I added a boolean field for the call model and form model to check if call or form is submitted Now the client didn't want that, because he could assign the same form or call for another ambulance that has different crew, so in my case if another crew logged to the app he will see … -
how to delete useranme and password of customuser in django
how to delete username and password of a customuser in Django. I wanna set phone and OTP code instead of username and password. class User(AbstractUser): """ . . . """ image = models.ImageField(blank = True) number = models.IntegerField() -
How to update a specific value of a object present in array of object within Postgres JSON Field
Here is my JSON field value. which is stored in the PostgreSQL table. I want to search and update the specific user_name in the user key { "user": [ { "user_name": "Devang", "user_weight": 0.7676846955248864 }, { "user_name": "Meet", "user_weight": 0.07447325861051013 }, { "user_name": "L.b.vasoya", "user_weight": 0.056163873153859706 } ], "address": [ { "address_name": "India" } ] } whose name is Devang to Dev using Django JSONField for example "user": [ { "user_name": "Dev", "user_weight": 0.7676846955248864 }, .... I have tried the RAWQuery for the find. This is the query. ``` select json_field->user from user_table where json_field @> '{"user": [{"user_name": "Devang"}]}'; It will return like this ```[ { "user_name": "Devang", "user_weight": 0.7676846955248864 }, { "user_name": "Meet", "user_weight": 0.07447325861051013 }, { "user_name": "L.b.vasoya", "user_weight": 0.056163873153859706 } ] I have also tried JSON_SET to update the user_name but JSON_SET only accepts. It will update the upper level, not a nesting level