Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : Chunck queryset about 1000 object for update
I have about 50000 data in this object for update I need to chunck in at 1000 at a time instance_list = Stock.objects.filter( status=Status.ACTIVE, organization=self.request.user.organization, **stock_specific_attribute_filter(self.request.GET), ) -
How to log data to database in Django without html redirect
I have been attempting a difficult task with django and I am curious if I am thinking about the nature of the beast in the correct way, and if so if anybody could provide guidance in understanding how to achieve the goal I am hoping to accomplish. I am attempting to create a webapp that can log information without redirecting the url. I have created a small django project which demonstrates a similar task in a much simpler way. Here is the html page that is included in the http reponse to loading the index page. <p>The purpose of this is to log moments we like in the video</p> {% load static %} <video id="myVideo" width="320" height="240" controls> <source src={% static some/static/movie/path.mp4 %} type="video/mp4"> Your browser does not support the video tag. </video> <button onclick="getTime('goodMoment')">Click Here to Mark Time of awesome moment</button> <p id = "goodMoment"></p> <p> Now I would like to log the string that was posted to "goodMoment" as the "time_string" field for a new instance of the model "SavedTime"</p> <p> however, it is important that there is no http response to take us away from this page, because the video needs to continue playing</p> {% load static … -
recommendation required for buidling a new app
I am very new to programming and am after some advice. At work, we run a soccer score predictor whereby each person enters a score for all the games and gets 3 points for a correct score and 1 point if they get the result correct but not the score. It is a very manual process of inputting scores into Excel and getting results, so I want to build an app. I've done a small amount of work with Django and Python in the past. Does anyone care to recommend a language that would be best suited for this task? Thanks -
Docker run /build in CI with different settings file for test stage
I had gitlab-ci.yml that runs postgres container and then builds a web container. The web container has setting.py with DATABASES setup. .gitlab-ci.yml : ... test: stage: test script: - docker run --name db -d postgres:9.6 - docker build --pull -t test_image . - docker run --name myweb ...blah-blah ... setting.py .... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbname', 'USER': 'dbuser', 'PASSWORD': 'dbpassword', 'HOST': 'db', 'PORT': '5432', #or nothing, worked either way } } .... All that worked fine until some recent changes. The changes were: DATABASE section was moved out of settings.py into postgres.py (in the same directory withg settings.py) with hard-coded values replaced with os.environ.get('SOME VAR') calls and settings.py is now imported into postgres.py: postgres.py from <mywebapp>.settings.settings import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('DB_NAME', ''), 'USER': os.environ.get('DB_USER', ''), 'PASSWORD': os.environ.get('DB_PASS', ''), 'HOST': os.environ.get('DB_HOST', ''), 'PORT': '5432', } } Obviously, that does not agree with the docker which now can not find any of the DB config vars ('ENGINE', 'NAME', etc) and I got to fix it. The error is relatively descriptive (from - docker build --pull -t test_image ., not from "- docker run ..."): django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the … -
Queryset difference based on one field
I am trying to compare two querysets based on a single field. But I can't figure out most efficient way to do it. This is my model and I want to check if old and new room_scans(ForeignKey) has PriceDatum's with the same checkin date. if not, create PriceDatum with that checkin date related to the new room_scan. class PriceDatum(models.Model): """ Stores a price for a date for a given currency for a given listingscan Multiple such PriceData objects for each day for next X months are created in each Frequent listing scan """ room_scan = models.ForeignKey(RoomScan, default=1, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) checkin = models.DateField(db_index=True, help_text="Check in date", null=True) checkout = models.DateField(db_index=True, help_text="checkout date", null=True) price = models.PositiveSmallIntegerField(help_text="Price in the currency stated") refund_status = models.CharField(max_length=100, default="N/A") # scanned = models.DateTimeField(db_index=True, help_text="Check in date", null=True) availability_count = models.PositiveSmallIntegerField(help_text="How many rooms are available for this price") max_people = models.PositiveSmallIntegerField(help_text="How many people can stay in the room for this price") meal = models.CharField(max_length=100, default="N/A", help_text="Tells if breakfast is included in room price") Below is the code what I am trying to do: previous_prices_final = previous_prices.filter(refund_status='refund', current_prices_final = current_prices.filter(refund_status='refund', max_people=max_people_count,meal=meal).order_by().order_by('checkin') if len(previous_prices_final) > len(current_prices_final): difference = previous_prices_final.difference(current_prices_final) for x in difference: PriceDatum.objects.create(room_scan=x.room_scan, room=x.room, checkin=x.checkin, … -
What is the best way to stream video from webcam or raspberry pi on a web application (using Django)?
Web application based on the human action recognition model, simply its purpose is to classify actions appear in a streaming video (webcam, raspberry pi .. ), how to do this using Django framework? -
How to change the queryset returned based on the URL
I am trying to make an educational site and have made a category system. There is a URL for each category and I need change the queryset returned based on the URL I am on. For example if I am on "localhost:8000/posts/category/3", I want my queryset returned to be: Post.objects.filter(category=3).order_by('-date_posted') And so one depending on the URL. I don't quite know where to start from for this. The class based view that returns the queryset: class CatPostListView(ListView): model = Post template_name = 'blog/science.html' #This is when you click a profile in a post, it takes you to his posts only context_object_name = 'posts' paginate_by = 15 def get_queryset(self): return Post.objects.filter(category=2).order_by('-date_posted') urls.py (Contains only the part necessary): urlpatterns = [ path('post/category/<int:pk>/', CatPostListView.as_view(), name='category') ] And just in case models.py: class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.SET_NULL) class Meta: # enforcing that there can not be two categories under a parent with same slug # __str__ method elaborated later in post. use __unicode__ in place of # __str__ if you are using python 2 unique_together = ('slug', 'parent',) verbose_name_plural = "categories" def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() category … -
Adding data to queryset in ModelViewSet
My ViewSet has two methods implemented: list() and get_queryset(). queryset operates on all objects of a model. It's used for filtering data without usage of DjangoFilterBackend. I'm interested in adding an extra field to the response when specific quantity of records is returned, e.g.: if len(queryset) > 1: resp = {"message": "Narrow down filter criteria."} elif len(queryset) == 0: resp = {"message": "No results found."} else: resp = {"message": "OK"} When I run the code, prints placed in list() and get_queryset() appear in the following order: 'list()' checking in... 'get_queryset() checking in... It seems that all changes applied in list() method are overwritten by get_queryset(). Otherwise, this answer would have helped. Is there any other way to return the queryset enriched by additional data, resp in this case? -
What is the best way to create referral links for my django web app?
I want to implement a referral system in my django web app, but i'm confused on how to go about it. What is the best way to implement a referral system whereby a user can share a link typically the signup page with his referral link. when the new user signs up, this will be recorded somewhere and when the new user creates takes certain actions on the site the user who invited him will get a bonus. -
Python Django ListView not calling get_queryset
Our group is trying to use the listview class to display all of the posts in a list format to the user in a news feed style. We created the ListView class with a valid 'template_name' and 'context_object_name'. Then, we implemented the get queryset to retrieve all of the posts from the db ('all()' method): class PostsView(generic.ListView): template_name = 'home.html' context_object_name = 'all_posts_list' def get_queryset(self): return Post.objects.all() However, this get_queryset method is not being run when we call the view. When I have built other apps in the past, the get_queryset was called automatically for my ListView objects, as it should according to the ListView documentation. Does anyone have any suggestions? -
DRF Nested Serializer
I am going to add products to my cart and as we know it is done by Product FK but it looks like this { "id": 1, "user": 1, "product": 1, "name": "iphone X", "price": "500.00", "quantity": 1, "total": 500 }, { "id": 2, "user": 1, "product": 2, "name": "Samsung", "price": "500.00", "quantity": 1, "total": 500 } as it can be seen user: 1 has two product and cart id is different the problem I am facing that is Order which should be taken from cart. class Order(models.Model): user = mo`enter code here`dels.ForeignKey(User, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) total_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) here I can place order for only one product but I do not want this because I have 2 products in my cart my serializer is like this class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ('user', 'cart', 'total_price', 'date_ordered') I want to place order for all products I have in my cart but I need help because please. I am new to Django. Any idea please how to solve this problem? Thank you! -
Best way to create user information table into two tables and connected with OneToOne relation
Please guide and suggest me the best way to solve this problem. I have a user information table: first: username, first_name, last_name, email, password [ provided by django ] Second: mobile, parent_id and other user profile related details [ want to create ] Goal: I want the second table with some fields and connect with the auth_user ( the name provided by django ) through OneToOne relation so I can fectch all the field through one object. What I have tried 1 case I created a second table and connect with FK relation and download all previous data from the previous DB and sperate data manually and uploaded through CSV into new tables. Problem: I cannot access both table data through a single object. 2nd case So I update the second table with OneToOne relation. Problem: add new users with this relation is perfectly fine but when trying to edit/ change previously saved data then got error error: invalid literal for int() with base 10 during change in models Note: Hundreds of user in the previous table, just safly migrate with new DB schema. Please, give me a tricky idea to fix this issue. Thanks to all. Kudos to the … -
The 'cover' attribute has no file associated with it. Django
I want to display person pictures in a table with their name and surname columns. When i put as source static it show pictures but when i send request to database it didn't show. And its already insert data and pictures to database and show picture in /media/images/some.jpg. view.py: def viewpost(request): person_list = Persona.objects.all() if request.method == 'POST': if request.POST.get('name') and request.POST.get('surname') and request.POST.get('address'): person = Persona() person.name = request.POST.get('name') person.surname = request.POST.get('surname') person.address = request.POST.get('address') person.age = request.POST.get('age') person.cover = request.FILES['cover'] person.save() return HttpResponseRedirect('/viewpost') else: return render(request, 'mysite/viewpost.html', {'persons': person_list}) model.py: class Persona(models.Model): name = models.CharField(max_length=255, unique=False) surname = models.CharField(max_length=255, unique=False) address = models.TextField() age = models.CharField(max_length=255, unique=False) cover = models.ImageField(upload_to='images/') and template: <td ><img src="{{person.cover.url}}" class="img-responsive" width="40px" id="pop" data-toggle="modal" data-target="#myModal"/></td> -
How to implement JWT auth in Django with custom endpoint?
I'm learning Django ecosystem and trying to figure out how to implement JWT authentication outside of "hello world" way provided by simplejwt library (trying to build realworld.io REST API). I can't understand how can I do that: should I use simplejwt library or pyjwt and create my custom authentication logic. For example, I want to be able to: POST /users and with { "email": "test@example.com", "password: "password" } and get result back { "email": "test@example.com", "password: "password", "token": <JWT_TOKEN_HERE> } and be able to authenticate myself by sending Authentication header with Bearer <JWT_TOKEN_HERE> https://github.com/davesque/django-rest-framework-simplejwt let's me create 2 endpoints with built-in functionality, but I want to customize it for my own. -
Custom Django Login Form Not Logging Users In
I am trying to create a login page for my webapp. I am able to log users in through the official admin page, but when I use my page the request.user is not logged in. def index(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if 'remember_me' in request.POST: request.session.set_expiry(1209600) # 2 weeks else: request.session.set_expiry(0) # Browser close login(request, user) return render(request, 'AllocationWebapp/browse.html', {}) else: print("Invalid login details: {0}, {1}".format(username, password)) return render(request, 'AllocationWebapp/browse.html', {'error': "Invalid login details supplied."}) else: return render(request, 'AllocationWebapp/login.html', {}) user is being set correctly, but after login request.user is still AnonymousUser and not logged in. -
My datatable has a datalist with several options how to export the selected option from the datalist to excel.thank you for your time in advance
My datatable has a datalist with several options how to export the selected option from the datalist to excel. thank you for your time in advance -
How to use AWS for free hosting of a web app (Docker, Nginx, Angular, Django)?
I am a total beginner and just completed the first version of my web application. I am using Docker, Nginx, Angular & Django. Note that the backend works on static files and uses a simple database for User Registration. I want to deploy it to a free, cloud solution. I heard that I can use AWS Elastic Beanstalk but found a bit complicated both the configuration and the pricing policy. Question Can anybody guide me through what to consider or even better, what selection I have to make in order to host my web app on AWS without a charge? PS: I don't know If I have to mention this, but in case the web app attracts a satisfying number of users, I would adjust the implementation in order the user to be able to upload and use my services upon their own data (and not upon the csv files). In this case, I might have to use other AWS services or migrate to another cloud solution. Just to say that both of them are welcome! -
if(x>2): print(x) but 1 is printed do you know why? (in python, django view)
code for sn in skil_note: if(sn.category.id > int(ca_num) & sn.category.id != 99): # ca num = 2 print("sn.category.id : ", sn.category.id) else: print("haha: " , sn.category.id) result Quit the server with CTRL-BREAK. ca_num : 2 sn.category.id : 89 sn.category.id : 89 sn.category.id : 89 sn.category.id : 1 sn.category.id : 1 haha: 2 haha: 2 haha: 2 haha: 2 haha: 2 sn.category.id : 3 sn.category.id : 3 sn.category.id : 3 sn.category.id : 3 sn.category.id : 3 sn.category.id : 3 sn.category.id : 5 sn.category.id : 5 sn.category.id : 5 sn.category.id : 6 sn.category.id : 6 sn.category.id : 6 sn.category.id : 6 sn.category.id : 6 sn.category.id : 6 sn.category.id : 6 sn.category.id : 6 sn.category.id : 6 sn.category.id : 8 sn.category.id : 8 sn.category.id : 1 sn.category.id : 10 sn.category.id : 10 sn.category.id : 10 If you know the reason, thanks 2> 1, but if you can tell me why 1 is output, thank you Is the if statement wrong? Should I compare in another way? Is there a problem with the format of the for or if statements? -
How to deal with KeyError: 'pk' in Django Formview
I'm trying to construct a form using Django FormView which will redirect me to page if the form is valid. I want to see a success message in a modal window after redirect. That did not work well as I'd get KeyError: 'pk' upon form submission. views.py: class ApplyView(FormView): template_name = 'vouchers/apply.html' model = Voucher voucher = None form_class = VoucherApplyForm def form_valid(self, form): self.code = form.cleaned_data['code'] now = timezone.now() Voucher.objects.filter(code__iexact=self.code, valid_from__lte=now, valid_to__gte=now, usage_limit=3, active=True) form.apply_voucher() return super(ApplyView, self).form_valid(form) def get_success_url(self): messages.add_message(self.request, messages.INFO, "Congratulations! You've successfully redeemed {{ voucher.value }} " "{{ voucher.get_type_display }} off the selected item(s).") return reverse('vouchers:apply', args=(self.kwargs['pk'],)) class VoucherDetailView(generic.DetailView): template_name = 'vouchers/detail.html' model = Voucher def get_context_data(self, **kwargs): context = super(VoucherDetailView, self).get_context_data(**kwargs) context['redemption_form'] = VoucherApplyForm(initial={'voucher':self.object}) return context urls.py: urlpatterns = [ path('<int:pk>/', views.VoucherDetailView.as_view(), name='detail'), path('<int:voucher_id>/apply/', views.ApplyView.as_view(), name='apply'), ] detail.html: <h1>Redeem your voucher!</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'vouchers:apply' voucher.id %}" method="post"> {{ redemption_form }} {% csrf_token %} <input type="submit" value="Apply"> </form> apply.html: {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class="{{ message.tags }}" {% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} And i ended up receiving error … -
How to store a list of string (tags or keywords) in a django model field?
I have these models: class Author(model): user = OneToOneField(CustomUser) other_filed = CharField(...) class Post(Model): author = ForeignKey(Author, on_del..) title = CharField(...) # keywords field to be inserted in a form and stored As already described, I need to field for the keyword related to each post written by an author. While I need something simple to avoid complexities, I prefer to be able to restrict the length of each keyword and the number of keywords. I have read Keywords Field in Django Model and What is the most efficient way to store a list in the Django models? and a few other articles but do not seem to be able to decide what should I do suppose I will find a way to store it. Why do I need it? At this stage, I only need to populate the keywords meta tag in the head part of the html of the page related to the article. I may, in the future, use these keywords to search and find an article. -
For loop only working in one template in django
I am trying to build an educational website and am trying to put all categories using for loops in a dropdown in the navbar. I have put it in base.html and all other templates extend base.html. But the items are only shown in the root page whose template is home.html. I have tried using passing multiple contexts to all posts. base.html: {% load static %} <!doctype html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> <title>{% block title %}ION{% endblock %}</title> </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'blog-home' %}">ION</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a> <a class="nav-item nav-link" href="{% url 'post-all' %}">Posts</a> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Categories</a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> {% for cate in cat %} <a class="dropdown-item" href="{% url 'category' cate.pk %}">{{ cate.name }}</a> {% endfor %} </div> </li> <a class="nav-item nav-link" href="{% url 'blog-about' %}">About</a> </div> <!-- Navbar … -
How to Fix UnboundLocalError at /signup/ in Django
I Wnat To Create A User Like Signup or register when i hit submit button i got this error: i want to signup user local variable 'usercustom' referenced before assignment Views.py def signup(request): registered = False if request.method == "POST": user_form = UserForm(request.POST or None) custom_form = UserCustom(request.POST or None) if user_form.is_valid() and custom_form.is_valid(): user = user_form.save(commit=False) user.save() custom = custom_form.save(commit=False) custom.user = user custom.save() registered = True else: print(user_form.errors,custom_form.errors) else: user_form = UserForm() usercustom = UserCustom() return render(request,'form.html',{'user_form':user_form,'usercustom':usercustom,'registered':registered}) Form.html {% extends "base.html" %} {% block body_block %} <div class="content-section"> {% if registerd %} <h1>Thank Your For registering!</h1> {% else %} <h1>Register Here</h1> <h3>Fill out the form</h3> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ user_form.as_p }} {{ usercustom.as_p }} <input type="submit" value="Register!" class="btn btn-danger"> </form> {% endif %} </div> {% endblock %} -
Unit testing a management command that uses a model derived from an abstract model class where the model is created for testing purposes only
I've created an abstract model class that can be used to create concrete models. Since I intend to put this in a separate django module to be re-usable, I don't have a concrete model in my package. I'm testing my abstract class AbstractBaseModel by dynamically creating a concrete model in my tests: class AbstractModelTestCase(TestCase): @classmethod def setUpClass(cls): class LocationTestModel(AbstractBaseModel): name = models.CharField(max_length=100) title = models.CharField(max_length=100, blank=True) num = models.IntegerField(default=0) try: with connection.schema_editor() as editor: editor.create_model(LocationTestModel) super(AbstractModelTestCase, cls).setUpClass() except ProgrammingError: pass cls.Location = LocationTestModel @classmethod def tearDownClass(cls): try: with connection.schema_editor() as editor: editor.delete_model(cls.Location) super(AbstractModelTestCase, cls).tearDownClass() except ProgrammingError: pass This works fine: In my test cases, self.Location is my test model and I can create and manipulate it as any other concrete model. Now I'd like to test a management command using call_command. My management command takes an app_label as argument and then looks for all the models in the app app_label, checking which models are sub-instances of my AbstractBaseModel, like this: def get_models_to_handle(self, app_label): try: app_to_handle = apps.get_app_config(app_label) except LookupError: app_to_handle = None models = [] if app_to_handle: app_models = app_to_handle.get_models() models.extend(model for model in app_models if issubclass(model, AbstractBaseModel)) return models The goal is to do something for each of these … -
How to return image URL as prefix https:// in Django Rest Framework?
My django Rest API return image URL path http://blah/media/blah.jpg. But I want to return https://blahblah. Is there any attribute in settings.py? CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') I Inserted this and tried SECURE_SSL_REDIRECT = True but it throws 301 code and nothing rendered. -
how to show step function in my integration project
I want to create a small project that can return the integration of user given input. but my main problem is that i want to show steps of that function. examples like in numpy or sympy.(they give the show steps button).