Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a good way to deal with multiple forms and models in Django?
I'm building an app in which I have a model with several manytomany fields and some foreignkey fields, and I need a view that allows me to create all in one page and let me enter multiply times for the manytomanyfields, but I don't know how to deal with a lot of forms in the same page/view. main model class Client(models.Model): company_name = models.CharField(max_length=255, blank=True, null=True) payment_method = models.CharField(max_length=64, null=True, blank=True) owner = models.CharField(max_length=100, blank=True, null=True) operation = models.CharField(max_length=50, blank=True, null=True) value = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) currency = models.CharField(max_length=55, null=True, blank=True) address = models.ManyToManyField(Address, blank=True) contact = models.ManyToManyField(Contact, blank=True) relationship = models.ManyToManyField(Relationship, blank=True) attachment = models.ManyToManyField(Attachment, blank=True) billing = models.ForeignKey(Billing, null=True, blank=True, on_delete=models.CASCADE) delivery = models.ForeignKey(Delivery, null=True, blank=True, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True, null=True) note = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.company_name others models class Address(models.Model): address = models.CharField(max_length=256, null=True, blank=True) number = models.PositiveIntegerField(null=True, blank=True) district = models.CharField(max_length=32, null=True, blank=True) city = models.CharField(max_length=32, null=True, blank=True) country = models.CharField(choices=COUNTRY_CHOICES, max_length=64, null=True, blank=True) def __str__(self): return self.address class Contact(models.Model): name = models.CharField(max_length=256, blank=False, null=True) sector = models.CharField(max_length=64, blank=True, null=True) email = models.EmailField(max_length=256, blank=True, null=True) phone = PhoneField(blank=True, null=True) cellphone = PhoneField(blank=True, null=True) role = … -
Create model instance from dict containing different keys compared to model attributes in Django
I am trying to create model/s from an api response. The response received has different keys as compared to the model attributes in our system. I would like to know the best way to create a model from that response. class MyModel(BaseModel): external_id = models.IntegerField(blank=True, null=True) start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) def save_to_db_from_external_data(response_data): map_dict = { 'externalId': 'external_id', 'startDate': 'start_date', 'endDate': 'end_date' } if type(response_data) == 'dict': new_model_data_dict = {} for key in map_dict: if key in response_data: new_model_data_dict[map_dict[key]] = response_data[key] MyModel.objects.create(**new_model_data_dict) elif type(response_data) == 'list': new_model_data_list = [] for data_dict in response_data: new_data_dict = {} for key in map_dict: if key in data_dict: new_data_dict[map_dict[key]] = data_dict[key] new_model_data_list.append(new_data_dict) MyModel.objects.create(**(model_data_dict) for model_data_dict in new_model_data_list) The above is the code that I have written. Is this the correct way to do the required task? Or is there any better way in django to achieve the same? -
Debug hover in VSCode is not showing variable values in Python
In a Django view context, I am trying to see the variable values at debug time in the hover, and they are not showing up. Version: 1.53.2 (user setup) Commit: 622cb03f7e070a9670c94bae1a45d78d7181fbd4 Date: 2021-02-11T11:48:04.245Z Electron: 11.2.1 Chrome: 87.0.4280.141 Node.js: 12.18.3 V8: 8.7.220.31-electron.0 OS: Windows_NT x64 10.0.18363 What I expect to see: What I actually see: Python Extension v2021.1.502429796 Language Server: Pylance -
Django + OWASP ZAP Cross Site Scripting (Reflected) - Is the value attribute of an HTML input tag a risk?
In my Django project, I have a search input in the navbar across most pages on my site. I'm a beginner to OWASP ZAP. After running the scan, one of the high priority alerts (red flag icon) raised was "Cross Site Scripting (Reflected)". In my case, this is my website search form: <form method="GET" id="searchForm"> <input type="text" name="q" id="searchQuery" placeholder="Search..." autocomplete="off" maxlength="100" required=""> </form> if someone searches for javascript:alert(1); in the search box, the value= attribute contains the same. <form method="GET" id="searchForm"> <input type="text" name="q" value="javascript:alert(1);" id="searchQuery" placeholder="Search..." autocomplete="off" maxlength="100" required=""> </form> Is this is a potentially vulnerability or is the input is being sanitized by Django? This form is created using a Django forms.ModelForm: class SiteSearchForm(forms.ModelForm): class Meta: model = Search fields = ('q',) -
How to prepopulate tabularInline fields with different values per-row
I have a ModelAdmin class with an inline of type TabularInline. What I would like is for each row of the TabularInline. What I need to do is to pre-select the select boxes with the available languages so each of them will have one of the languages as a selected value (e.g. row1: English, row2:Arabic, row3: Français, row4: Espanol). Please note that the number of rows is generated based on the count of the available languages. Any suggestions would be appreciated. My code is shown below: admin.py class SectorTranslationInline(admin.TabularInline): model = SectorTranslation form = SectorTranslationForm def get_extra(self, request, obj=None, **kwargs): lang_count = Language.objects.count() return lang_count def get_max_num(self, request, obj=None, **kwargs): lang_count = Language.objects.count() return lang_count class SectorAdmin(admin.ModelAdmin): inlines = [ SectorTranslationInline ] models.py class Sector(models.Model): _name = models.CharField(max_length=255, null=False, default='') class Language(models.Model): name = models.CharField(max_length=255, null=True) name_prefix = models.CharField(max_length=255, null=True) class SectorTranslation(models.Model): lang = models.ForeignKey(Language, related_name='lang_sector_translation', on_delete=models.CASCADE) sector = models.ForeignKey(Sector, related_name='sector_translation', on_delete=models.CASCADE) name = models.CharField(max_length=255, null=False, default='') -
How to make a django field read only for a non staff user in django rest framework
Here is my django model; class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="books") quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.book.title}" Here is the serializer; class OrderItemSerializer(serializers.ModelSerializer): book = BookSerializer(read_only=True) class Meta: model = OrderItem exclude = ["user"] How do I prevent non staff users from changing the ordered field or making the field read-only for non staff users -
Django Two Factor Auth with custom login
I am trying to add two factor login using the @otp_required decorator from Django Two-Factor Authentication into my custom login. From other posts, it seems like the correct way to do this is create a new view that is extended from two factors Login View so I have views.py from two_factor.views import LoginView from two_factor.forms import AuthenticationTokenForm, BackupTokenForm class testLogin(LoginView): template_name='customLogin.html' form_list = ( ('auth', TestLoginForm), ('token', AuthenticationTokenForm), ('backup', BackupTokenForm), ) urls.py path('test/', views.testLogin.as_view(), name='test') I have also extended my login form to be forms.py from django.contrib.auth.forms import AuthenticationForm class TestLoginForm(AuthenticationForm): username = forms.CharField(max_length=20) password = forms.CharField(max_length=20, widget=forms.PasswordInput) How would I pass the form into a html page and then get that data back through a post command so I can work with the data in another view such as my customView. views.py def customView(request): form = TestLoginForm(request) if (request.method == "POST"): if (form.is_valid()): -
Recover old jupyter notebooks
I had to uninstall everything on my laptop and reinstall including python and jupyter. Now I dnt see any of my jupyter notebooks when I launch jupyter. I am having almost a heart attack! How I can recover my codes in jupuyter? some additional info: This was part of our company transition from legacy company to new company. We basically lost all installed programs as the results of this transition. I know, very stupid but I was not involved in making decisions! -
Django Admin login not working after model change
I changed the username field to email, following this guide. Everything works so far, except for Django Admin Website, which worked before like a charm. No matter what I enter it always displays "Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive.". This is odd, as I am still able -from my separate frontend- to add and login users. Just the ones created via createsuperuser don't work properly. I went to the shell and it stated the following: >>> from user.models import User >>> User.objects.get(id=1) <User: Firstname Lastname> >>> me = User.objects.get(id=1) >>> me.password 'pbkdf2_sha256$216000$XTRS1jTuNQWA$rvRCMxeYAJVaL1SftNjXBYCxlMiRnHs9uopq4OMh6gM=' >>> me.email 'me@test.test' >>> me.username >>> me.is_staff True >>> me.is_superuser True >>> me.is_active True So this seems to work. But when I do the authenticate method for those credentials, nothing happens. My model looks basically like this and worked before the change: class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = CustomUserManager() I tried deleting the database and reading the user, I tried different passwords and usernames (mail addresses). -
trouble with django on git bash. command not found
I've been trying to to start a django project but have been having issues following the usual steps recommend to start a django project, some have been working some have not. For instance: pip django doens't work, throwing the error - bash: pip: command not found, while py -m pip django works. Similary when I try to check if django is installed django --version gives the error bash: django: command not, while this py -m django --version has no issues. So I figured just adding py -m would make all comands work, however when I try py -m django-admin startproject x to try and create my first django file but it gives the error "C:\Users\username\AppData\Local\Programs\Python\Python39\python.exe: No module named django-admin" What can I do to make django-adming work and be able to create a project :( -
Django createsuperuser command not working after switching from username to email
So I changed the Django username field to 'email', which is documented as completely legal here, but after this, the createsuperuser method doesn't work. Of cause I have added the Auth model to my settings and it worked before. This is basically my model currently: class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] After migrating the change createsuperuser throws this after every input is entered: XXX\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() missing 1 required positional argument: 'username' I tried moving around this with a custom manager, but it threw new problems plus I would really would like to avoid this. Furthermore, I looked at the source code of the method, but couldn't figure out where this could go wrong. I also reset and deleted the database without luck. -
Django secret key on elastic beanstalk
Is there any reason why this isn't working anymore? I'm getting key must not be empty even though I have env variable set in EB console. https://stackoverflow.com/questions/47372082/django-secret-key-environmental-variable-not-working-in-elastic-beanstalk -
localhost vs. 127.0.0.1 in regards to CSS
So I've seen a few posts about the differences between localhost and 127.0.0.1 but nothing specifically regarding my question. I am currently creating a Django application which, when run, starts the application on 127.0.0.1:8000. My problem involves updating my CSS files and not always seeing changes when I refresh. Sometimes the changes will display on one of the two but not the other and was curious as to why this may be? I do currently have multiple CSS files as well as bootstrap files which I have downloaded the libraries for. Any general feedback on why these changes occur on one of the two but not the other would be appreciated! -
Django objects.filter vs objects.all
I have a question regarding the filter() and all() methods of django objects. It is not a question which one of the two is preferred, I just noticed an odd (to me) behavior. Because, as it is laid out in Django ORM - objects.filter() vs. objects.all().filter() - which one is preferred? in Django src, both ways should return the same (they both reference the chain() method): See: https://github.com/django/django/blob/0963f184abd96800b76b19a6a181e1b544c7fafe/django/db/models/query.py#L928 And: https://github.com/django/django/blob/0963f184abd96800b76b19a6a181e1b544c7fafe/django/db/models/query.py#L951 So the filter() and all() method should return the same objects. But I recently discovered the following behavior: MyModel.objects.all()[0].update(name="Test") # --> $: AttributeError: type object 'MyModel' has no attribute 'update' # And to check if it indeed has no update method: MyModel.objects.all[0].__dir__() # --> no update() method in returned dictionary but a save method So while above code raises Error, line below would work: MyModel.objects.all()[0].name = "Test" MyModel.objects.all()[0].save() However, if the same object is retrieved by the filter() method, it has the update() method. Why do I get the same object both times but with seemingly different methods added to it? -
How Can I Make The User Vote Only Once
so I'm trying to build a poll app with Django but I have a problem, I can't preventing a user from voting twice or more This is My Models.py class NewPoll(models.Model): Question = models.CharField(max_length=255,default=False) option1 = models.CharField(max_length=255) option2 = models.CharField(max_length=255) option3 = models.CharField(max_length=255) option1count = models.IntegerField(default=0) option2count = models.IntegerField(default=0) option3count = models.IntegerField(default=0) created_by= models.ForeignKey(User,related_name='newpoll',on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.Question What I have in my vote view in views.py #some codes @login_required(login_url='signin') def vote(request,poll_id): newpoll = get_object_or_404(NewPoll,pk=poll_id) if request.method == "POST": selected_option = (request.POST['poll']) if selected_option == 'option1': newpoll.option1count +=1 elif selected_option == 'option2': newpoll.option2count +=1 elif selected_option == 'option3': newpoll.option3count +=1 else: return HttpResponse("Wrong Form!") newpoll.save() return redirect('result',poll_id=newpoll.pk) return render(request,'vote.html',{'newpoll':newpoll}) -
How to pass variable (list) to JavaScript in Django?
I am trying to create a chart Using Chartjs and Django, i have a problem when i am trying to pass the data from views.py to js code. so,this is my code in views.py.. def home(request): labels = ["A", "B", "C", "D"] data = [1,2,3,4] return render(request, 'home.html',{'labels': labels ,'data': data,}) and this is my part of code in home.html .. <script> var labels = {{labels}}; var data = {{data}}; var ctx = document.getElementById('myChart').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'line', // The data for our dataset data: { labels: labels, datasets: [{ label:"chartLabel", backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data:data, }] }, // Configuration options go here options: {} }); </script> put when i use these tow lines in js .. var labels = ["A", "B", "C", "D"]; var data = [1,2,3,4]; instead of this tow my code works fine. var labels = {{labels}}; var data = {{data}}; -
highcharts won't load django views
I am trying to find an alternative to placing the highcharts javascript in the django template for security reasons since CSP blocks it. I created another file in the static folder and referenced it within the template. Part of the chart shows but I don't think the data is going through since no data is shown on the chart. This is the script in the javascript file that is supposed to proecss the django view dat: <script> document.addEventListener('DOMContentLoaded', function () { const chart = Highcharts.chart('container', { chart: { backgroundColor: '#eaeaea', type: 'bar' }, title: { text: 'Rezultatet sipas lëndëve' }, xAxis: { categories: '[{% for cat, value in cat_scores.items %} '{{ cat }}' {% if not forloop.last %}, {% endif %}{% endfor %}]' }, yAxis: { title: { text: 'Suksesi' } }, series: [{ name: 'Saktë', data: '[{% for cat, value in cat_scores.items %} {{ value.2 }} {% if not forloop.last %}, {% endif %}{% endfor %}]' }, { name: 'Pasaktë', data: '[{% for cat, value in cat_scores.items %} {{ value.1 }} {% if not forloop.last %}, {% endif %}{% endfor %}]' }, { name: 'Perqindje', data: '[{% for cat, value in cat_scores.items %} {{ value.0 }} {% if not … -
Django - get table data from templates into views.py
I am making a restaurant application and currently working on takeaway food functionality i.e. user orders food online. I am displaying food items from my postgresql database onto my takeaway.html template and assigning each food item a class. Each food item will have an 'add to basket' button, JavaScript provides all functionality related to the basket. I have found some resources that mention using the GET method with a form but I'm still not too sure. I am curious as to how I can access this 'basket' in my views.py and be able to put the values into my database. I wish to access the food name, quantity and the price from the table if possible. Any resources or help would be greatly appreciated. takeaway.html <div class="col-sm-12 my-auto"> <h3>Starters</h3> {% for starter in starters %} <div id="{{ starter.id }}"> <span class="food-item-name">{{ starter.name }}</span> <div class="food-item-details"> <p>{{ starter.description }}</p> <p class="food-item-price">{{ starter.price }}</p> <p>{% for a in starter.allergen.all %}{{ a.name }} | {% endfor %}</p> <button class="add-item-button" onclick="addToBasket(this)">Add to Basket</button> </div> {% endfor %} </div> <div> <h3>Mains</h3> {% for m in mains %} <div id="{{ m.id }}"> <span class="food-item-name">{{ m.name }}</span> <div class="food-item-details"> <p>{{ m.description }}</p> <p class="food-item-price">{{ m.price }}</p> <p>{% … -
How to filter some items in a manytomany field in Django
I am trying to make an announcement system in my application whereby the Dean can create an announcement and selects the student he is sending them to. I will like to get a way to be able to filter only the specific student announcement(s) on his/her page. models.py class Announcement_by_dean(models.Model): student_id = models.ManyToManyField(add_students_by_manager) message = models.TextField() sent_date = models.DateField(default=datetime.now(), blank=True) updated_date = models.DateField(auto_now=True, blank=True) def __str__(self): return self.id class add_students_by_manager(models.Model): manager_ID = models.ForeignKey(Manager_login_information, on_delete=models.CASCADE) student_ID = models.CharField(max_length=200) student_name = models.CharField(max_length=200) phone_number = models.CharField(max_length=200) address = models.CharField(max_length=200) dob = models.CharField(max_length=200) major = models.CharField(max_length=200) password = models.CharField(max_length=200) def __str__(self): return self.student_name views.py def student_course_list(request): stu_course_id = request.POST.get('stu_course_id') my_announcement = Announcement_by_dean.objects.filter(student_id=request.user.id).order_by('-sent_date') print(my_announcement) context = {"my_announcement":my_announcement} return render(request, "student_course_list.html", context) -
Importing from "django.(any module)" gives me this warning : could not be resolved from sourcePylance (reportMissingModuleSource)
I have just created a Django project in virtual environment and I'm getting this error or warning I'm not quite sure : (module) django Import "django.contrib" could not be resolved from sourcePylance(reportMissingModuleSource) In every line that has import from django . I have searched for this problem and I have tried these so far : 1 - editing Settings.JSON file in VScode by adding : "python.pythonPath": "C:/Users/abdur/dev/cfehome/django_project/Scripts/python.exe", Which is the python.exe location in my virtual environment 2 - I have selected Python Interpreter to the one that is inside the virtual environment like this picture : I have tried the other choice too but didn't work as well . however when I run python manage.py runserver It works without giving me any errors but I'm trying to understand why I'm getting these warnings . -
Django Static Folder Javascript
Hey There I am noob on django.Basically I am trying to add static folder on external javascript file for image slider but I can't If any buddy know the answer please help me.I Need your help -
Why is my django-graphql query returning null, when the property of my model is not?
I am creating a Django application with a GraphQL API (using graphene-django), and I have made the types for my models. However, I have this CompetitorModeType, which is a custom type. The purpose of this is for when I want to access a specific property of a Competitor (or a mode), I can use this type, and in the query, pass the mode a variable. The goal is to pass the Competitor id and the mode I want to access and get it back as response.data.mode or something like that. So it is what I did with the resolver: The problem is that when I do the query, I get the value as null, and I don't why. Here is the query I am doing: As you can see, I am getting null. However, the values are not null, as shown here: And if I do the same query in the Django shell, I don't get null: My theory is that I am not correctly creating the Type. That there is probably a logical error there because the shell is proof that the query works. If anyone knows what is going on, pls help! -
context not passing to included template
I am trying to pass models from my view to the template with the context parameter. The problem is that the context isn't passing to the included template, it is working everywhere else just not in the included template (before applying ajax it works fine). This is my template (gifts_template.html): <form id="form_filter_gifts"> {% csrf_token %} <div class="row"> <div class="col"> <select class='form-select' name="s_filter_gifts_by_date" id="s_filter_gifts_by_date"> <option value="" selected>Show Gift Cards From</option> {% for year, month_list in gifts_years_months.items %} {% for month in month_list %} {% if gifts_selected_year == year and gifts_selected_month == month %} <option value="{{ year }}-{{ month }}" selected>{{ year }}-{{ month }}</option> {% else %} <option value="{{ year }}-{{ month }}">{{ year }}-{{ month }}</option> {% endif %} {% endfor %} {% endfor %} </select> </div> <div class="col"> <input type="submit" name="btn_filter_gifts_date" class="btn btn-light" value='Filter'> </div> </div> <span>Cool!</span> {% if gifts %} <span>Cool!</span> <br style="line-height: 0;" /> <table class="table table-light table-striped"> <thead> <tr> <th scope="col">Date</th> <th scope="col">Gift Amount</th> <th scope="col">Tax</th> </tr> </thead> <tbody> {% for gift in gifts %} <tr> <td>{{ gift.date }}</td> <td>{{ gift.gift_money|floatformat }}</td> <td>{{ gift.gift_tax|floatformat }}</td> </tr> {% endfor %} </tbody> </table> {% endif %} This is the relevant html includer: <!--Balance Modal--> <div class="modal fade" id="balance_modal" … -
Align Bootstrap Tags with Text in List
How can I align the right side of the tag with the left side of the text (image attached)? superlongtagname | text1 shortertagname | text2 tinytagname | text3 Here is my template code (looping through a list of Django objects): <ul> <li> <span class="badge bg-{{ t.get_color_display }}"> {{ t.name }} </span> {{ rn.entry_text }} </li> </ul> I've tried alignment utilities (align-end), floating (on both the li and the span), etc, and nothing seems to work. -
AttributeError: 'list' object has no attribute 'objects' Django Rest
I want to post request django rest but this error.I have two Serializer.I want to post a request for full data not via id. I have a mistake File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework\serializers.py", line 205, in save self.instance = self.create(validated_data) File "C:\django 5\Новая папка (34)\Новая папка (29)\Новая папка (23) full\Musa\MDShop\serializers.py", line 125, in create new_smartphone = smartphone.objects.create(sm) AttributeError: 'list' object has no attribute 'objects' class OrderCreateSerializer(serializers.ModelSerializer): smartphone=ShopSerializer(many=True) class Meta: model = order fields = '__all__' def create(self, validated_data): smartphone = validated_data.pop('smartphone') smartphone_models = [] for sm in smartphone: print(type(sm)) new_smartphone = smartphone.objects.create(sm) new_smartphone.save() smartphone_models.append(new_smartphone) question = order.objects.create(**validated_data) print(smartphone_models) question.smartphone.set(smartphone_models) class ShopSerializer(serializers.ModelSerializer): img1 = serializers.SerializerMethodField('get_image_url') img2 = serializers.SerializerMethodField('get_image_url') img3 = serializers.SerializerMethodField('get_image_url') img4 = serializers.SerializerMethodField('get_image_url') img5 = serializers.SerializerMethodField('get_image_url') img6 = serializers.SerializerMethodField('get_image_url') class Meta: model = smartphone fields = ("id", "img1", "img2", "img3", "img4", "img5", "img6","title","price","slug") def get_image_url(self, obj): return obj.image.url how to solve this problem how to solve this problem how to solve this problem how to solve this problem