Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can we align child div right side of the parent div
In my below code I have one anchor tag and inside that anchor tag I have one div. So here what i am trying is to align both anchor tag and div side by side. In my case while I am giving left and right property to div then it is hiding inside anchor tag it is not appearing left and right so how can we align it side by side like left side is anchor and right side is div. {% if CategoriesBar%} {% for Categories in CategoriesBar %} <a class="trigger" href="{% url 'getProductsByCategory' Categories.cat_name {{Categories.cat_name}} <div class="sub"> {% for subCategories in SubCategoriesBar %} {% if Categories.cat_id == subCategories.parent_id %} <div class="item">{{subCategories.cat_name}}</div> {% endif %} {% endfor %} </div> </a> {% endfor %} {% endif %} css .trigger { box-sizing: border-box; position: relative; width: 120px; margin: 0 0 50px; padding: 10px; background: #bada55; text-align: center; } .sub { box-sizing: border-box; position: absolute; top: 100px; left: 0; width: 120px; background: #4863a0; color: #fff; text-align: left; -
How to solve PermissionError:[Errno13] using Python matplotlib.pyplot.savefig in Ubuntu 18.04 apache2 server Django
I made a line chart using this code in Django, Python 3.6, Apache2, Ubuntu 18.04 Before moved to the server(Ubuntu), I tested in my local environment(Mac OS), And it worked. def saveChart(request): ... plt.plot(val1, var2) plt.savefig('django project dir/static/chart.png') plt.close() And I got PermissionError:[Errno13] with plt.savefig() I've tried to give a 777 permission on my view.py but it didn't work. Is there anything I can do? -
AttributeError: module 'django.http.request' has no attribute 'user // i have Django rest installed
Error I am getting AttributeError: module 'django.http.request' has no attribute 'user' Signal I am trying to send when user logs in def auth_done(sender, **kwargs): print('User has logged in') tok = Token.objects.create(user=request.user) print(tok.key()) user_logged_in.connect(auth_done, sender=User) Login view @csrf_exempt def login_in(request): if request.method == 'POST': name = request.POST['first_name'] password = request.POST['password'] user = authenticate(username=name, password=password) if user is not None: print(user) login(request, user) tok = Token.objects.create(user=request.user) print(tok.key) print('User is authenticated') else: print('Not authenticated') return render(request, 'Auth/user.html') Settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ], # Use Django's standard `django.contrib.auth` permissions, 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.isAuthenticated' ] } -
pipenv failed to build image pip
I was trying to start a pipenv shell to start working on a django project on python 3.8.9 and it keeps giving me this error: Using C:/Users/CY/AppData/Local/Programs/Python/Python38/python.exe (3.8.9) to create virtualenv... [=== ] Creating virtual environment...RuntimeError: failed to build image pip because: Traceback (most recent call last): File "c:\users\cy\appdata\local\programs\python\python38\lib\site-packages\virtualenv\seed\embed\via_app_data\via_app_data.py", line 57, in _install installer.install(creator.interpreter.version_info) File "c:\users\cy\appdata\local\programs\python\python38\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 46, in install for name, module in self._console_scripts.items(): File "c:\users\cy\appdata\local\programs\python\python38\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 131, in _console_scripts entry_points = self._dist_info / "entry_points.txt" File "c:\users\cy\appdata\local\programs\python\python38\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 118, in _dist_info raise RuntimeError(msg) # pragma: no cover RuntimeError: no .dist-info at C:\Users\CY\AppData\Local\pypa\virtualenv\wheel\3.8\image\1\CopyPipInstall\pip-21.1.1-py3-none-any, has pip Failed creating virtual environment [pipenv.exceptions.VirtualenvCreationException]: Failed to create virtual environment. -
AttributeError at /search 'search' object has no attribute 'cleaned_data' django
def searchform(request): if request.method == "POST": form1 = search(request.POST) if form1.is_valid : titl = form1.cleaned_data.get("query") top = False for i in util.list_entries(): if titl == i: htmlconvo = util.get_entry(titl) mdcovo = markdowner.convert(htmlconvo) top = True break if top : return HttpResponseRedirect(request,"encyclopedia/title.html",{ "form":form1, "content":mdcovo, "title": titl }) else: lst = [] for j in util.list_entries(): if titl in j: lst.append(j) if len(lst) == 0: form1 = search() return render(request, "encyclopedia/error.html", { 'form': form1, }) else: return render(request, "encyclopedia/index.html", { "entries": lst, "form": form1}) else: form1 = search() return render(request,"encyclopedia/error.html",{ "form":form1, }) This is the view code of search in which i am getting an error AttributeError at /search 'search' object has no attribute 'cleaned_data' What should i do <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input type="text" name="search" placeholder="Search Encyclopedia"> </form> this is my layout.html -
How to get all of field names in serializer
Imagine if I have a ModelSerializer. How can I get all of my field names in serializer? for example: class AnyModelSerializer(serializers.ModelSerializer): class Meta: model = AnyModel fields = ['field1`, `field2`, ...] I want something to iterate through all field names, something like: for field in field_names: # do stuff here ... -
How to get a user's manager by python LDAP or Django LDAP?
How to get a user's manager by python LDAP or Django LDAP? BTW, could it possible to check if a user is deactived (means have left company)? -
Django pass variables from views to Ajax
In my django project i have a method in a view where execute some calculation e define a variable for message and pass to my Ajax method. I do: views.py ... try: msg="Prodotto inserito nel carrello" if request.POST['pgift'] == "true": <do some calculations> else: msg = "Non hai abbastanza punti per acquistare utilizzando il gift" except Exception as e: msg = "Errore imprevisto. Riprova ad inserire il prodotto o contattaci per maggiori informazioni" response = [] valrst = {'r_msg': msg} response.append(valrst) json = simplejson.dumps(response) return HttpResponse( json, content_type='application/json' ) then in my js code: test.js function update_item(upd_id, qta_val) { //oCtemplates = document.getElementById("t_select"); $.ajax({ type: "POST", url: "/update_cart/", data: { "updid": upd_id, "nqta": qta_val }, success: function (data) { $.each(data, function (index) { }); } }); How can i pass my django msg variable into my js for ceate an alert with this data? So many thanks in advance Manuel -
"TemplateDoesNotExist at/" issue in Python Django
Can someone assist me with the below error? I can't figure out the error here. I can't move forward with this error. I am a new learner of Django. I need to fix this issue ASAP. Thank you. -
How do I use a custom class based validator for multiple fields in Django Rest Framework?
I need to validate a field depending on another field with multiple validators like so: logged_in_id = serializers.UUIDField(validators=[Internal() | LoggedIn()]) where Internal and LoggedIn are class based validators: class LoggedIn: def __call__(self, value): if other_id == value: # other_id is another field like logged_in_id return True return False Can I access the validated_data of the serializer in a validator class somehow? Or write a validator class not for a specific field, but for the whole serializer, like the validate function? -
Django: Attributes Not Being Applied to Form
As the title states I have a django form that I am trying to customize yet for some reason the attributes are not being applied to it. I have used the exact same code in other projects and it worked perfectly except now for some reason it is not. The only other question I have found by googling is this one question. I have the exact same issue as this, I am trying to inject attributes into my label field but for what ever reason it is not working no matter what I have tried. My code is as follows: class MyAuthenticationForm(AuthenticationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget = forms.widgets.TextInput(attrs={ 'class': 'form-control' }) self.fields['password'].widget = forms.widgets.PasswordInput(attrs={ 'class': 'form-control' }) The weirdest thing was when I first started coding this morning it worked, then every subsequent time I visited my form it stopped. I truly have no idea what is going on and why this isn't working. Any help is greatly appreciated! -
how to use jquery selector to select id of django template variable value?
I have a django web app. In the html page, some element id in the for loop used django template variable value, as in the for loop every line should have different id value. But in the below jquery, when I tried to use selector, the django template variable value could not be selected(obj.title here in my case). <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script> {% for obj in query_results_book %} <td> <select name="keep_discard" id="keep_discard" onchange="GetVal(this)"> <option value="Keep">Keep</option> <option value="Discard">Discard</option> </select> <select name="discard_reason" id="{{obj.title}}"> <option value="Change edition">Change edition</option> <option value="Change to eTextbook">Change to eTextbook</option> <option value="Change title">Change title</option> <option value="No material required">No material required</option> </select> </td> {%endfor%} <script> function GetVal(obj){ var index = obj.selectedIndex; if(index == 1){ $("#obj.title").show(); } else{ $("#obj.title ").hide(); } } </script> Now the js script could not work for the query selector, it does not select my element. How could I let the jquery selector select some id, which is my django template variable value? -
How to send data (from Reactjs) through a class based API (Django Rest Framework)
I'm trying to send some form data to the backend, I always used function based api but since I couldn't find how to do what i needed I followed a tutorial and got some class based API but I don't really know how it works. Using POSTMAN and by entering all the keys and values, the request works and the data is inserted, however inside my react Project when I send the data It doesn't go in Views.py class TestView(APIView): def post(self, request, *args, **kwargs): serializer = EnrolSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) Serializers.py class EnrolSerializer(serializers.ModelSerializer): class Meta: model = Enroles fields = '__all__' Urls.py path('testapi/', TestView.as_view(), name='testing'), I'm not too sure how to send the data since I'm taking regular text-based data along with file and image Page.js import React, { useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import Registration from "./Registration"; import RegistrationSteps from "./RegistrationSteps"; import { Container, Button, Row, Col, Form } from "react-bootstrap"; import FormContainer from "../FormContainer"; import pictures from "../../pictures"; import { finalPageRegistration, } from "../../actions/registrationActions"; function RegistrationFinale({ history }) { const [dossier, setDossier] = useState(); const [avatar, setAvatar] = useState(); const dispatch = useDispatch(); const registrationInfos = useSelector((state) … -
running heroku django app from a virtual environment
I have a django app which i run from my virtual environment on my localhost and in that virtual environment i made some changes to django admin panel's html source code but when i deploy it to heroku. it installs another django with pip and doesn't run from the virtual environment i made changes to resulting into the loss of the changes i made. -
Problem with Django query on Elastic Beanstalk
I've met a problem with my Django query. So, I have a filter like this. Discount.objects.filter(end_date__gte=date.today()) #end_date is DateField It works properly on my localhost. But, on the server that I deployed with Elastic Beanstalk, it still returns yesterday's records. And, when I redeploy the server (without any changes), it works fine, yesterday's records have been filtered and hided. I tried but can't find where is the problem. Hope anyone can help me. Thank you all. -
Setup apache2 for routing internal requests
I have multiple Django applications, running on the same server under apache2 mod_wsgi, each having its own domain and conf file. etc/ ├─ apache2/ │ ├─ sites-available/ │ │ ├─ 000-default.conf │ │ ├─ a.example.com.conf │ │ ├─ b.example.com.conf These applications communicate with each other via http over the internet. I would like to route these requests locally without going through the internet seeking for reduced latency. My current setup is based on the typical Django mod_wsgi as documented. ... WSGIDaemonProcess example.com python-home=/path/to/venv python-path=/path/to/mysite.com WSGIProcessGroup example.com WSGIScriptAlias /mysite /path/to/mysite.com/mysite/wsgi.py process-group=example.com ... Any suggestion for a way to allow application A to reach application B via localhost call for internal requests ? -
How to show data from Django (DRF) to frontend of vue.js?
Here are the snippets provided required to solve the issue. I would be very thankful if anyone solve this isssue. -
How do I filter query range objects by id primary_key? Django
How I can filter 5 articles latest by slidenumber field.? class Article(models.Model): slidenumber = models.AutoField(primary_key=True) title = models.CharField(max_length=255) category = models.CharField(default='', max_length=30) description = models.TextField(default="Mo ta") bodyrichtext= RichTextField(default="", null=True) -
Is it possible to determine whether a Model's inlines have been changed during a save (update)?
class MyModel(models.Model): ... version = models.IntegerField( default=portal_settings.DEFAULT_MY_MODEL_VERSION ) ... class MyModelForm(forms.ModelForm): ... ... class MyModelQuestion(models.Model): my_model = models.ForeignKey(MyModel, on_delete=models.CASCADE) my_field = models.TextField() ... class MyModelQuestionForm(forms.ModelForm): class Meta: model = MyModelQuestion fields = ['my_field'] class MyModelQuestionInline(admin.TabularInline): model = MyModelQuestion fields = ['my_field'] can_delete = True can_edit = True extra = 0 class MyModelQuestionAdmin(admin.ModelAdmin): form = MyModelQuestionForm class MyModelAdmin(admin.ModelAdmin): form = MyModelForm inlines = (MyModelQuestionInline,) def bump_my_model_version_if_updated(sender, instance, created, **kwargs): if not created: if kwargs.get("update_fields") or <one or more of the inline objects is being updated>: <--- can't figure out how to do the second condition here instance.version += 1 instance.save() signals.post_save.connect(receiver=bump_my_model_version_if_updated, sender=MyModel) My problem is that at the moment in bump_my_model_version_if_updated() I can only tell if a direct field of the MyModel instance has been updated, but I cannot tell if any of the inline MyModelQuestion objects have been updated. The instance param of the signal is of course the MyModel instance. Is it at all possible to retrieve the MyModelAdmin (which should allow me to retrieve the inlines), or to retrieve the inlines directly from within the MyModel class? Can provide more code as requested if anything else is needed to help me out. Any suggestions appreciated! -
Getting an Error while running the python manage.py migrate
D:\Django Project\dataform>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, dataformapp, sessions Running migrations: Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute return self.cursor.execute(query, args) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right sy ntax to use near '(6) NOT NULL)' at line 1") -
How to make a this output in a string in django?
I am working in a django project where my requirement is to create a string from this output [{'Jira_Column': 'Epic', 'RelationalOperators': '=', 'Jira_Value': 'DevOps', 'LogicalOperator': ''}, {'Jira_Column': 'Sprint', 'RelationalOperators': '=', 'Jira_Value': 'DX4C Sprint 18 (FY21-Q4)', 'LogicalOperator': 'AND'}] my string should be only the values not the column names string should be like this from the output I shared: Epic = Devops AND Sprint = DX4C Sprint 18 (FY21-Q4) Here's my view def rule_assignment(request): print("check") rules = list(assignmentRule.objects.values_list('id','Developer','Epic')) print(rules) for rule in rules: assignmentRules = list(assignmentRuleItem.objects.values('Jira_Column', 'RelationalOperators', 'Jira_Value', 'LogicalOperator').filter(Rule_No = rule[0])) print(assignmentRules) return render (request, 'hello/Dependency_Management.html') And here are my models class developer(models.Model): Developer_Name = models.CharField(max_length=100, unique=True) Role = models.CharField(max_length=500) Level = models.CharField(max_length=30) Expertise = models.CharField(max_length=200) Availability_Hours = models.CharField(max_length=500) def __str__(self): return self.Developer_Name class assignmentRule(models.Model): id = models.IntegerField(primary_key=True) Developer = models.ForeignKey(developer, on_delete=models.CASCADE) Epic = models.CharField(max_length=30) def __int__(self): return self.id class assignmentRuleItem(models.Model): Jira_Column = models.CharField(max_length=100, blank=True) RelationalOperators= models.CharField(max_length=100) Jira_Value = models.CharField(max_length=500) LogicalOperator = models.CharField(max_length=30, blank=True) Rule_No = models.ForeignKey(assignmentRule, on_delete=models.CASCADE) can someone please help me to create that string like I mentioned above? -
django form: erorr passing model foreign into a form choice field
I am working with a form and model containing two foreign keys from other models. The two fk fields need to be displayed as choices in the template. I was able to do this, the form gets rendered just fine, however, there is an error when trying to save it. A couple posts were informative but none did solve my issue. It seems that the issue is not where I searched for, or at least I am unable to locate and fix it. here is what I have for models.py class Sales(models.Model): SaleID = models.AutoField(max_length=100, primary_key=True) SaleProductName= models.ForeignKey(Products, on_delete=models.CASCADE) SalePartnersName = models.ForeignKey(Partners,on_delete=models.CASCADE) SalePartnerBusinessName = models.CharField(max_length=100,default="NA") SaleQuantity = models.FloatField(max_length=100,default="NA") SaleUnit = models.CharField(max_length=100,default="NA") SaleNetAmount = models.FloatField(max_length=100) SalePartnerCommission = models.FloatField(max_length=100) SaleDate = models.DateField(default=datetime.date.today) SaleStatus = models.CharField(max_length=100,default="Ongoing") And here is my views.py def RecordNewDealView(request): if request.method == 'POST': form = RecordNewDealForm(request.POST) if form.is_valid(): form.save() return redirect('my_deals.html') else: form = RecordNewDealForm() context = {'form': form,} return render(request, 'record_new_deal.html', context) and finally here is the forms.py file brokers_df = pd.DataFrame(list(Partners.objects.all().values())) brokers = brokers_df[brokers_df['PartnerCategory'] == 'Broker'] items_list1 = brokers['PartnerName'].tolist() items_list2 = brokers['PartnerName'].tolist() CHOICES_OF_BROKERS = [list(x) for x in zip(items_list1, items_list2)] CHOICES_OF_BROKERS.insert(0,('Not involved','Not involved')) class RecordNewDealForm(forms.ModelForm): SaleStatus = forms.CharField(widget=forms.Select(choices=SALE_STATUS_CHOICES)) SalesBroker = forms.CharField(widget=forms.Select(choices=CHOICES_OF_BROKERS)) SaleProductName = forms.ModelChoiceField(queryset=Products.objects.all().values_list('ProductName', flat=True)) SalePartnerName = … -
Foreign key relation for Rest framework -- Django
I am using Django and Restframework to create a API. The data is I want the API output in such a way that "MasterResource" models is Parent, under that it filter the "Section" with matching "MasterResource" and then all the related "Items" matching with "Section". My Models are currently look like this: class MasterResource(models.Model): route_name = models.CharField(max_length=100) resourceId = models.CharField(primary_key=True, max_length=100) class ResourceSection(models.Model): resourceId = models.ForeignKey(MasterResource, on_delete=models.CASCADE, default=1) resource_name = models.CharField(max_length=100) sectionId = models.CharField(primary_key=True, max_length=100) class SectionItem(models.Model): sectionId = models.ForeignKey(ResourceSection, on_delete=models.CASCADE,default=1) item_title = models.CharField(max_length=100) image = models.ImageField(blank=True) link = models.URLField() And my views looks like this: @csrf_exempt @api_view(['POST']) @permission_classes([IsAuthenticated]) def create_resource(request): if request.method == 'POST': try: resourceId = request.POST.get("resourceId") route_name = request.POST.get("route_name") result = {} result['resourceDetails'] = json.loads(serializers.serialize('json',[MasterResource.objects.get(resourceId=resourceId)])) result['sectionDetails'] = json.loads(serializers.serialize('json',ResourceSection.objects.filter(resourceId__resourceId = resourceId))) result['itemDetails'] = json.loads(serializers.serialize('json',SectionItem.objects.filter(sectionId__sectionId=sectionId))) return JsonResponse(result, safe=False) except Exception as e: return HttpResponseServerError(e) I have achieved to receive data of "MasterResource" and its related "Sections", but the related "Items" arenot giving output Current output { "resourceDetails": [ { "model": "userdata.masterresource", "pk": "1234", "fields": { "route_name": "Testing test" } } ], "sectionDetails": [ { "model": "userdata.resourcesection", "pk": "112233", "fields": { "resourceId": 1234, "resource_name": "Test section" } }, { "model": "userdata.resourcesection", "pk": "223344", "fields": { "resourceId": 1234, "resource_name": "Test section2" … -
Django filter form appears by default as dropdown; change to checkbox
I have a model defined like below in models.py class ImageGrab(models.Model): title = models.CharField(max_length=50) slug=models.CharField(max_length=200) age=models.ForeignKey(Age, on_delete=models.CASCADE) gender=models.ForeignKey(Gender, on_delete=models.CASCADE) masked=models.ForeignKey(Mask, on_delete=models.CASCADE) withBackpack=models.ForeignKey(Backpack, on_delete=models.CASCADE) Filters for which are defined as below in filters.py: class ImageFilterAge(django_filters.FilterSet): class Meta: model = ImageGrab fields = ['age'] ###others similar to this class ImageFilter(django_filters.FilterSet): class Meta: model = ImageGrab fields = ['age', 'gender', 'masked', 'withBackpack'] The view is like below defined in views.py def images(request): imagelist = ImageGrab.objects.all() imagefilter = ImageFilter(request.GET, queryset=imagelist) agefilter = ImageFilterAge(request.GET, queryset=imagelist) genderfilter=ImageFilterGender(request.GET, queryset=imagelist) maskedfilter= ImageFilterMask(request.GET, queryset=imagelist) backpackfilter = ImageFilterBackpack(request.GET, queryset=imagelist) return render(request, 'imglist.html', {'filter': imagefilter,'agefilter': agefilter.form, 'genderfilter':genderfilter.form, 'maskfilter':maskedfilter.form, 'backpackfilter':backpackfilter.form}) My template is like this, in imglist.html <form method="get" name="search" id="search"> {{ agefilter }} <br> {{ genderfilter }} <br> {{ maskfilter }} <br> {{ backpackfilter }} <br> </form> This is rendered by default as dropdown select form as given in image link below. I want to change this to say checkbox multiple select and/ or radio button for the filters. Filtering using dropdown How to go about doing this? Thanks in advance. -
Get the details of selected item
I have a part table and delivery instruction table (dins). To create a dins, I have to choose a part name. So what I want to do is, after choosing the part name from the dropdown that part's price will be visible in the form. In the Part table, I have the price value for the specific part name. So during the creation of dins, after choosing such an example part name is X, then the form should show what is the price of that chosen part (X part) price. Any idea how to make that happen? views.py def create_deliveryins(request): from django import forms form = DeliveryInsForm() if request.method == 'POST': forms = DeliveryInsForm(request.POST) if forms.is_valid(): product = forms.cleaned_data['product'] usage = forms.cleaned_data['usage'] part= forms.cleaned_data['part'] deliveryins = DeliveryIns.objects.create( usage=usage, product=product, part=part, ) return redirect('dins-list') context = { 'form': form } return render(request, 'store/addDins.html', context) HTML <form action="#" method="post" novalidate="novalidate"> {% csrf_token %} <div class="form-group"> <label for="product" class="control-label mb-1">Product</label> {{ form.product }} </div> <div class="form-group"> <label for="part" class="control-label mb-1">Part</label> {{ form.part}} </div> <div class="form-group"> <label for="usage" class="control-label mb-1">Usage</label> {{ form.usage }} </div> </form>