Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Failing to display json into html with ajax
I am implementing a 'load more' button for my posts. With ajax this is what I'm doing to display the loaded posts into my html: success:function(res){ var _html=''; var json_data=$.parseJSON(res.posts); $.each(json_data,function(index,data){ _html+='<div class="post-box col-md-1">\ <div class="info-box mb-4">\ <div>\ {% if '+data.fields.cantidad+' == 1 %}\ <h3>'+data.fields.donador+'</h3><text>te donó '+data.fields.cantidad+' '+data.fields.objeto+'.</text>\ {% else %}\ <h3>'+data.fields.donador+' </h3><text>te donó '+data.fields.cantidad+' '+data.fields.objeto+'s.</text>\ {% endif %}\ <br>\ <text>'+data.fields.whenpublished+' </text>\ {% if '+data.fields.message+' != "" %}\ <hr>\ <text>'+data.fields.message+'</text>\ {% endif %}\ </div>\ </div>\ </div>'; }; This is my model: class Donacion(models.Model): creador_d = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now_add=True, blank=True) message = models.CharField(max_length=300, null=True, blank=True) donador = models.CharField(max_length=30, null=True, blank=True) cantidad = models.IntegerField() objeto = models.CharField(max_length=30, null=True, blank=True) def whenpublished(self): now = timezone.now() diff = now - self.creation_date if diff.days == 0 and diff.seconds >= 0 and diff.seconds < 60: seconds= diff.seconds if seconds == 1: return "Hace " + str(seconds) + " segundo" else: return "Hace " + str(seconds) + " segundos" if diff.days == 0 and diff.seconds >= 60 and diff.seconds < 3600: minutes= math.floor(diff.seconds/60) if minutes == 1: return "Hace " + str(minutes) + " segundo" else: return "Hace " + str(minutes) + " minutos" if diff.days == 0 and diff.seconds >= 3600 and diff.seconds < … -
Django collectstatic is not pushing to AWS S3
Please Help i have searched and reconfigured my project so many times i have created new aws accounts but still having the same issue python manage.py collectstatic keeps reverting to old folder i used for testing after configuring my aws s3 bucket for django this way # AWS service variables AWS_SECRET_KEY_ID = config('AWS_SECRET_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = 'd1l47x08equ47x.cloudfront.net' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_LOCATION = 'static' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' nothing happens when i run collect static Please someone help -
Django creating a web site with fully coded html
I have a project where I have to design the web page and create a login system for the user. I wrote a fully build HTML, CSS and javascript web design and now I have to connect with Django to build a login system. I know it's a bit a simple question but is it so hard to build the templates for fully made HTML? I searched everywhere for such an example like that but in every video I watch people starting the web design from to top. -
Is it mandatory to use sessions in Django to stop one user's information being displayed to another?
Hi I'm very new at Django and I'm sorry if this is a stupid question. I have created an application using Django where I have a form accepting information using the POST method. In views.py I then get the information I want and store it in a variable to be displayed back to the page. However, when I deployed this to heroku, I noticed anyone who accessed the webpage would enter their name and their name would be visible to everyone. I didn't store it in a database, it's only stored in a variable. How do I make it so that all user entered by a user stays on only their page when they access it? Do I need to use sessions? -
How to create a server side timer/countdown in Django Channels?
Lets say I am building a pub-quiz app with Django Channels (Websockets). There are 10 questions and each question has a time limit and a button to add extra 5 seconds. I know a possibility would be to haver the timer client-side, but I need it to be server-side to avoid tampering with the Js causing problems since there are many players involved. How can I create a timer in Django, server-side? Once the timer is up, it would need to call a function to fetch the next question. I would know how to do it with a while loop: While True: if datetime.now() == question_end_time: fetch_next_question() But from what I have read this does not seem to be a good idea due to blocking the thread. Is there any other way how to check every second if the time for the question is up and is so, call a function? Thanks in advance. -
Django Routing w/ subApplication
What I have: a Django Project that is acting as a REST API through Django Rest Framework. a number of Django Apps that are controlling the logic of my Postgres DB. What I am trying to do: Create a new Django App that represents a Service / Integration with Robinhood Within ^^ I want to structure my logic in subApplications in order to separate all logic for a user vs a transactions vs a transfers etc ... This entire Django App & all subApplications are APIs ONLY ... they will never need models / migrations but they will eventually communicate with the other Django Apps CODE STRUCTURE: Main Django Project ├── APP_holdings ├── APP_logs ├── APP_unique ├── APP_users ├── ⭐️⭐️ DJANGO │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── asgi.py │ ├── fixtures │ │ ├── platforms.json │ │ └── symbols.json │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── EXAMPLE.env ├── Pipfile ├── Pipfile.lock ├── Procfile ├── README.md ├── ⭐️⭐️ SERVICE_robinhood │ ├── README.md │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ ├── ⭐️⭐️ user │ │ ├── __init__.py … -
Django view not getting ajax request
I have a script in my template that tries to send data to a django view during onbuttonclick event. My problem is that the request doesn't seem to make it to the view. The browser console sees the request properly and all, but the django view does't even return true when i call request.is_ajax(). request.method returns GET instead of POST, and the data is empty. This behavior is persistent regardless of the request type. html <a onclick="setGetParameter(this)" pid="some_id">Some Text</a> .js <script> var csrftoken = Cookies.get('csrftoken'); function setGetParameter(el){ var stuff = $(el).attr('pid'); $.ajax({ type: 'POST', headers: { "X-CSRFToken": csrftoken }, url: '/view_url/', data: {'datatopass': stuff}, success: function(response){ alert(response); } }); } </script> urls.py path('view_url/', views.test), path('', views.home), views.py def test(request): output = request.is_ajax() return HttpResponse(output) -
How to index a resampled pandas dataframe by datetime?
I am using the django_pandas package to obtain a Pandas dataframe from stored Django models. df = qs.to_dataframe(['time', 'price_open', 'price_high', 'price_low', 'price_close'], index='time') Now I want to access the dataframe by a datetime, however, this does not work. Printing df looks like this, where the time column has a weird position: If I do print(df.keys()) I get the following results: Index(['price_open', 'price_high', 'price_low', 'price_close', ], dtype='object') but I more expected time. Also, df.columns does not contain time but only the other columns. How can I access df by a given datetime? Why is time not the key for df? Thanks! -
Allow REST api access only by personal webiste (not other requests servcices)
I know this question was asked before but I didn't found a feasible solution for my problem, I implemented CORS inside my Django application in order to restrict the domain access and also used CSRF tokens for secure data transfer against unsecured HTTP methods, but still I can make requests to an API via postman or other HTTP services, how can I avoid that? NOTE: my app doesn't make use of users with oAuth system and more, it makes a POST request to the database in order to get a token (app term specific) regardless of the person who is making the request, but I want only my website to make such request and NO MORE, how to do that? -
How to POST a data into the restricted REST API url without logging in as a user?
In my Django app. I use django.contrib.auth as authentication for users, I also have django rest framework APIs. I have enabled. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), Since, I can only access the API data by logging in through the user account, but on my project. I have a sensor(IoT) that have to POST into the api 127.0.0.1/api/data/, How can I authenticate my sensor(IoT) to POST request into the API url without expiring session? or How to POST a data into the restricted REST API url without logging in as a user? Thanks! -
should admin-only fields be extracted into a dedicated model which has a OneToOne relation to the original model?
I have the following model class User(AbstractUser): # other fields... billing_active = models.BooleanField( _('Billing active'), default=True, help_text=_( 'designates whether the user should be charged' ) ) billing_start = models.DateField(_('Billing cycle start')) billing_end = models.DateField(_('Billing cycle end')) billing_charge = models.DecimalField( _('Charge'), max_digits=5, decimal_places=2, help_text='amount to be charged' ) by looking at those prefixes billing_* it seems that fields should belong to a new object, it seems OK since it's just a database representation. But billing_active and billing_charge are admin fields and can't be changed by user, would it be good to create a new model UserBillingSettings which contains all those fields? then I could use django's builtin permissions system: class User(AbstractUser): # fields ... class UserBillingSettings(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='billing_settings') # billing fields -
Is it possible to group by field name using django orm?
I have two models: class ExampleOne(models.Model): # some fields class ExampleTwo(models.Model): example_one = models.ForeignKey( "App.ExampleOne", on_delete=models.CASCADE, related_name="examples", ) field_one = ... field_two = ... And I created this view for my endpoint: class MyViewSet(viewsets.ViewSet): def list(self, request): queryset = ExampleOne.objects.all().values( "id", "examples__field_one", "examples__field_two", ) return Response({"data": queryset}) That return this: { "data": [ { "id": 1, "examples__id": 1, "examples__field_one": foo, "examples__field_two": bar, }, { { "id": 1, "examples__id": 2, "examples__field_one": foo, "examples__field_two": bar, }, { "id": 2, "examples__id": 3, "examples__field_one": foo, "examples__field_two": bar, } But I wanted a way to group by the first model. It's possible? I wanted something like this: { "data": [ { "1": [ { "examples__id": 1, "examples__field_one": foo, "examples__field_two": bar, }, { "examples__id": 2, "examples__field_one": foo, "examples__field_two": bar, }, ], "2": [ { "examples__id": 3, "examples__field_one": foo, "examples__field_two": bar, }, ] } } It's possible? All information I find about grouping involves values (count, sum, ...). But I just wanted to group by one field (model one id). -
How to change email settings in django dynamically
I want to make an email sender app that took user email and password and send an email to multiple recipients. I am not sure whether it is possible to do because we have to provide Email_HOST_USER in settings. If anyone can help me with explanation please? -
dropdown is not showing html css
i have the attr data-toggle= dropdown on the {{form.query}} which is the search input but it just wont show, any solutions? bootstrap/jquery links in head section <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> js in body <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script> hmtl code <form class="dropdown" method="get"> {{form.query}} <ul class="dropdown-menu col-12 pl-2" role="menu" aria-labelledby="menu" id="list"> <li role="presentation"> <a href="#" role="menuitem" tabindex="-1">Django</a></li> <div class="dropdown-divider"></div> <li role="presentation"> <a href="#" role="menuitem" tabindex="-1">Potato</a></li> <div class="dropdown-divider"></div> <li role="presentation"> <a href="#" role="menuitem" tabindex="-1">Sleep</a></li> </ul> {{form.category}} <input type="submit" value="Search" class="btn btn-lg btn-primary col-12 my-2"> </form> -
I was trying to add templates to my Django project but it returns an error: TemplateDoesNotExist at /
I get a mistake when tying to add templates to my Django project. settings.py : TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'), ) views.py: def index(request): a = models.User.objects.get() return render(request, "main/list.html", {"list": a}) and list.html: {% extends "base.html" %} {% block title %}Chats{% endblock %} {% block content %} {% if list%} {% for i in list%} <h2>{{i.usrname}}</h2> {% endif %} The project folder itself looks like this: Main folder is app. Thanks for your help! -
How to dynamically update Twitter meta tags using Django model object fields
all. I am trying to create Twitter cards dynamically by filling in "content=" values with Django model object fields that I can update using the admin panel. My HTML header code looks like this: <meta name="twitter:card" content="{{ lesson.twitter_card_type }}"> <meta name="twitter:description" content="{{ lesson.twitter_description }}"> <meta name="twitter:title" content="{{ lesson.twitter_title }}"> <meta name="twitter:site" content="{{ lesson.twitter_site }}"> <meta name="twitter:image" content="{{ lesson.twitter_image }}"> <meta name="twitter:creator" content="{{ lesson.twitter_creator }}"> Replacing the variables with static values passes the Twitter card validator checks. When using variables, the browser inspector displays the proper meta tags, but I get the following output from the Twitter card validator log: INFO: Page fetched successfully INFO: 13 metatags were found ERROR: Invalid card name (Card error) According to this answer Twitter card meta tags work in index.html, not in React Helmet and this answer Dynamically adding meta tags using javascript or jquery [twitter cards], it seems that there might be an issue using variables in meta tags; however, this site https://www.ordinarycoders.com/blog/article/how-to-add-django-meta-tags states using Django model objects should work. Unfortunately, I need to create cards dynamically the way my site is set up so hard-coding is not an option. Thanks in advance to anyone who can offer any insight! -
By using transaction.atomic, are all ACID properties met?
This is a theoretical question I'm trying to work out. I'm working on a Django-based web application and I'm wanting to make my Django database transactions ACID compliant. However I'm wondering if this is fully achieved by using transaction.atomic? Obviously, Atomicity is achieved here but are the other 3 properties also achieved? If not, what steps can I take to achieve those 3 properties? Any thoughts and explanations would be much appreciated, thank you! -
All data gets deleted after deploying new version in Elastic Beanstalk
So I am hosting my Django website on the elastic beanstalk. Whenever I deploy a new version the older data gets deleted. Though upon deploying a newer version, it says it uses S3 bucket yet all my data and images are deleted. .ebextensions/db-migrate.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango/wsgi.py settings.py .... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': str(BASE_DIR / 'db.sqlite3'), } } ... STATIC_URL = '/static/' STATIC_ROOT = 'static' MEDIA_URL = '/uploads/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/uploads') ... -
DRF convert string of Ids to related model objects in serializer
Trying to write up a Model/Serializer/View with DRF to provide a rest_framework.viewsets.ModelViewSet that includes the appropriate EmpList based on the string of user-ids in Publication.author. Only need the objects to be serialized for output, no need to create new EmpList objects. # Would a model manager help here? class Publication(models.Model): # The author is stored as a string "user-id1, user-id2, user-id3" # This storing as a string of multiple ids can't change author = models.TextField() ... class PublicationSerializer(serializers.ModelSerializer): # Would I add code here to override list? class PublicationViewSet(rest_framework.viewsets.ModelViewSet): queryset = Publications.objects.all() serializer_class = PublicationSerializer # EmpList is a model on top of an SQL View, so there's no real model level connection in the tables class EmpList(models.Model): # This ID matches up with "user-id1" found in Publication.author id = models.CharField() name = models.CharField() ... class EmpListSerializer(serializer.Serializer): class Meta: model = EmpList fields = ["__all__"] This seems pretty possible, I just can't seem to figure out how to wire things up correctly. Any thoughts are appreciated, thanks. -
database_table locked during automated tests with selenium django
I use django==3.1.2 and selenium and selenium==3.141.0. I have a test file with 12 tests and when I execute them like so: python3 manage.py test myapp.tests --settings=app.settings_test 2 of the tests fail. When I execute them singly like so python3 manage.py test myapp.tests.MyTests.test_this --settings=app.settings_test they don't fail. The errors are usually something like django.db.utils.OperationalError: database table is locked: visitors_person The above exception was the direct cause of the following exception: myapp_cars ... django.core.management.base.CommandError: Database file:memorydb_default?mode=memory&cache=shared couldn't be flushed. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the expected database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run. or django.db.utils.OperationalError: database table is locked: myapp_drivers It always errors on different models of the database. My database in settings_test.py looks like this: DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(tempfile.gettempdir(), 'db_test.sqlite3'), 'OPTIONS': { 'timeout': 20, } } During these tests I create about 120 entries spread over 12 tests, the fixtures install about 20 entries. So not that much. After googling the error I added the timeout and I added time.sleep(1) after each MyModal.objects.create() to see if this … -
Change django model fields on the basis of other fields value
I have a query that can we achieve something like this. This is not a model. This is just a plot of what I want to achieve. I want to change field input type on the basis of other field value. x=models.BooleanField(default=true) if x: name =models.CharField(max_length=100, null=True, blank=True, default='abc') else: name=models.ForeignKey(SomeModel,on_delete=models.CASCADE) -
Please help, no code changed but now not working
I have a django Post model with a user foreign key. When I create a post it normally would work and fill the user with the requested user as instructed in the serializer but on postman I get: { "user": [ "This field is required." ] } here is the API view: class PostViewset(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = [IsOwnerOrReadOnly] def perform_create(self, serializer): serializer.save(user=self.request.user) here is the serializer: class PostSerializer(serializers.ModelSerializer): user_name = serializers.SerializerMethodField() class Meta: model = Post fields = ['user', 'id', 'title', 'body', 'user_name'] def get_user_name(self, obj): try: return obj.user.user_name except: pass -
Django: datetime.now() not saving to database from view.py
I am trying to save the date time in my view on form submission. models: class Request(models.Model): email = models.EmailField(max_length=200) percentage = models.FloatField( default=0, validators=[MinValueValidator(0), MaxValueValidator(100)]) fee = models.FloatField(default=0, validators=[ MinValueValidator(0), MaxValueValidator(100000)]) updated_at = models.DateTimeField(db_index=True, auto_now=True) requested_at = models.DateTimeField(null=True) approved_at = models.DateTimeField(null=True) confirmed_at = models.DateTimeField(null=True) view: if form.is_valid(): instance = form.save(commit=False) instance.requested_at = datetime.now() instance.save() The form saves fine except for the requested_at date time which isn't saving. Think I am missing something simple but I cannot figure it out... -
Is there a way to use reverse outside of a Django App?
Long story short, I need to call a python script from a Celery worker using subprocess. This script interacts with a REST API. I would like to avoid hard-coding the URLs and django reverse seems like a nice way to do that. Is there a way to use reverse outside of Django while avoiding the following error? django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I would prefer something with low-overhead. -
How do I update fields in MongoDB document using djongo?
how can I update a document fields with Djongo MongoDB Model exemple { id: ObjectId(6deer3096f0efae5c49b9983f) email:"email@gmail.com" password:"pass" username:"user" } Request made { email:"newemail@gmail.com" password:"newpass" username:"newuser" } Here is my code @api_view(['GET', 'POST', 'DELETE']) def user_detail(request, id): try: user = User.objects.get(_id=ObjectId(str(id))) user_serializer = UserSerializer(data=user, many=False) except User.DoesNotExist: return JsonResponse({'message': 'The user does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'POST': edited_user = JSONParser().parse(request) edited_user_serializer = UserSerializer(data=edited_user) if edited_user_serializer.is_valid(): for key in edited_user_serializer.data: user.key = edited_user_serializer.data[key] user.save() return JsonResponse({'edited': edited_user_serializer.data}, status=status.HTTP_200_OK) else: return JsonResponse({'error': "an error occured"}, status=status.HTTP_400_BAD_REQUEST) If I had done: user.username = "newusername" It would work, but inside this for loop it doesn't Thank you for your help ! .