Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having django select the right option for a html select tag
I have a template in django that is a pretty simple table that loads up based on the list passed into it from the view. a snippet of the HTML code: {% for hou in bookings_list %} <tr value={{hou.pk}}> <td><a href="mailto:{{hou.user.user.email}}"> {{ hou.user.user.first_name }} {{ hou.user.user.last_name }}</a></td> <td> <select id="room_number" name={{hou.pk}} class="select form-control"> <option value=-1 id=-1> ------ </option> {% for room in room_list %} <option value={{room.id}} id={{hou.pk}}>{{ room.room_name }}</option> {% endfor %} </select> </td> <td> .. more stuff ..</td> </tr> {% endfor %} (bookings_list is a list of bookings for housing that the user has booked (includes room they are assigned to unless no one assigned them a room from a new booking so it is NULL), the room list is a list of all possible rooms for the person in charge to select to assign to a user via the booking) I have ajax working with a jquery change call that when the select is selected it gives the room_id to what ever room.id was selected on the front end and saves the record in the view. But if I reload this page, the ------ always shows up. I know I have to figure out how to set the … -
How would you model this in Django?
I want to upload a list of companies to my web app and then run some long background scripts on each company (ie. Webscraping). Each upload will be essentially be a batch task. I suspect I will probably need to queue these batch processes with something like Redis or Celery, though I am not sure because the batch should start immediately after being being submitted. I am mainly having trouble figuring out how to create my Models for this logic. So any help there would be greatly appreciated. Right now I've set up a Company model and a Batch model. I'm unsure on how to link these models together appropriately so I can sum up the number of employees from each company in a batch. Please reference these pictures for visual details. -
Display different content based on Boolean
I want to allow only manager to create view a content on my website, So I added an entry to my model "Profile" manager = models.BooleanField(default=False) By default is false If false the user cannot see the content. So I tried : {% if profile == manager %} SHOW THE CONTENT {%else%} Does not show the content {% endif %} But nothing change. What did I do wrong ? -
Get Topics ordered by recent Entries
Suppose that I have models: class Entry(models.Model): topic = models.ForeignKey(Topic) date_created = models.DateTimeField() class Topic(models.Model): title = models.CharField(max_length=100) I want to create a queryset that returns Topics which has Entries whose creation date is in last 24 hours. Topics should be ordered so that the first topic has the latest Entry. I tried this with Postgres, but the ordering is lost: Topic.objects.filter(entry_set__date_created__gte=timezone.now() - datetime.timedelta(hours=24))\ .order_by('entry_set__topic', '-entry_set__date_created').distinct('entry_set__topic') I found a solution to a similar problem but it is written in raw sql, and I couldn't convert it to django-orm. -
Annotate existing model objects in Django
Is there a way to use something like Django's annotate method, but for a collection of existing model instances instead of a queryset? Say I have a model like this (all irrelevant details removed): class Node(Model): parent = ForeignKey('self', related_name='children') If I were fetching some nodes and wanted the child count for each one, I could do this: nodes = Node.objects.filter(some_filter=True).annotate(child_count=Count('children')) for node in nodes: print(node.child_count) But what if I already have a collection of Node objects, instead of a queryset? I essentially want the annotation equivalent of prefetch_related_objects. I'm picturing something like this: nodes = list(Node.objects.filter(some_filter=True)) annotate_objects(nodes, child_count=Count('children')) for node in nodes: print(node.child_count) Is there anything like this built into Django? Digging through the docs has not been fruitful for me. -
Django problem with loading CSS and/or JS
Hello, I've got a project to do and I've been wanting to implement CSS and JS to my Django project WITHOUT using Bootstrap. And as you can see I have personal_portfolio/static/css/navbar.css But when I load static files and use the tag inside my base.html the page doesn't apply my stylesheet. I do not understand why ! Whereas when I use bootstrap I have no problem ! I've been wanting to use only CSS and JS cause I want to learn those as well and the project I have requires me to do it myself and not use Bootstrap. Thanks a lot, I hope you all can help me ! -
Django serializer: required_fields
Is it possible to set required fields as a list inside serializer? I don't wont to determine each field with other line like this: name = serializers.CharField(read_only=True) description = serializers.CharField(read_only=True) date_start = serializers.DateTimeField(read_only=True) date_end = serializers.DateTimeField(read_only=True) I expect next behavior: class CampaignStepFirstSerializer(serializers.ModelSerializer): class Meta: model = Campaign fields = ( 'name', 'description', 'date_start', 'date_end', ) required_fields = fields -
Django request.user gives Anonymous in the response view after callback from payment gateway
Payment gateway (3rd party website) sends post data to a callback url (my website) which can be accessed using request.POST But request.user gives Anonymous in the response view. On adding decorator @login_required to the view, request.POST becomes empty but request.user returns authenticathed user. I need to access both request.user and request.POST form data at the same time to save transaction into database. # @login_required def response(request): if request.method == "POST": MERCHANT_KEY = settings.MERCHANT_KEY data_dict = {} for key in request.POST: if request.POST[key]: data_dict[key] = int(request.POST[key]) PaymentHistory.objects.create(user=request.user, **data_dict) return render(request, "response.html", {"paytm": data_dict}) return HttpResponse(status=200) -
Reference name from Django database, NOT the id
I am sending an email with object ID in a model, but I want to send the object names. I have two models: class Uniform(models.Model): category = models.CharField(max_length = 50) description = models.CharField(max_length = 50) price = models.FloatField(max_length = 6) size = models.CharField(max_length = 10) def __str__(self): return '{}: {} - {} - ${}'.format(self.category, self.description, self.size, self.price) class Transaction(models.Model): employee_id = models.ForeignKey(Employee, on_delete = models.PROTECT) uniform = models.ForeignKey(Uniform, on_delete = models.CASCADE) date = models.DateTimeField(default=timezone.now) def __str__(self): return '{}: {} - {}'.format(self.employee_id, self.uniform, str(self.date)) And forms.py class TransactionForm(forms.ModelForm): class Meta(): model = Transaction fields = '__all__' My Views.py def employeeCloset(request): form = TransactionForm() if request.method == 'POST': form = TransactionForm(request.POST) if form.is_valid(): subject = 'Checked out item from Me' message = 'It is the responsibility of the team member to maintain all articles identified so that they are presentable and worn upon arriving according to standards required in the Employee Handbook. I understand I will be charged the deposit according to the cost identified below: \n {} \n These costs will be deducted from the team member’s paycheck and will be credited upon return of article(s). \n Any item that is not returned by the end of the pay period the … -
Add multiple entries to a database in one post using charfield
I am building a todo app and for now people can only add one "task" at the time. I would like to allow user to have multiple text area (5 for example) and so they can add multiple tasks in one post. As you can see on the picture, only one input is available, I cannot add more than that without error. I thought that maybe I could add multiple charfield in my model "todo" but that seem ugly. -
Scrape code from website with python and beautiful soup
My project is about scraping 5 shopping websites. I found useful data from StackOverflow and from youtube. But I am stuck on one website. one div class used style display, none and hidden visibility after that all div classes are hidden. I tried to use ajax, google chrome extension for javascript, and applied different methods which I applied on the other 4 but this website is bit hard for me. If someone helps me to read those tags so that I can scrape data from a website. Website URL is : Website currently, I am using simple code for parse. here is the code which I used. y = requests.get(url) soup = BeautifulSoup(y.text, "html.parser") products = soup.find('div', class_='container min-w1170') products = products.find('div', class_='row mgt25') print(products) products = products.find_all("div", class_="findify-components-common--grid__column findify-components-common--grid__column-6") print(products) until first print, all div classes are working but after that, I am unable to find data from next div classes. -
How can I run a function after a user gets registered Django
I am developing a server using Django and wanted when a user registered to run a function that would create a directory with the username. The folder with the new user name will be saved in Collections. My code is as follows: Models.py from django.db import models from django.contrib.auth.models import (BaseUserManager,AbstractBaseUser) class UserManager(BaseUserManager): def create_user(self, username, first_name, last_name, email, password=None): """ Creates and saves a user with the given variables and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, first_name, last_name, email, password=None, is_admin=True): """ Creates and saves a superuser with the given variables and password. """ user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, is_admin = is_admin, ) user.set_password(password) user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True) username = models.CharField(max_length=255, unique=True) first_name = models.CharField(max_length=100, unique=False) last_name = models.CharField(max_length=100, unique=False) is_active = models.BooleanField(default=True, unique=False) is_admin = models.BooleanField(default=False, unique=False) user_collection = models.CharField(max_length=500, default='NotCreated', unique=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name', 'last_name', 'email'] def __str__(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin Directory images Is there … -
Jquery selector returns the same class
I have written a dynamic page which loads the products from the context object. the number of products in the object, number of times the loop will run and i have created a hidden input. in each iteration the value of hidden input will be the primary key of the product. but when i use jquery to fetch the value of clicked product, the id of first product is returned. Any product i click only the first products id is been returned. {% for album in list1 %} <div class="col-lg-3" id="div1"> <div class="card" style="width: 20rem;"> <input type="hidden" class="custId" value={{ album.id }}> {{ album.product_name }} Category : {{ album.product_category }} Price : {{album.id }} $('.k').click(function(){ var a = $('.custId').val(); alert(a); console.log(a) }); -
how to get userId from token in django
I create API in django with django-rest-framework. I have a model called Comment, and each Comment has a UserId. I am creating the users by rest-auth. Each User has a token which I use on frontend. from django.db import models import uuid from django.utils.timezone import now from django.contrib.auth.models import User class Comment(models.Model): CommentId= models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) DataCreated = models.DateField(default=now, editable=False) UserId = models.ForeignKey(User, on_delete=models.CASCADE, default=uuid.uuid4, editable=False) Name = models.CharField(max_length=120, default="") class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('CommentId', 'DataCreated', 'UserId', 'Name') I create a simpre view which save new Comment @api_view(['POST']) def addComment(request): serializer = CommentSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The point is that in request.data I receive data like Name and Token and not UserId, so I am wondering how to get UserId from Token? -
Django migrations with multipule databases
I have a django projects that has 2 apps and each app runs on a different DB (lets call them default and DB2). I have created a router to manage the data and added the router to my settings.py When I run migrate I get Applying analytics.0001_initial... OK but in the default DB the only thing that gets updated is the django_migrations table showing that the app analytics has been migrated with 0001, and in the DB2 the table itself isn’t even created at all. Going to the django shell and trying to do obj.objects.all() gives me table DB2.table_name does not exist I also verified in sql DB2 exists but doesn’t have any table from what I created My router: class DB2Router(object): """ A router for apps that connect directly to the DB2 database. This router allows apps to directly update the DB2 database rather than using raw SQL as in the past. The router forces the use of the DB2 database for any app in the "apps" list. """ db = "DB2" apps = ["analytics"] def db_for_read(self, model, **hints): if model._meta.app_label in self.apps: return self.db return None def db_for_write(self, model, **hints): if model._meta.app_label in self.apps: return self.db return None … -
Javascript Counter up on HTML span tag element using jquery.counterup.min.js doesn't work
So I am currently developping a Django app, and I amy trying to set up a counter to display a given integer on the main page. Here is the javascript stuff I load on my HTML template (that is not the entire file): <script type="text/javascript" src="{% static 'EpiDB/jquery-3.2.0.min.js' %}"> </script> <script type="text/javascript" src="{% static 'EpiDB/jquery.tablesorter.min.js' %}"> </script> <script type="text/javascript"> $(document).ready(function() { $("#annotable").tablesorter(); } ); </script> <script type="text/javascript" src="{% static 'EpiDB/jquery.searchable-1.0.0.min.js' %}"> </script> <script type="text/javascript"> $(function () { $( '#annotable' ).searchable({ searchField: '#annotsearch', striped: true, oddRow: { 'background-color': '#e2e9f3' }, evenRow: { 'background-color': '#ffffff' }, searchType: 'fuzzy' }) }); </script> <!-- popper js --> <script src="{% static 'EpiDB/popper.min.js' %}"></script> <!-- bootstrap js --> <script src="{% static 'EpiDB/bootstrap.min.js' %}"></script> <!-- easing js --> <script src="{% static 'EpiDB/jquery.magnific-popup.js' %}"></script> <!-- swiper js --> <script src="{% static 'EpiDB/swiper.min.js' %}"></script> <!-- swiper js --> <script src="{% static 'EpiDB/masonry.pkgd.js' %}"></script> <!-- particles js --> <script src="{% static 'EpiDB/owl.carousel.min.js' %}"></script> <script src="{% static 'EpiDB/jquery.nice-select.min.js' %}"></script> <!-- swiper js --> <script src="{% static 'EpiDB/slick.min.js' %}"></script> <script src="{% static 'EpiDB/waypoints.min.js' %}"></script> <script src="{% static 'EpiDB/jquery.counterup.min.js' %}"></script> All content of my page using the other javascripts is working fine except the counter up. So I read bit about the way … -
Migration of local Django project to pythonanywhere throws incorrect timezone error when running manage.py
I have a local Django project that runs fine. I am following the instructions from pythonanywhere (https://help.pythonanywhere.com/pages/DeployExistingDjangoProject/). I set up a virtualenv and made sure my Django versions match. When I get to the point of running ./manage.py migrate I get a permission denied error: bash: ./manage.py: Permission denied If I instead try to run python3 manage.py migrate I get a timezone setting error Bash console output (Tooling-virtualenv) 09:31 ~/Tooling/Tooling (master)$ python3 manage.py migrate Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/username/.virtualenvs/Tooling-virtualenv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/username/.virtualenvs/Tooling-virtualenv/lib/python3.7/site-packages/django/core/management/__init__.py", line 325, in execute settings.INSTALLED_APPS File "/home/username/.virtualenvs/Tooling-virtualenv/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/home/username/.virtualenvs/Tooling-virtualenv/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/home/username/.virtualenvs/Tooling-virtualenv/lib/python3.7/site-packages/django/conf/__init__.py", line 189, in __init__ raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE) ValueError: Incorrect timezone setting: America\Los_Angeles pythonanywhere error log 2019-11-26 01:20:11,190: Error running WSGI application 2019-11-26 01:20:11,200: ValueError: Incorrect timezone setting: America\Los_Angeles 2019-11-26 01:20:11,200: File "/var/www/username_pythonanywhere_com_wsgi.py", line 54, in <module> 2019-11-26 01:20:11,200: application = get_wsgi_application() 2019-11-26 01:20:11,200: 2019-11-26 01:20:11,200: File "/home/username/.virtualenvs/Tooling-virtualenv/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2019-11-26 01:20:11,200: django.setup(set_prefix=False) 2019-11-26 01:20:11,201: 2019-11-26 01:20:11,201: File "/home/username/.virtualenvs/Tooling-virtualenv/lib/python3.7/site-packages/django/__init__.py", line 19, in setup 2019-11-26 01:20:11,201: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2019-11-26 01:20:11,201: 2019-11-26 … -
Use object attribute in URL pattern in Django
In my Django app, I essentially have Locations and Bookings, where Bookings are created by a user and assigned to a Location. I now wrote a view that is supposed to list all Bookings created by a certain user (independent of location). However, I cannot get the URL pattern to work since it seems like I cannot use an attribute of the user object in my urlpattern. Is my approach just not working or am I overlooking something? Request Method: GET Request URL: http://127.0.0.1:8000/bookings/user/aaaaaaaa/ Django Version: 2.2.5 Exception Type: TypeError Exception Value: booking_list_user() got an unexpected keyword argument 'url_short' My code: views.py def booking_list_user(request, user): bookings = Booking.objects.get(requested_by=user) return render(request, 'booking_list.html', {'bookings': bookings, 'user': user}) models.py class Booking(models.Model): requested_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='booking_requested_by', on_delete=models.SET('--user deleted--')) location = models.ForeignKey(Location, related_name='booking_location', on_delete=models.CASCADE) ... urls.py urlpatterns = [ path('all/', booking_list_all, name='booking_list_all'), path('user/<user.url_short>/', booking_list_user, name='booking_list_user'), path('<slug>/new/', booking_add, name='booking_add'), path('<url_short>/', booking_view, name='booking_view'), ] -
how do i get the body info from django using a http post request
i am doing a http request to a django server using dart Future getImage() async { http.Response response = await http.post("http://127.0.0.1:8000", body: "hi"); print(asd.statusCode); print(encoded); print(asd.body); setState(() { _image = image; }); } and i want to acces the body data in django @csrf_exempt def getimage(request): if request.method == 'POST': response_data=request.body return HttpResponse(json.dumps(response_data), content_type="application/json") -
Why do I get an http 203 status in test django?
I am using TestCase in Django, sometimes the tests fall because the petition gets a response with a status HTTP 203. I have installed the package django-cors-headers. Any idea why this is happening? -
How to change single object from Django ListView
I have a ListView which lists out employee info. I want supervisors to be able to toggle the employee's account active or inactive. Problem is that all the accounts in the list are being toggled when selecting the the toggle button. html: {% for employee in employee_list %} <tr> <td>{{ employee.get_full_name }}</td> <td>{% if employee.is_staff %} <span class="fa fa-check site-yellow"></span> {% else %} <span class="fa fa-times-circle text-muted"></span> {% endif %} </td> <td> <form action="" method="POST"> <input name="toggle" type=hidden value="{{ employee.id }}"> <button class="btn btn-warning btn-xs" type="submit">Toggle</button> </form> </td> <td>{% if employee.is_active %} <span class="fa fa-check site-yellow"></span> {% else %} <span class="fa fa-times-circle text-muted"></span> {% endif %} </td> <td> <button> </td> </tr> {% endfor %} Views.py: def post(self, request, *args, **kwargs): employee = request.POST.get('toggle') employee = Employee.objects.get(id=employee) if employee.is_active: employee.set_inactive() else: employee.set_active() return self.get(request) How can I do this without having to redirect user to a DetailView? -
Django use edit form as add user gives error
I'm using Django 2.x. I want to use all fields which are in the edit user form to the add user form. For that I have extended AuthUserAdmin @admin.register(User) class UserAdmin(AuthUserAdmin): inlines = [ ProfileAdminInline ] fieldsets = AuthUserAdmin.fieldsets add_fieldsets = AuthUserAdmin.fieldsets list_filter = [ 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined', ] list_display = [ 'email', 'full_name', 'is_staff', 'is_superuser', 'is_active', 'last_login', 'date_joined', ] ordering = ('-date_joined', 'username',) search_fields = ['email', 'first_name', 'last_name'] But adding user gives error Please correct the errors below But no field is highlighted for the error. How can I use edit form as add form in Django admin add user? -
Django - How to make session expire when browser is closed by user
I develop an app with Django I want to manage different security aspects for connexion/authentification first, I would like session expire when user close his browser so, in my understanding it should be SESSION_EXPIRE_AT_BROWSER_CLOSE = True in settings.py but it does not work even if I close the browser and open another browser I am connected -
How can I prevent an update modal from creating a new entry in database when submitted in Django?
I have a form that tracks when a user enter/leaves an area. If a user, for example, enters an area, then forgets to "leave" it and attempts to enter another area, the previous entry gets flagged with an N, and the user is prompted by a modal to enter an "estimated time" of when they think they left the previous area. The problem I'm having is that the modal is creating a new entry when submitted, and I can't figure out where this is happening and how to prevent it. It this is also causing the logic to flag the newer entry too and just basically ask for an "estimated time" over an over. For a visual explanation; this is the first submission, when someone enters an area. Then here, I enter another are without exiting the first one, the entry gets flagged, and then I'm prompted by the modal (this is before submitting the modal). Up to this part, everything is working accordingly. Then, When I submit the modal, this is what happens: And after I hit submit it just keeps appearing and updating the next entry due to it being flagged too because of the new entry that … -
Handle multiple forms in a django view(serially) without loosing the values in context
I am building a Reporting Application in Django. The user is asked to fill in a form and based on his/her choices, some data is shown in a tabular format. Along with the data, another form is displayed where the user can filter on the provided data. The issues I am having is, I loose the data, once I submit the second form. Basically my Django view is being called again and the context has no data in it. What is the best practice of achieving this without having code repetitions?