Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF get field from other serizalizer
I'm trying to solve my previous question : drf ordering by custom field and add ranking in to_representation My idea now is create an nullable field in model (db), so that I could try to store the custom field into the nuallable field and then sort it by nullable field in viewset not serizalizer. However how could I pass the value to this nullable empty field in serizalizer? the nullable field I define is weekly_score and here is the code: def get_weekly_score(self,instance): data = super().to_representation(instance) rankings = data.pop('rankings', None) result=0 if rankings: popscore_sum = 0 counter = 0 for value in rankings: for key, value in rankings[counter].items(): isFloat = isinstance(value, float) if isFloat: popscore_sum += value counter += 1 result = popscore_sum / counter return result However it give error Django:“RuntimeError: maximum recursion depth exceeded” -
Is something wrong with the password change page on Django admin?
Using Django 3.16, going into the admin console and managing a user (admin/auth/user/412/change/ in the example of user id 412), I attempt to change the user password by clicking on the link "you can change the password using this form". But when I click on the link I get the error "User with ID "412/password". It's like the URL settings aren't pulling the PK/ID out of the URL properly. (You'll see I'm using the Grappelli styling for the admin console. I've tested it without Grappelli and I get the same errors.) My urls.py has the usual line path('admin/', admin.site.urls). Is there some reason why this might be happening, or something I can do about it? thanks John -
Django custon form with validate
I have some problem with the form and Django. I would like to do a custom (in column and with style) form from a model. But after few hours to try I thinks it's not possible. So I decide to create not a forms.ModelForm but a forms.Form, in order to custom my form. But in this way i can't keep the validations... And last thing I try, it in the template file to write a validation manually, it's work but when I submit my form with error, and when it's refresh, all the data are loose, and I see just the error message... So it make me crazy... I just would like to do a nice form with django... Thanks in advance forms.py class PatienceForm(forms.ModelForm): class Meta: model = Patience fields = ('nom', 'prenom', 'age', 'email') template.html <form method="POST" accept-charset="utf-8"> {% csrf_token %} <p><label for="id_nom">Nom :</label> <input type="text" name="nom" maxlength="200" required id="id_nom"></p> <p><label for="id_prenom">Prenom :</label> <input type="text" name="prenom" maxlength="200" required id="id_prenom"></p> <p><label for="id_age">Age :</label> <input type="number" name="age" required id="id_age"></p> <p><label for="id_email">Email :</label> <input type="email" name="email" maxlength="254" required id="id_email"></p> {% for err in form.email.errors %} {{err}} {% endfor %} <button type="submit" class="save btn btn-default">Save</button> view.py def post_essaie(request): if request.method == "POST": … -
django class ListView is not displaying and data
I wanted to see how ListView class is working, but I couldn't display any data. I checked everything multiple times, but I can find my mistake. Any help is appreciated. view: class ViewListView(LoginRequiredMixin, ListView): template_name = 'realestateads.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['latest_realestate_ads'] = AdRealEstate.objects.order_by('-publish_date')[:5] return context HTML: {% if latest_realestate_ads %} {% for ad in latest_realestate_ads %} <!-- BLOCK POST --> <div id="div_block"> <a href="#" class = "post_hover" style = "width:100%;"> <div id="estate-posts-block"> <div class="estate-post-block-content"> <table> <tr> <td>Title</td> <td class = "par_space"><span>{{ ad.title }}</span></td> </tr> <tr> <td>Location</td> <td class = "par_space"><i class="fas fa-map-marker-alt"></i>&nbsp;<span class = "cont_space">{{ ad.address }}</span></td> </tr> <tr> <td>Contact</td> <td class = "par_space"><i class="fas fa-bed"></i><span class = "cont_space">{{ ad.phone}}</span></td> </tr> <tr> <td>Type</td> <td class = "par_space"><i class="fas fa-city">&nbsp;</i><span class = "cont_space">On Sale</span></td> </tr> </table> </div> </div> </a> </div> <!-- END BLOCK POST--> {% endfor %} {% else %} <p>No data</p> {% endif %} -
How to pass Django DateTimeField inside POST method of contact form
I create an contact-form using Django models. I added DateTimeField in my models.py file so that I can see the date-time when the contact-form was submitted. After added DateTimeField in my models.py. I am getting this error in admin panel when click on contact model: NOT NULL constraint failed: contact_contact.current_time and getting this error when clicking submit button: ['“” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] I run makemigrations and migrate after adding the DateTimeField in models.py and didn't get any error massage while running makemigrations and migrate. >>python manage.py makemigrations No changes detected >> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. #my models.py file from django.db import models import datetime # Create your models here. class Contact(models.Model): current_time = models.DateTimeField(blank=True, null=True,default=datetime.date.today) name =models.CharField(max_length=100) email =models.EmailField(max_length=100) message = models.TextField(max_length=2000) #my forms.py file from django.forms import ModelForm from .models import Contact class ContactForm(ModelForm): class Meta: model = Contact fields = ['name','email','message',] def clean(self): # data from the form is fetched using super function super(ContactForm, self).clean() # extract the username and text field from the data name = self.cleaned_data.get('name') if len(name) < 5: self._errors['username'] = … -
PWA - Cannot log out
I am unable to logout in a web application due to caching via service worker, how may I solve this? I have tried ignoring certain pages for caching but that does not seem to work. I am not sure what to do. -
How can I run an async function from a django view to run in the background while I process requests in the main loop?
As I said in the title, I want a task to run in the background processing a large database query while I handle requests from my frontend. Can I even do that with async/asyncio? I was told it was possible... For the purpose of context, I would like to do something like the following. Note also that I don't really need the function to tell me when it's done (though I'd sure like to know if it's possible) since I just check if the .json file was finally written. def post_data_view(request): if request.method == 'POST': ... do_long_query_in_the_background(some_data) return HttpResponse('Received. Ask me in a while if I finished.') def is_it_done_view(request): if request.method == 'GET': data = find_json() if data: return JsonResponse(data) else: return HttpResponse('Not yet dude...') async def do_long_query_in_the_background(data): # do some long processing... # dump the result to a result.json return I was told this was possible with async but I really find it hard to understand. For context, I tried to simplify this a lot, and even then I found I didn't quite understand what was happening: async def f(): while True: print(0) await asyncio.sleep(2) asyncio.create_task(f()) even this code I tried fails sys:1: RuntimeWarning: coroutine 'f' was never awaited, … -
python socketio - open packet not returned by the server
I am trying to connect to a socket server (node.js) say http://localhost:4300. On the server side it has been successfully connected, on my server's log client connected {client_id} but on my client side (python-socketio client) it returns exceptions OPEN Packet not returned by the server Could anyone please help me explain why I got this exceptions? I have been doing what the docs said. -
" Django " category in div id
Hi I have to use Python and Django for our application. I get categories slugs for div id but not working What do you think? I put the required code at the bottom. view.py def my_grouper(n, iterable): args = [iter(iterable)] * n return ([e for e in t if e is not None] for t in itertools.zip_longest(*args)) def home_page(request): sliders = Sliders.objects.get_active_slider().first() projects = Projects.objects.get_active_projects() projects_category = ProjectsCategory.objects.get_active_projects_category() grouped_projects = list(my_grouper(4, projects)) context = { 'slider': sliders, 'projects': grouped_projects, 'projects_category': projects_category } return render(request, 'tarahan/home-page.html', context) list category template {% for category in projects_category %} <li class="p-tab-btn" data-tab="#{{ category.slug }}">{{ category.title }}</li> {% endfor %} for loop for get item {% for project_list in projects %} <div class="p-tab" id="{% for project in project_list %}{{ project.categories.first.slug }}{% endfor %}"> <div class="project-carousel owl-theme owl-carousel"> <!--Gallery Item--> {% for project in project_list %} <div class="gallery-item"> <div class="inner-box"> <figure class="image-box"><img src="{{ project.image.url }}" alt="{{ project.categories.first.slug }}"> </figure> <!--Overlay Box--> <div class="overlay-box"> <div class="overlay-inner"> <div class="content"> <a href="{{ project.image.url }}" class="lightbox-image image-link" data-fancybox-group="example-gallery" title=""><span class="icon fa fa-expand"></span></a> <a href="{{ project.get_url }}" class="image-link"><span class="icon fa fa-link"></span></a> </div> </div> </div> </div> </div> {% endfor %} </div> </div> {% endfor %} thanks -
i am getting a Python Error: list index out of range
i am trying to loop through a 2d array to append the first item to a different list. When i try to loop through and append it gives an error. error: list index out of range here is the code #there is a loop that creates a 2d array that goes like this [[object, int], [object, int], [object, int]] sorted_list = sorted(temp_list, key=lambda x: x[1], reverse=True) #the above code sorts this list by the second value in the inner arrays of the 2d array for x in sorted_list: y = x[0] post_list.append(y) #the above code loops through the sorted list and should append the first value of each inner list #to the list post_list note that if i change the loop to: for x in sorted_list: print(x[0]) then it doesn't give an error, it just outputs this object object object why am i getting the out of range error? -
REST API versioning pattern guide
I am writing huge Rest API, to make it easily discoverable, i am making the pattern like this way. http://127.0.0.1:8000/membership/api/v1/make-a-payment But i notice poeple used to make the pattern like this way: http://127.0.0.1:8000/ap/v1/blabla Can you anyone tell me what is the best practice? is it ok writing pattern like this way? http://127.0.0.1:8000/membership/api/v1/make-a-payment ? I just trying to make it easily discoverable by swegger docs. What is your opinion? -
DRF Update price of a product via Viewset Interface
My model for this is straight simple, but I fail to create a "handsome" interface on the ViewSet Template: class Product(models.Model): id = models.PositiveIntegerField(unique = True) price = models.DecimalField(Price, default = 0) name = models.CharField("name", max_length = 128) I created a serializer: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["id", "name", "price"] and I added a ViewSet: class LoadPageViewSet(viewsets.ViewSet): serializer_class = ProductSerializer http_methods = ["get", "put"] def list(self, request): query = Product.objects.all() results = ProductSerializer(data = query, many = True) results.is_valid() return Response(data = results.data, status = status.HTTP_200_OK) def put(self, request): serializer = LoadPageSerializer(data = request.data) if serializer.is_valid(): P = Product.objects.get(id = request.data["id"]) P.price = request.data["price"] P.save() return Response(serializer.data, status = status.HTTP_200_OK) return return Response(serializer.data, status = status.HTTP_400_BAD_REQUEST) If I execute this, when I choose a new price I run into the unique constraint of the id field: product with this id already exists.. -
Setting Djando field default value based on another field
I am creating a Django model where: expirationTimeStamp field's default value is based on creationTimeStamp isLive boolean field value is based on expirationTimeStamp I have written the following functions expirationTimeCalculation and postLiveStatus and assigned them as default values to the fields but I am getting error. I have also tried to assign to respective fields through property(function) yet I am still getting error. One of the functionality that I need to implement is that user can send custom expirationTimeStamp as well that would override default value, therefore, I believe property(function) assignment is not ideal for expirationTimeStamp field. Is there any other way that I can go about to set the expirationTimeStamp field value based on creationTimeStamp field? Any feedback is appreciated! class Posts(models.Model): def expirationTimeCalculation(self): EXPIRATION_DURATION = 86400 #time in seconds expirationTime = self.creationTimestamp + timedelta(seconds = EXPIRATION_DURATION) return expirationTime def postLiveStatus(self): return (self.expirationTimestamp > timezone.now) message = models.TextField() creationTimestamp = models.DateTimeField(default=timezone.now) expirationTimestamp = models.DateTimeField(default=expirationTimeCalculation) isLive = models.BooleanField(default=postLiveStatus) -
testdriven.io Tutorial broke: Dockerizing Django with Postgres, Gunicorn, and Nginx
https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/ Learning Fullstack. Have done a little Docker, a lot of python, but no NGINX stuff. 60% through this tutorial I am failing at the end of NGINX section. The Nginx container builds and starts with the other two but stops immediately. And I of'course get a 404 on the localhost and port specified. Just to eliminate any screwy localhost issues on my Mac, I ran an Nginx container directly from the Docker command.... docker run -p 80:80 nginx It ran fine. No so with my tutorial project. The project is literally bog standard from the tut, but here are some specifics. docker-compose.prod.yml: version: '3.7' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn hello_django.wsgi:application --bind 0.0.0.0:8000 expose: - 8000 env_file: - ./.env.prod depends_on: - db nginx: build: ./nginx ports: - 1337:80 depends_on: - web db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db volumes: postgres_data: nginx/Dockerfile - FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d nginx/nginx.conf upstream hello_django { server web:8000; } server { listen 80; location / { proxy_pass http://hello_django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } -
DRF ViewSet: Change appearance of field
I have a model like this: ## model: class Product(models.Model): id = models.PositiveIntegerField(unique = True) price = models.ForeignKey(Price, on_delete = models.CASCADE, null = True, blank = True) ## serializer: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["id", "price",] which shows up in the template of the API like this: I get, this is because of the nature of the model field type. Two questions here: Can I get rid of the little arrows somehow and make a normal field? Could I somehow return a list of all Product ids like for the price? Something like ids = Product.objects.values_list("id", flat = True) or so? -
Django Blog, Only Update Publish Date if not Already Published
So I've built a very basic blog in Django. I have been working on adding a new feature allowing me to save a new post as a draft to publish later, or to unpublish an already published post. I'm fairly new to Django/Python, so perhaps I'm making a novice mistake here. To achieve this, I've added two fields to my Post model. A BooleanField named published and a DateTimeField named publish_date. I only ever want publish_date to update when publish is set to True & was previously False. The approach I've taken is to override the save() method of my Post model. Within the method, I am either setting publish_date to None (if published is unchecked on the form) or I am setting publish_date to timezone.now() (if published is checked on the form). This approach is okay, although publish_date will be updated everytime the post is updated, even if it has not been unpublished/republished. This cannot happen. I'm still learning about the interactions between views, models, and forms, so I really appreciate any guidance. Please take a look at all relevant code and let me know of a better approach to solving this. Thank you for your help! models.py class … -
'str' object has no attribute 'match_key' when sorting dictionary
Full error: 'str' object has no attribute 'match_key' I am trying to sort a dictionary by the values of one of the keys in the objects but I am running into errors whem doing so. What is the best way to do this kind of sort? Code: x = { 'id': f'{item.id}', 'post': item, 'match_key': match_percentage } temp_dict.update(x) sorted_dict = sorted(temp_dict, key=operator.attrgetter('match_key')) -
How do you add a text placeholder without changing the model to a form?
So this this post shows how you would use a placeholder for a textfield if you wanted to change the model to a form. But if I want to keep the model as a model so that I don't need to write a form, how can I add a placeholder in the textbox that disappears when the user clicks it? Here's my current model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) firstName = models.CharField(max_length = 25, null=False, blank=False, default="Enter your first name") I want to switch default to blank and add "Enter your first name" as a placeholder so the user doesn't need to delete the text when he or she wants to fill in the information. However, I don't want to turn it into a form. -
How can I automatically add a Django command to each log?
Right now I have a Django command named log_test. class Command(BaseCommand): help = '' def handle(self, *args, **options): logging.info("This is a log test") My log formatter looks like this 'formatters': { 'standard': { 'format': '%(message)s [%(request_id)s]{%(user_id)s}' }, }, So when I run python manage.py log_test the above function will log This is a log test [abc]{12} I would like to update this so that the log reads This is a log test [abc]{12} script=log_test Is there an easy way to do this using Django? In summary want each log that originated from a Django command to also log the name of the Django command. -
Django forgot password email giving invalid token on Mac and iPad
I have a Django application running on a Windows server. I have used the "Forgot Password" option numerous times without a problem. A user complained that on a Mac using Firefox, she got an invalid token when she clicked on the link in the password reset email. I could not duplicate it on my Windows PC using Chrome or Firefox. However, I tried it on an iPad, and I got the same behavior as she (I don't have a Mac to try). I tried it several times with the same result. The link in the email that I send looks like this: https://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} I opened the same email from my Windows PC, and that link in my password reset email worked without a hitch (it generates a reset page with the address "https://myserver.com/reset/MTE/set-password/"). My ipad gets to the same page, but with an invalid token. Does anyone know what might be going on here and how to fix it? Thanks-- Al -
Django Static Image Not Serving
I have a simple django app I am trying to build and I am trying to display an image on the front page. When i load the front page the image is not there. But when i go directly to the image url it shows just fine. I have been following the django documentation and I can not seem to solve this issue. My site structure is like this Main Dir -app -website -static --images Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ('/path/to/static/root/directory/',) DIRNAME = os.path.dirname(__file__) STATIC_ROOT = os.path.join(DIRNAME, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] base.html {% load static %} <div class="parallax"><img src="{% static 'images/frontbannar.jpg' %}" alt="Unsplashed background img 1"></div> I have also run this command and it did not work. python manage.py collectstatic -
Javascript undifined error while using dataset with django templates
I get undefined error while using JS dataset to try to get data from a django template i cant fix it, can anyone provide a solution. The index.html template <div id="currentUser1" data-currentUser="1"></div> For the JS code document.addEventListener('DOMContentLoaded', function(){ let currentuser2 = document.querySelector('#currentUser1').dataset.currentUser; console.log(currentuser2) }); The out on the browser undefined network.js:4:13 Thats the error I get, and as for the console everything is okay with no errors. -
Is it possible to reset a password without a token? django + react
Could I reset a password for a user without a token , which (ithink) would require sending a link via a email to a users email address (I'm not sure if django or react have that functionality) So could I rewrite their password data with a axios post request if I had most details of their account like username,email,user_id. -
error while trying to run Unittest with PostgreSQL db inside docker container
I have this Django app which runs inside Docker. I am trying to run some test on a script. I run this command below but receive the following error: any idea? iam new to docker and postgresql and django as well.. docker-compose run web sh -c "python manage.py test test test.unit.enrollments.test_views.MyAPIViewTestCase.test_id" =========================================================== ERROR: test.unit.transactions.test_views (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: test.unit.transactions.test_views Traceback (most recent call last): File "/usr/local/lib/python3.5/unittest/loader.py", line 428, in _find_test_path module = self._get_module_from_name(name) File "/usr/local/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name __import__(name) File "/opt/app/test/unit/transactions/test_views.py", line 15, in <module> from test.unit.transactions.view_testing_utils import ViewTestingUtils File "/opt/app/test/unit/transactions/view_testing_utils.py", line 9, in <module> from test.unit.groups.view_testing_utils import ViewTestingUtils as SharedViewTestingUtils File "/opt/app/test/unit/groups/view_testing_utils.py", line 27, in <module> class ViewTestingUtils: File "/opt/app/test/unit/groups/view_testing_utils.py", line 169, in ViewTestingUtils status=LargeGroupGroupStatus.IN_PROGRESS.value, File "/usr/local/lib/python3.5/enum.py", line 274, in __getattr__ raise AttributeError(name) from None AttributeError: IN_PROGRESS ---------------------------------------------------------------------- Ran 138 tests in -70489110.777s FAILED (errors=168, skipped=8) Destroying test database for alias 'celery'... ERROR: 1 -
AWS Elastic Beanstalk Deployment Error: 502 Bad Gateway - Django Application
I am having problems deploying my 1st python django app to AWS Elastic Beanstalk. The app appears to upload correctly but when I try to use it I get 502 Bad Gateway. The logs show the following: *2021/03/25 20:14:53 [error] 5144#0: 357 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.8.43, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "crap-env.eba-2nhwp4ty.us-west-2.elasticbeanstalk.com" Would appreciate any help.