Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Same model with different features?
Object Model: class Object(models.Model): author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE) title = models.CharField(max_length=300) category = models.ForeignKey(Category, on_delete=models.CASCADE) address = models.CharField(max_length=300) content = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_object = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) def __str__(self): return f"{self.title}" Category model: class Category(models.Model): title = models.CharField(max_length=50) def __str__(self): return f"{self.title}" For example I have some categories, like hotels, restaurants etc. So I want for each category to have different features (radio buttons when adding new), but I'm not sure, how to handle it properly. Hotels must have rooms, pool etc. Restaurants must have country kitchen, seats etc. In future I will have and other categories. Quesion is: Which is the best way (practice) to do this. My solution: To create third table with features and every category to have column features and store features separate by comma, but it's not very good solution based on DB normalization. -
How fix ImportError: cannot import name '_mysql' in Django 2.2.5
I'm Deploying a Django Application on an AWS instance (amazon2 64-bit, Linux/4.14.128-112.105.amzn2.x86_64). I spent a lot of time looking and searching in stack overflow without finding a solution. My problem: correctly install mysqlclient. The error: mod_wsgi (pid=14418): Failed to exec Python script file '/var/www/html/project_x/project_x/wsgi.py'. mod_wsgi (pid=14418): Exception occurred processing WSGI script '/var/www/html/project_x/project_x/wsgi.py'. Traceback (most recent call last): File "/var/www/html/project_x/projectenv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/var/www/html/project_x/projectenv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: cannot import name '_mysql' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/var/www/html/project_x/project_x/wsgi.py", line 17, in <module> application = get_wsgi_application() File "/var/www/html/project_x/projectenv/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/var/www/html/project_x/projectenv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/html/project_x/projectenv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/var/www/html/project_x/projectenv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/var/www/html/project_x/projectenv/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager … -
django 2.1 how to fetch value from db and assign it to foreign key
i am new to python django, i found it a bit challenging to fetch data from database and assign it to foreign key. i am using a postgres database. model: class Company (models.Model): author = models.ForeignKey ( User , on_delete = models.CASCADE ) comapny_name = models.CharField ( max_length = 32 , null = False , blank = False ) class owner (models.Model): company = models.ForeignKey ( Company, on_delete = models.CASCADE ) owner_name = models.CharField ( max_length = 32 , null = False , blank = False ) how should i go about it as i dont want to pass the value of FK through URl instead i want to query the value and assign it during form processing. Each User is allowed to create one company only so i want to assign comoany_name which is related to the user that h created the company name and assign it to the FK. views: def ownerform (request): q = Company.objects.all() if request.method == 'POST' : form = businessmodelform ( request.POST ) if form.is_valid ( ) : instance = form.save ( commit = False ) instance.company_id = q.id instance.save ( ) return redirect ( 'str_dashboard' ) else : form = businessmodelform ( ) … -
Template tag as filter value in Django
I have defined one custom tag which is working fine in templates. Like -- {% get_setting "DATE_FORMAT_UI" %} Above statement is returning correct value in template. Now i want to use the same in a filter like this - {{extra_info.to_date|date: '{% get_setting "DATE_FORMAT_UI" %}' }} But this is giving error. I tried in different ways of using quotes for the {% get_setting "DATE_FORMAT_UI" %} But every time bad luck. So could any body help me in solving this. I want to pass date format in filter . That date format is saved into config file. but how to pass that value dynamically in filter. -
How to get the list of columns in a Django Queryset?
I have a code that creates multiple complicated querysets from different tables, using lots of annotations, etc... The code is then joining those querysets using union. Each of those querysets by itself seems to be fine. Calling print(len(qset)) works for each of them. But after combined_qset = qset1.union(qset2), I get the following error: django.db.utils.ProgrammingError: each UNION query must have the same number of columns LINE 1: ..., '') AS "owner" FROM "t1") UNION (SELECT "field_x... ^ When I look at the code, I count the number of fields in .only(...) and .values(...) calls, count the numbers of annotations, etc, it seems that all those querysets have exactly the same number of columns. The error message shows just a tiny little part of the SQL generated (see above), so it's not really helpful. Is there a simple way to get the list of columns of a queryset, so I can find the discrepancy and fix it? -
.png image doesn't show in html template email through django
I made a django website that sends an email after a form has been filled out – the email contains a png image made through django qrcode. Even though the other elements of the html template is shown in the email, the qr code isn't visible. How can I solve this problem? I am doing this all on a local server if that is relevant. Email template: {% extends "event/base.html" %} {% load qr_code %} {% block content %} {% qr_from_text the_user.url_link size="M" image_format="png" %} <h2>cwecmccev</h2> {% endblock content%} Views: def buy(request): if request.method=='POST': form=forms.Purchase(request.POST) if form.is_valid(): form.save() name=form.cleaned_data.get('first_name') + form.cleaned_data.get('last_name') messages.success(request, f'Payment completed for {name}') subject, from_email, to = 'Subject Test', 'tasselsas@gmail.com', form.cleaned_data.get('email') html_content = render_to_string('tickets/mail_template.html', {'varname':'value'}) text_content = 'ereijfij' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return redirect('thankyou') else: form=forms.Purchase() return render(request, 'tickets/buy.html', {'form': form}) Thanks in advance! -
Redirect from .com/ to just .com
I have a web page served by Django, and i want to make it to 301 redirect from mysite.com/ to mysite.com without a slash on the end. Is it possible to do with Django? Last version of Django, python 3.6. path("", views.home, name="main_page") -
Should I learn flask before i learn Django? [on hold]
I am new to backend web development and am starting with django but should I start with flask instead? I am resorting to these two options as I know python quite well. -
Django. OneToOneField. Reverse relation by related_name raise AttributeError
I have model class ClientBid(models.Model): bid = models.OneToOneField(Bid, verbose_name=_('Bid'), on_delete=models.CASCADE, related_name='client_bid') ... When I do the next, I am getting error: bid = Bid.objects.first() bid.client_bid # or bid.clientbid, does not matter ... AttributeError: 'Bid' object has no attribute 'client_bid' Buuuut, when I do something like that: ClientBid.objects.all() bid = Bid.objects.first() bid.client_bid <ClientBid: ClientBid object (1)> All works fine. Why? and how to fix this ? -
how to allow f() to take decimal values
Firstly, I need to sum the student mark before converting it to a percentage. So Ive managed to sum up their mark and somehow managed to convert it to percentage thru this method. students = MarkAtt.objects.values('studName__VMSAcc').annotate(mark=Sum('attendance'), percentage=(F('mark')/1100) * 100) However, I realised that the F() does not take decimal value. It only takes the integer value. This would cause an error to my percentage calculation if the value 'mark' is less than 100. For example: 600/1100 = 0.54545 then it will only take 0 to multiple with 100. And output '0' instead of 54%. How do I allow the function take decimal value? -
django html - require help in POST method from html template to views.py in json format
I want help in knowing who can I pass a values in array from html template to views.py below is my template snapshot <input type="hidden" name="parameter_name" value="{% parameter_list %}" /> parameter_list is a array(list) which I want to pass it to views.py In the current situation, it is been passed as a string. Which is creating issues in my future requirement of that field. I want this to be passed as array(list). I tried JSON.stringfy() but it didn't work. Request someone to help me in this. -
How to get a variable value to populate dropdown in Django
How to get the value of a variable in a Django view. I would like to select the value of an option and use it as a foreign key in another model. However, I can't get the value, just the text of the #prova variable. views.py def getQuestao(request): if request.method == 'GET' and request.is_ajax(): idProva = request.GET.get('prova', None) print("ajax idProva ", idProva) result_set = [] todas_questoes = [] answer = str(idProva) print('answer = ', answer) questoes_selecionadas = Questao.objects.get(idProva=answer) print("cities are: ", questoes_selecionadas) todas_questoes = questoes_selecionadas.questoes.all() print("cities are: ", todas_questoes) for questao in questoes_selecionadas: print("questao name", questao.idQuestao) result_set.append({'name': questao.idQuestao}) return HttpResponse(simplejson.dumps(result_set), content_type='application/json') # return JsonResponse(result_set,status = 200) else: return redirect('/') index.html <select id="prova" class="form-control" name="prova"> <option value='' selected>Prova</option> {% for prova in provas %} <option value="{{ prova.idProva }}">{{ prova.tipoProva }} {{prova.anoProva}}</option> {% endfor %} </select> <select id="questao" class="form-control" name="questao"> <option value='' selected>Questão</option> </select> <script>$(document).ready(function(){ $('select#prova').change(function () { var optionSelected = $(this).find("option:selected"); var idProva = optionSelected.val(); data = {'prova.form-control.val()' : idProva }; $.ajax({ type:"GET", url:'/getCity', // data:JSON.stringify(data), data:data, success:function(result){ console.log(result); $("#questao.form-control option").remove(); for (var i = result.length - 1; i >= 0; i--) { $("#questao.form-control").append('<option>'+ result[i].idQuestao +'</option>'); }; }, }); }); </script> -
How to implement many to many field django api filter in React Js?
Here i am trying to get data from django backend api and here i have many to many field filter like user=1,2 S how i will implement this is react js i am also attaching code here it is api working localhost link http://localhost:8000/api/1/deliveries/report/?user=1,2 like this working in backend and i am trying to select 2 user from multiple select field but i am getting output of only one field And here is React Js Code getData = async e => { try { const idd = e.target.elements.idd.value; e.preventDefault(); const res = await fetch( `http://localhost:8000/api/1/deliveries/report/?user=${idd}` ); const movies = await res.json(); console.log(movies); this.setState({ movies: movies.results }); } catch (e) { console.log(e); } }; and here is select from where i select user <label>Select Walk</label> <select multiple className="form-control btn-block" id="exampleFormControlSelect2 btn-block" style={{ width: "200px", color: "rgba(19, 183, 96, 1.0)" }} name="idd" > {this.state.movies.map(c => ( <option value={c.user}>{c.user1}</option> ))} </select> -
Pass a model from a view to form's inner Meta class
I want to pass a specific model from my view to my form's inner Meta class: view: @login_required def product_create_view(request): if request.method == 'POST': create_product_form = CreateProductForm(request.POST, request=request, model=model) if create_product_form.is_valid(): create_product_form.save() else: create_product_form = CreateProductForm(request=request, model=model) return render(request, 'products/product_create.html', {'form': create_product_form}) form: class CreateProductForm(ModelForm): class Meta: model = CreateProductForm.model fields = ( 'title', 'description', 'price', 'stock', 'category' ) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') self.model = kwargs.pop('model') super().__init__(*args, **kwargs) Is that possible? -
How to use model clean method in django and iterate over fields
I asked a question and, as I have read a little, I now can better express what I need: How to do model level custom field validation in django? I have this model: class StudentIelts(Model): SCORE_CHOICES = [(i/2, i/2) for i in range(0, 19)] student = OneToOneField(Student, on_delete=CASCADE) has_ielts = BooleanField(default=False,) ielts_listening = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_reading = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_writing = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) ielts_speaking = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) and have this model form: class StudentIeltsForm(ModelForm): class Meta: model = StudentIelts exclude = ('student') def clean(self): cleaned_data = super().clean() has_ielts = cleaned_data.get("has_ielts") if has_ielts: msg = "Please enter your score." for field in self.fields: if not self.cleaned_data.get(str(field)): self.add_error(str(field), msg) else: for field in self.fields: self.cleaned_data[str(field)] = None self.cleaned_data['has_ielts'] = False return cleaned_data What I am doing here is that checking if has_ielts is True, then all other fields should be filled. If has_ielts`` isTrueand even one field is not filled, I get an error. Ifhas_ielts`` is False, an object with has_ielts=False and all other fields Null should be saved. I now want to do it on the model level: class StudentIelts(Model): SCORE_CHOICES = [(i/2, i/2) for i in range(0, 19)] student = OneToOneField(Student, on_delete=CASCADE) … -
Finding difference of count of records using aggregation
I'm given a task to write this code into one query using aggregation/annotation. I tried using the count and stuff but I don't have any idea how this works upvotes = UserVote.objects.filter(blog=self, vote_type='U').count() downvotes = UserVote.objects.filter(blog=self, vote_type='D').count() return upvotes - downvotes -
How to get List From aettings.py to view in python?
I try to get list from settings.py to in view. but i got error 'Settings' object has no attribute 'DEFAULT_ROLES' but i define as you see settings.py variable. anyone know whats issue ? settings.py ---------------- DEFAULT_ROLES = ["ROLE_MANAGE_ALL_CONTACT", "ROLE_MANAGE_ALL_CALENDAR"] Views ----------- from django.conf import settings def register(request): util = Utils() print(settings.DEFAULT_ROLES) -
How to send end-user ip address with the youtube-dl request and get video download link. or there is another way to not get blocked by youtube
currently working on a youtube video downloader . using youtube-dl,Django and hosting my project on Pythonanywhere,i almost completed my project but when i send request more then 15-20 youtube block my pythonanywhere server ip. SO i want to ask that how can i solve this blocking problem. free proxies takes too much time to respond. please give me a solution.thanks in advance -
django model.objects.filter for loop doesn't loop through all records
this weird thing happened to me, I'm trying to loop through a bunch of records I got from database, the value of print(next_ghanoons.count()) is 190 but the thing printed in for loop is 0 1 2,... and i goes till 106 and never reaches 190 records what's wrong with my code @staticmethod def get_next(obj): current_section = obj.id_section current_id_book = obj.id_section.id_book.id_book next_order = obj.order + 1 try: next_ghanoons = Ghanon.objects.filter(order=next_order) except ObjectDoesNotExist: return None print(next_ghanoons.count()) i = 0 for ghanoon in next_ghanoons: i = i + 1 print(i) -
logged out and then hit back button and i am able to see the previous page
logged out and then hit back button and i am able to see the previous page Here is my code from django.views.decorators.cache import cache_control @cache_control(no_cache=True, must_revalidate=True, no_store=True) def logout_user(request): logout(request) return HttpResponseRedirect('/login') @login_required(login_url='/login/') def index(request): return render(request, 'index.html') -
Serving a different ModelForm based on selected category
I am making a page for adding products to the webshop by the user, and I have made chained dependent combobox selection, where you start with one combobox for main product category and once you select a main category, another <select> appears for selecting a subcategory, and so on until the innermost (most specific) subcategory is selected. This currently works as follows: whenever a value in a combobox is changed, two AJAX requests are fired. First one calls a view that renders another <select> if a category has children, otherwise returns an HttpResponse which stops attaching the listener. Second one calls a view that renders a different ModelForm if selected category is root node (main category), otherwise returns an HttpResponse which says not to render another ModelForm. I want to serve a different ModelForm based on selected main category. So, say if there are two main categories, Books and Shoes, if you select Books, BookModelForm should appear and the product should be saved as a Book. I have serving the different ModelForm part implemented, however the problem is product_create_view itself and saving the product to the database. This is my views.py: mappings = { '1': BookProductForm, '2': ShoesProductForm } def … -
Django: Form submit wrong value when using inputs with same name?
I'm using custom form: <form method="POST" action="." id="utf_add_comment" class="utf_add_comment"> {% csrf_token %} <div id="utf_add_review" class="utf_add_review-box"> <h3 class="utf_listing_headline_part margin-bottom-20">Add Your Review</h3> <span class="utf_leave_rating_title">Your email address will not be published.</span> <div class="row"> <div class="col-md-6 col-sm-6 col-xs-12"> <div class="clearfix"></div> <div class="utf_leave_rating margin-bottom-30"> <input type="radio" name="rating" id="rating-1" value="1"> <label for="rating-1" class="fa fa-star"></label> <input type="radio" name="rating" id="rating-2" value="2"> <label for="rating-2" class="fa fa-star"></label> <input type="radio" name="rating" id="rating-3" value="3"> <label for="rating-3" class="fa fa-star"></label> <input type="radio" name="rating" id="rating-4" value="4"> <label for="rating-4" class="fa fa-star"></label> <input type="radio" name="rating" id="rating-5" value="5"> <label for="rating-5" class="fa fa-star"></label> </div> <div class="clearfix"></div> </div> </div> <button type="submit" class="button">Submit Review</button> <div class="clearfix"></div> </div> </form> views.py: if request.method == 'POST': print(request.POST) How these inputs looks: So if I submit form, like picture (with 2 marked stars) it returns me 4. If I marked only one star, it returns me 5, 4 = 2 etc.. I'm not quite sure, that this is problem from code above or it comes from js plugin. -
How to get many to many fields filter in django rest-framework?
I want to filter my data like localhost:8000/api/1/deliveries/report/?user=1,2 Many to many field not like only one field i am trying to do but i could not please help me Here is Views.py class ReportView(generics.ListCreateAPIView): queryset = Delivery.objects.all() serializer_class = serializers.DeliverySerializer filter_backends = [DjangoFilterBackend] filter_fields = { 'too': ['lte'], 'fromm': ['gte'], 'electric_bike': ['exact'], 'mode': ['exact'], 'user': ['exact'], } And here is Serializer.py class ReportSerializer(serializers.ModelSerializer): class Meta: model = Delivery fields = '__all__' I am only getting only one user filter http://localhost:8000/api/1/deliveries/report/?user=1 like this -
Request body is not being passed from axios get call to back end
I have an issue while sending get request with a body in axios. It does not pass the body of the request to the backend. Axios code looks like below const FunctionName = (environment, page_num) => { axios.get(API_URL, { params: { environment, page_num }, }).then(res => { console.log(res); }).catch(err => { console.log(err.response.data); }); } I'm using Django as my backend and I'm receiving empty body i.e {} which causes bad request sent to the backend. I went through several stack overflow questions but none of them helped me. Can anyone please help me with this. Update My django code looks like below class TestView(APIView); def get(self, request): environment = request.data['environment'] page_num = request.data['page_num'] ... ... Here when I'm unable to get the environment or page_num data. The same request when I send from postman with the get call and content in the request of the body, it accepts and sends the response back. -
Django 'runserver' command is producing an error
the following error is produced when I use the 'runserver' command: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'blog' During handling of the above exception, another exception occurred: 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 "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 336, in run_from_argv connections.close_all() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/utils.py", line 219, in close_all for alias …