Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter by fields from foreignKey relationships
I got a bunch of models and some of them are connected (by foreign-key relationships) and I wrote a serializer which allows me to print out all of the connected fields that I want, and leave out what I do not want to see. Great. Now I also have a basic filter, which uses the model (PmP) which contains all the foreignkeys, but now I want to add another filter for a field (field name e from PmPr Model) from a different Model, one that is read in via foreignkey connection (pr in Model PmP). But I dont know how to do that and as far as I can see, I cant set two filter_classes inside my view (PmPLListView)?! And I dont know how to access the field via the foreignkey relation. So how do I go about this? If I can access the e field from PmPr Model via my existing filter - than that is also fine with me, I dont necessary want two filter classes (if even possible). It was just me first thought. (btw. sorry about the strange names, but unfortunately I'm not allowed to write the real names) these are my models (at least the … -
Unable to fetch data from mysql using django
I am not getting the data into the table. I assure you that I didn't get any errors while running python manage.py runserver and my database connection with Django is working perfectly. I also assure you that the table in my database has adequate data and there is no issue in the database. From views.py: from django.shortcuts import render, HttpResponse from anapp.models import Tblchkone # Create your views here. def main(request): return render(request, 'main.html') def getTblchkone(request): allcategories = Tblchkone.objects.all() context = {'allcategories' : allcategories} return render(request, 'main.html', context) From models.py: from django.db import models from django.db.models.base import Model # Create your models here. class Tblchkone(models.Model): categoryId = models.BigAutoField(primary_key=True, editable=False) categoryName = models.CharField(max_length=14, unique=True) From main.html: <!doctype html> <html lang="en"> <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.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>MAIN</title> </head> <body> <table class="table"> <thead> <tr> <th scope="col">Category_Id</th> <th scope="col">Catefory_Name</th> </tr> </thead> <tbody> {% for x in getTblchkone %} <tr> <td>{{x.categoryId}}</td> <td>{{x.categoryName}}</td> </tr> {% endfor %} </tbody> </table> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> </html> -
Is settings CORS_ALLOW_ALL_ORIGINS in production ever okay?
I have a project where many different domains will be making requests to my django API, these domains will frequently change and I will not know what these domains will be, so have no way of whitelisting them. Is it okay to set CORS_ALLOW_ALL_ORIGIN to True, and if not, what security risks do I face, and is there an alternative method I can approach this with if so? -
Extract JSON content in Metabase SQL query
Using: Django==2.2.24, Python=3.6, PostgreSQL is underlying DB Working with Django ORM, I can easily make all sort of queries, but I started using Metabase, and my SQL might be a bit rusty. The problem: I am trying to get a count of the items in a list, under a key in a dictionary, stored as a JSONField: from django.db import models from jsonfield import JSONField class MyTable(models.Model): data_field = JSONField(blank=True, default=dict) Example of the dictionary stored in data_field: {..., "my_list": [{}, {}, ...], ...} Under "my_list" key, the value stored is a list, which contains a number of other dictionaries. In Metabase, I am trying to get a count for the number of dictionaries in the list, but even more basic things, none of which work. Some stuff I tried: Attempt: SELECT COUNT(elem->'my_list') as my_list_count FROM my_table, json_object_keys(data_field:json) AS elem Error: ERROR: syntax error at or near ":" Position: 226 Attempt: SELECT ARRAY_LENGTH(elem->'my_list') as my_list_count FROM my_table, JSON_OBJECT_KEYS(data_field:json) AS elem Error: ERROR: syntax error at or near ":" Position: 233 Attempt: SELECT JSON_ARRAY_LENGTH(data_field->'my_list'::json) FROM my_table Error: ERROR: invalid input syntax for type json Detail: Token "my_list" is invalid. Position: 162 Where: JSON data, line 1: my_list Attempt: SELECT ARRAY_LENGTH(JSON_QUERY_ARRAY(data_field, '$.my_list')) … -
How to implement custom django filter for aggregated data from related model
models.py ... class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Hike(models.Model): hiker = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='hikes') hike_date = models.DateField(max_length=100, blank=False) distance_mi = models.FloatField(blank=False) views.py ... class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer serializers.py class PersonSerializer(serializers.ModelSerializer): hikes = serializers.PrimaryKeyRelatedField(many=True, read_only=True) all_hikes = Hike.objects.all() def total_mi(self, obj): result = self.all_hikes.filter(hiker__id=obj.id).aggregate(Sum('distance_mi')) try: return round(result['distance_mi__sum'], 2) ... total_miles = serializers.SerializerMethodField('total_mi') ... class Meta: model = Person fields = ('id','first_name','last_name','total_miles') filters.py class HikerFilter(django_filters.FilterSet): hiker = django_filters.ModelChoiceFilter(field_name="hiker", queryset=Person.objects.all()) class Meta: model = Hike fields = { 'hiker': ['exact'], 'hike_date': ['gte', 'lte', 'exact', 'gt', 'lt'], 'distance_mi': ['gte', 'lte', 'exact', 'gt', 'lt'], } *simplified data +---------+------------+-------------+ | hike_id | hike_date | distance_mi | +---------+------------+-------------+ | 2 | 2020-11-02 | 4.5 mi | | 3 | 2021-03-16 | 3.3 mi | | 5 | 2021-08-11 | 5.3 mi | | 7 | 2021-10-29 | 4.3 mi | +---------+------------+-------------+ The Person view includes "total_miles" stat added via the Serializer (total_mi). Person endpoint http://localhost:8000/persons/2/ { "id": 2, "first_name": "Miles", "last_name": "Marmot", "hikes": [ 2, 3, 5, 7 ], "total_miles": 17.4, }, Currently, the "total_miles" is for all years. My QUESTION: how can I filter "total_miles" in the Person view by a specific year? e.g. http://localhost:8000/persons/2/?year=2020 > "total_miles": 4.5, e.g. … -
How to redirect back two pages Django?
I have a book page. On this page is the button "In favorite". If the user clicks on the button and is authenticated, it will use addBookmark view to add a new object into the database(and just reload the book page). However, if the user isn't authenticated, it'll redirect to the login page firstly. @login_required def addBookmark(request, slug): book = Book.objects.get(slug=slug) if BookMark.objects.filter(user=request.user, book=book).exists(): bookMark = BookMark.objects.get(user=request.user, book=book) bookMark.delete() return HttpResponseRedirect(request.META.get("HTTP_REFERER")) newBookMark = BookMark.objects.create(user=request.user, book=book) newBookMark.save() return HttpResponseRedirect(request.META.get("HTTP_REFERER")) The problem: When a user is redirected to the login page, the next URL will just add a new object in db and reload the page, but this is the login page. How can I redirect users back to the book page if the user isn't authenticated firstly? -
How can I use the value of a model atributte inside a <img> src?
I am trying to create a project in which a model attribute is used as part of an image name. I have tried many methods and I think I am close to the solution, but I have a problem. This is my code: <img src="{% static 'media/{{model.atributte}}.jpg' %}" alt="{% static 'media/{{model.atributte}}.jpg' %}"></img> For example: if the value of the attribute is "img" this should result in = static/media/img.jpg My intention was to use that to set the src path but this is the result I get in the HTML. /static/media/%7B%7Bmodel.atributte%7D%7D.jpg I appreciate any kind of help or recommendation, as an extra comment, I want to clarify that if I write the value of the attribute in the src it does locate the image, but would always do it for the same model and I have several models. Thanks in advance. -
I am confused while rendering my views.py "Django"
My vews.py: if you want me to share another piece of information feel free to ask! def viewList(request, id): # check for the watchlist listing = Post.objects.get(id=id) user = User.objects.get(username=request.user) if listing.watchers.filter(id=request.user.id).exists(): is_watched = True else: is_watched = False if not listing.activate: if request.POST.get('button') == "Close": listing.activate = True listing.save() else: price = request.POST.get('bid', 0) bids = listing.bids.all() if user.username != listing.creator.username: if price <= listing.price: return render(request, 'auctions/item.html', { "listing": listing, 'form': BidForm(), "message": "Error! Your bid must be largest than the current bid!", 'comment_form': CommentForm(), 'comments': listing.get_comments.all(), 'is_watched': is_watched, }) form = BidForm(request.POST) if form.is_valid(): bid = form.save(commit=False) bid.user = user bid.save() listing.bids.add(bid) listing.bid = price listing.save() else: return render(request, 'acutions/item.html', {'form'}) context = { 'listing': listing, 'comment_form': CommentForm(), 'comments': listing.get_comments.all(), 'is_watched': is_watched, 'form': BidForm() } return render(request, 'auctions/item.html', context) inside this view, I added a punch of my project requirement (comments/watchlist(bookmark)/and the last thing(that what I have a lot of problem with it) is the system of Bid) that lets users add bids on such posts and let the creator of that post the ability to close it.... please help I am sticking in this zone, I tried many times to understand! Note I am new at … -
403 error with Apache 2 running on Linode Ubuntu 21.10 in Django
I am following along with the "Python Django Tutorial: Deploying Your Application (Option #1) - Deploy to a Linux Server" by Coref Shafer. After I've activated my Apache 2 server and tried to access my Django app, the page returns a 403 error. After checking my error log, I find the following: Current thread 0x00007f57a341f780 (most recent call first): <no Python frame> [Sat Nov 06 18:29:53.698451 2021] [wsgi:warn] [pid 24290:tid 140014377891712] (13)Permission denied: mod_wsgi (pid=24290): Unable to stat Python home /home/vavao/website/venv. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/vavao/website/venv' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/vavao/website/venv' sys.base_exec_prefix = '/home/vavao/website/venv' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '/home/vavao/website/venv' sys.exec_prefix = '/home/vavao/website/venv' sys.path = [ '/home/vavao/website/venv/lib/python39.zip', '/home/vavao/website/venv/lib/python3.9', '/home/vavao/website/venv/lib/python3.9/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f57a341f780 (most recent call first): <no Python frame> And here is my website.conf file <VirtualHost … -
Use both Django REST framework and web sockets
I have an application built on Django. Initially, I constructed a few APIs using the Django REST API framework, which worked fine. Later, I implemented web sockets to listen to a server. I started the application server on port 5010 and the socket on which this application listens to the server is 8010. However, after implementing web sockets, my API calls started to fail(screenshot below). Please explain if using both REST API framework and web sockets would be possible in Django. -
No module named _tkinter on heroku
I have a Django app that uses PIL import PIL.Image from PIL import ImageTk as itk But when I deploy this app on Heroku, it gives me a traceback error or No module named "_tkinter" is found I'm not using Tkinter but still, this is happening. -
is there any way in django rest framework to list all devices a user logged in?
I'm trying to mimic goggle account's feature of listing all devices and terminate session from devices is there any approach with to create this feature using django rest framework. Thanks -
Trying to iterate through a nested dictionary in django template
I am trying to use for loop though a dictionary in django template and inside the for loop, I am trying to nest another for loop to loop through say quantity for displaying those many images of product - the template is like this - {% for product_id, item in b_data.items %} {% for i in item.numItems %} <div class="col-md-4 mb-4"> <div class="card" style="width: 18rem;"> <img src="/media/{{item.image}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{item.title}}</h5> <p class="card-text">{{product_id}} {{item.qty}}</p> <div class="card-footer"> <a href="#" class="btn btn-primary"><i class="bi bi-cart2"></i></a> </div> </div> </div> </div> {% endfor %} {% endfor %} The views.py looks like below - def make_your_box(request): box_p = {} box_p[str(request.GET['id'])]={ 'image':request.GET['image'], 'title':request.GET['title'], 'qty':request.GET['qty'], 'price':request.GET['price'], 'numItems': list(range(1, int(request.GET['qty'])+1)), } print(box_p) if 'boxdata' in request.session: if str(request.GET['id']) in request.session['boxdata']: box_data=request.session['boxdata'] box_data[str(request.GET['id'])]['qty']=int(box_data[str(request.GET['id'])]['qty'])+1 box_data[str(request.GET['id'])]['numItems']=list(range(1,int(box_data[str(request.GET['id'])]['qty'])+1)), box_data.update(box_data) request.session['boxdata']=box_data else: box_data=request.session['boxdata'] box_data.update(box_p) request.session['boxdata']=box_data else: request.session['boxdata']=box_p print(request.session['boxdata']) print(len(request.session['boxdata'])) x = 0 for prodid, item in request.session['boxdata'].items(): x = x + int(item['qty']) print(x) t_box=render_to_string('ajax/TestSelect1_1.html',{'b_data':request.session['boxdata']}) return JsonResponse({'b_data':t_box}) even in the print stmts outputs correct outpput in the command prompt as shown below - [06/Nov/2021 23:05:30] "GET /TestSelect1 HTTP/1.1" 200 13945 [06/Nov/2021 23:05:30] "GET /media/product_imgs/IMG_0910.JPG HTTP/1.1" 200 3462312 {'5': {'image': 'product_imgs/RedCookies.jpg', 'title': 'Strawberry Cookies', 'qty': '1', 'price': '10', 'numItems': [1]}} {'5': {'image': 'product_imgs/RedCookies.jpg', 'title': 'Strawberry … -
Payment gateway in Pakistan for ecommerce project
I am making an ecommerce store in Django, I want to integrate payment so I can accept payments through Credit/Debit card from my customers. Requirements: I should be able to accept local as well as international credit cards. I have searched a lot, What I have searched through is Following: Popular services for payments are Stripe and Paypal but unfortunately both are not supporting Pakistan. Another Popular service I came up with is 2checkout but their terms and conditions are crazy, its hard to get account on their site. As For local banks, just to give you an idea, HBL bank also provides gateway but its setup fee is 1 hundred thousand and annual fee is also 1 hundred thousand and 3% per transaction. As For other banks some are 40 thousand + 3% per transaction so thats why I can't go with that. For example stripe is 3% per transaction and thats it no annual fee no setup fee. I also looked at skrill but problem is that my customer should also have skrill account for paying me through skrill which is not practical. Please Guide me what I do now, Also If I go with local services such … -
should django password validation not working
I am trying to build a vanilla user registration system with django using a custom registration_form. I would like to check that the password is correct without reloading the page. I am struggling both to require the passwords to comply with the standard set of django password requirements, as well as check that the two passwords match. What I want to achieve is to have the password fields behave like the email field. In the email field, if the @ symbol is missing, a popup appears telling me it needs to change. However, if the passwords don't match or are very few characters, I am still able to submit the form. Is this the expected behavior or is something going wrong? I know that I can check if the form is valid without reloading (e.g. using ajax to do an is_valid() check on the form) after it has been submitted but I am trying to figure out if this is necessary? here is my form class registration_form(UserCreationForm): username = forms.Field(widget=forms.TextInput(attrs={'class': "form-field w-input", 'placeholder': 'Username'})) email = forms.Field(widget=forms.EmailInput(attrs={'class': "form-field w-input", 'placeholder': 'Email address'})) password1 = forms.Field(widget=forms.PasswordInput(attrs={ 'class': "form-field w-input", 'placeholder': 'Password'})) password2 = forms.Field(widget=forms.PasswordInput(attrs={ 'class': "form-field w-input", 'placeholder': 'Repeat Password'})) class … -
Django Select 2 Widget not working , Field rendered but styles not applied
I have been trying to use multiple select using django-select2 widget for a while Step-1: I installed django-select2 using pip install django-select2 Step-2: Added it the installed app INSTALLED_APPS = [ ... django_select2 ... ] Step-3: I added the below to settings.py SELECT2_JS = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/js/select2.min.js" SELECT2_CSS = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/css/select2.min.css" SELECT2_I18N_PATH = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/js/i18n" Step 4: I tried it using the widgets from django_select2.forms import Select2MultipleWidget class ClientForm(AppModelForm): class Meta: model = Client fields = "__all__" exclude = ['client_website'] widgets = { 'point_of_contact': Select2MultipleWidget } Step 5: Just render the form without any loop of any sort {{ client_form }} The result is No style is applied to the select. I also tried including the styles and scripts in the head tag (Didn't help). I belive the widget is working, because when i switch from Select2MultipleWidget to Select2Widget , It changes to a single select <select name="point_of_contact" lang="None" data-minimum-input-length="0" data-theme="default" data-allow-clear="true" data-placeholder="" id="id_point_of_contact" class="django-select2" multiple=""> <option value="2">Test</option> <option value="1">Tester</option> </select> The above is the html rendered for the multi select widget by django Kindly help in getting the functionality of django-select2 -
Best way to search with a ManyToMany field Django
I have 2 models, and I wanted to search with a Many to Many field according to my structuring, below is my models : class User(django_models.AbstractBaseUser, TimeStampedModel, django_models.PermissionsMixin): """ User model for the user creation """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) account_types = models.ManyToManyField(AccountTypes, related_name='account_types') Then another model AccountTypes : class AccountTypes(TimeStampedModel, models.Model): """ Account types for the users. e.g Mentors, Mentees, Parents etc. """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) name = models.CharField(_('Account Name'), max_length=30, blank=False, null=False) How can I search a user uuid with the certain AccountType ? My try was like this : User.objects.get(uuid=uuid, account_types__in=['Mentor']) But I got this error : ValueError: Field 'id' expected a number but got 'Mentor'. -
fields.E304 Reverse accessor clashes in Django for multiple custom user model
ERRORS: core.User.groups: (fields.E304) Reverse accessor for 'core.User.groups' clashes with reverse accessor for 'seller.User.groups'. HINT: Add or change a related_name argument to the definition for 'core.User.groups' or 'seller.User.groups'. core.User.user_permissions: (fields.E304) Reverse accessor for 'core.User.user_permissions' clashes with reverse accessor for 'seller.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'core.User.user_permissions' or 'seller.User.user_permissions'. seller.User.groups: (fields.E304) Reverse accessor for 'seller.User.groups' clashes with reverse accessor for 'core.User.groups'. HINT: Add or change a related_name argument to the definition for 'seller.User.groups' or 'core.User.groups'. seller.User.user_permissions: (fields.E304) Reverse accessor for 'seller.User.user_permissions' clashes with reverse accessor for 'core.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'seller.User.user_permissions' or 'core.User.user_permissions'. This is the error I get when I try to migrate two identical custom User Models. I copy pasted the code of the custom user model from my user app models.py to the seller app models.py. # seller/models.py class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('Users must have an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password): user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=False) is_staff = … -
Annotate based on related field, with filters
class IncomeStream(models.Model): product = models.ForeignKey(Product, related_name="income_streams") from_date = models.DateTimeField(blank=True, null=True) to_date = models.DateTimeField(blank=True, null=True) value = MoneyField(max_digits=14, decimal_places=2, default_currency='USD') class Product(models.Model): ... class Sale(models.Model): product = models.ForeignKey(Product, related_name="sales") created_at = models.DateTimeField(auto_now_add=True) ... With the above model, suppose I want to add a value to some Sales using .annotate. This value is called cpa (cost per action): cpa is the value of the IncomeStream whose from_date and to_date include the Sale created_at in their range. Furthermore, from_date and to_date are both nullable, in which case we assume they mean infinity. For example: <IncomeStream: from 2021-10-10 to NULL, value 10$, product TEST> <IncomeStream: from NULL to 2021-10-09, value 5$, product TEST> <Sale: product TEST, created_at 2019-01-01, [cpa should be 5$]> <Sale: product TEST, created_at 2021-11-01, [cpa should be 10$]> My question is: is it possible to write all these conditions using only the Django ORM and annotate? If yes, how? I know F objects can traverse relationships like this: Sale.objects.annotate(cpa=F('offer__income_streams__value')) But then where exactly can I write all the logic to determine which specific income_stream it should pick the value from? -
Why my codes showing during during runtime? (Django)
I just wanna ask what's wrong with my codes? <div class="form-row"> <div class="form-group col-md-6"> <label><b>Lot Area: </b></label> <input type="text" id='lot_area' class="form-control" oninput="amount_calculate()" value="{{form.c_lot_area}}"> </div> </div> I am using Django. When I run it, the codes also display. It always shows the double quotes and the right arrow during runtime. -
Celery AttributeError : 'download_all' object has no attribute 'location'
I want to create a progress bar for my project. I have a class and this class has some functions. Especially, one of them takes a long time (def download_all) and this is my main reason for wanting to create a progress bar. I successfully set up celery, celery-progress, etc. and they work all fine. My problem is this: I want to integrate the progress bar to download_all function. I It gives an error: AttributeError: 'download_all' object has no attribute 'location' I am sure that this error is because of the celery task because when I run it without celery, it works. This is my code. How can I do it? views.py def setup_wizard(request): ... task = (functions.myClass(n_username, n_password, n_url, n_port, db_password, username=request.user.username)).delay(5) task_id = task.download_all(request.user.username, setup.nessus_username, setup.nessus_password, setup.nessus_url, setup.nessus_port, setup.db_password, username=request.user.username).task_id // in task_id download_all parameters, I had to user request.user.username instead of "self" parameter. ... context = { ... 'task_id':task_id } functions.py @shared_task(bind=True) class myClass(): def __init__(self, nessus_user, nessus_password, nessus_url, nessus_port, db_password, username): self.location = zt_dosya_url self.static_fields = {} self.download_all(n_user, n_password, n_url, n_port, db_password) self.send(username) ... def download_all(self, n_user, n_password, n_url, n_port, db_password): if not os.path.exists(self.location): os.mkdir(self.location) else: shutil.rmtree(self.location, ignore_errors=True) os.mkdir(self.location) ... for s in scans: i = … -
AttributeError: 'str' object has no attribute '__name__' creating OTREE investment game with Pycharm,
I am working on a game where investors have a specific fund with multiple rounds of investments. In case they invest in any round, their available fund for the subsequent rounds should be adjusted for that. If the initial budget was $1000 and the participant invest $50 in round 2, then for third he should have $950. Please have a look and help me class Constants(BaseConstants): name_in_url = 'investment' players_per_group = None num_rounds = 1 budget = cu(1000) class Player(BasePlayer): investment = models.CurrencyField(label="How much will you invest?") def set_funds(self): players = self.get_players() investment = [p.investment for p in players] self.total_investment = sum(investment) for player in players: player.funds = Constants.budget - player.total_investment def investment_error_message(player, value): print('value is', value) if value > player.funds: return 'Cannot offer more than your remaining fund' class investment(Page): form_model = 'player' form_fields = ['investment'] class ResultsWaitPage(WaitPage): pass class Results(Page): pass page_sequence = ['investment'] -
width not correct in when using d-flex in Bootstrap 5.0
I have a base.html file that I am using as a template in my Django project. I used d-flex to create top nav and sidebar but I am struggling to set up width and height on each website to 100%. When running it as a static page everything is ok but when I try to run it in Django then the result is like this: As you can see the width and height are not 100% but they are adjusting somehow to the content. How can I fix this? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>Starlab - {% block title %}{% endblock %}</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.7/css/all.css"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"> </script> </head> <body> <div class="d-flex w-100" id="wrapper"> <!-- Sidebar--> <div class="border-end bg-white text-center" id="sidebar-wrapper" style="width: 275px;"> <div class="sidebar-heading border-bottom bg-light text-center" style="height: 55px;"></div> <div class="list-group list-group-flush"> <a class="list-group-item list-group-item-action list-group-item-light p-3" href="{% url 'homepage' %}">Home pge</a> <a class="list-group-item list-group-item-action list-group-item-light p-3" href="/products">Products</a> <a class="list-group-item list-group-item-action list-group-item-light p-3" href="/articles">Articles</a> </div> <div class="list-group-item p-3">Categories <ul> {% for tag in tags %} <div class="text-center"><a href={% url 'tagged' tag.slug %}>{{tag.name}}</a></div> {% empty %} … -
Django HyperlinkedModelSerializer on a table that has a field marked as pk + fk
I have this table which has a field marked as a primary key, when it also is a foreign key. Isn't ideal, but need to deal with this at the moment. class Profile(models.Model): class Meta: verbose_name_plural = "Profiles" member = models.OneToOneField( Member, on_delete=models.CASCADE, primary_key=True, ) ... Now I have a django-rest-framework serializer for the Member and Profile models, that looks like this, class MemberSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Member fields = ('id', 'role_id', 'user_id') class MemberProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ['member_id','bio','address','mobile'] The question I have is that, when I have the 'member_id' extracted from MemberProfileSerializer, it lists down the id correctly (this is the id that is pk for Profile, and is also fk to the Member table) But if I need to extract more information from the Member model, and to do that, if I add a reference to the MemberSerializer, I get back an empty object in the results! class MemberProfileSerializer(serializers.HyperlinkedModelSerializer): member_id = MemberSerializer() class Meta: model = Profile fields = ['member_id','bio','address','mobile'] Any suggestions on why this could be happening! -
get all children of category id in a list drf
I have a model like this class Catgeory(models.Model): name = models.CharField() parent = models.ForeignKey('self', related_name='children') Now I need to write a piece of code to return a list of all children ids for a specified category for example, I have a category like that General (id=1) --> Electronics (id=2) --> Mobile phones (id=3) --> Apple (id=4) If I want to get children of Electronics it should return [3, 4] But I have been trying to find a solution for 3 hours, unfortunately, I could not solve it yet. I can get all parents by one child but cannot get children by a parent. If anybody has a solution or any idea, can you help? Any help would be appreciated! Thank you very much!