Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF check if an object already exist in DB when receiving a request
I have products defined by their Name and Location. Each product has a unique pair of Name/Location. I'm writing a view to be able to create a product and I would like to first check if it exists in DB. If yes then keep the ID somewhere to return it to my front app. If no then create it and get the ID also. From my research, overriding the perform_create method should be the solution but I can't figure out how to. Any help would be appreciated. urls.py from django.conf.urls import url from main.views import product_view urlpatterns = [ url(r'^products/$', product_view.ProductCreate.as_view()), url(r'^products/(?P<pk>[0-9]+)/$', product_view.ProductDetail.as_view()), ] product_view.py from rest_framework import generics from rest_framework import permissions from main.models import Product from main.serializers import ProductSerializer class ProductCreate(generics.CreateAPIView): """ Create a new product. """ permission_classes = (permissions.IsAuthenticated,) serializer_class = ProductSerializer queryset = Product.objects.all() def perform_create(self, serializer): product_name = serializer.validated_data['product_name'] product_location = serializer.validated_data['product_location'] if product_name != '': product_list = Product.objects.filter( product_name=product_name, product_location=product_location) if not product_list: product = <my function to create the product> else: product = product_list[0] # I have no idea how to handle the following # serializer.save(...) # else: # Raise an error class ProductDetail(generics.RetrieveUpdateAPIView): """ Retrieve, update or delete a product. """ permission_classes … -
How to do price filter in django internetshop?
I downloaded free template for internetshop and there is a price slider: <div class="price-range"><!--price-range--> <h2>Price Range</h2> <div class="well text-center"> <input type="text" class="span2" value="" data-slider-min="0" data-slider-max="600" data-slider-step="5" data-slider-value="[250,450]" id="sl2" ><br /> <b class="pull-left">$ 0</b> <b class="pull-right">$ 600</b> </div> </div><!--/price-range--> How can i re write it with django to filter items with price ? -
Django: Change a model's attribute field with a form
I have rendered a list of objects in my page. Each one has an edit button next to it that you can click on, that brings up a modal window, to change the name of the model field. The model: class SensorParameter(models.Model): sensor = models.ForeignKey(Sensor) parameter = models.ForeignKey(Parameter) parameter_name_userdef = models.CharField(max_length=100, blank=False, default="Parameter") live_value = models.FloatField() Live value comes from somewhere else. Sensor and Parameter are keys to build a unique table of parameters that belong to sensors. The field I need the user to be able to edit is parameter_name_userdef where the end user can change a machine generated string to whatever they want (from "MhzV13.65Hp" to "FOO", for example). I have tried with a form, but I can't quite get it to work. I think the form is not grabbing the particular instance of the object, but instead it's instantiating a new object from the model. The form: class CustomParameterForm(ModelForm): class Meta: model = SensorParameter fields = ['parameter_name_userdef'] I only provide the value they can change. The objects are built into a table, that looks like this in the template: <tbody> {% for parameter in sensor_parameters %} <tr class="text-left"> <td class="text-center"><span>{{parameter.parameter.parameter_name}}</span></td> <td><i data-parameter-id="{{parameter.id}}" data-toggle="modal" data-target="#editCustomParam" class="far fa-edit" title="Edit … -
Tests failed on ForeignKey constraints
I'm creating a custom "upload from csv" function in my Django application, using a custom model.Manager method that receives the result of applying csv.DictReader on the csv data. My tests on normal models are okay, but they are failing on models with ForeignKey constraints. The relevant source codes are as follows models.py class PledgeManager(models.Manager): """Custom manager for model Pledge.""" def from_upload(self, data): """Process data from Pledge upload.""" for obj in data: try: # get the prospect & fund by natural key obj['prospect'] = Prospect.objects.get_by_natural_key( obj['prospect']) obj['pledge_fund'] = Fund.objects.get_by_natural_key( obj['pledge_fund']) obj['pledge_date'] = datetime.strptime( obj['pledge_date'], r'%d/%m/%Y') try: with transaction.atomic(): self.create(**obj) ccall_log.debug('Created Pledge object: %s', obj) except IntegrityError: ccall_log.error('Cannot create Pledge object: %s', obj) except Prospect.DoesNotExist: # no prospect ccall_log.error( 'Cannot create Pledge object, no Prospect: %s', obj) except Fund.DoesNotExist: # no fund ccall_log.error( 'Cannot create Pledge object, no Fund: %s', obj) except BaseException as exc_: ccall_log.exception(exc_) ccall_log.error( 'Exception encountered during processing: %s', obj) class Pledge(models.Model): """Model for a Pledge.""" objects = PledgeManager() pledge_amount = models.DecimalField( verbose_name='Pledge amount', decimal_places=2, max_digits=12, validators=[MinValueValidator(0)]) pledge_fund = models.ForeignKey(Fund, on_delete=models.CASCADE) pledge_date = models.DateField(verbose_name='Pledge date') prospect = models.ForeignKey(Prospect, on_delete=models.CASCADE) test_models.py class TestPledge(TestCase): """Test cases for Pledge.""" @classmethod def setUpTestData(cls): prospect_obj = { 'natural_key': 'Test Prospect', ... } Prospect.objects.create(**prospect_obj) Fund.objects.create(natural_key='Test … -
Django |safe template filter
Is there a way to specify characters that shouldn't be escaped is Django templates. I have the following Copyright® I don't want Django to escape the &reg ; is there a filter to do that? The workaround I've used to prevent XSS attacks is: {{object.title|safe|striptags}} Is there a better solution than this? -
Django forms getlist and valid_form
I am trying to retrieve the list of options in a select multiple (not the values selected but all the items in the choices. I have others have used: request.POST.getlist('assigned_subnets[]') However I am using a updateview and believe I need to get the data in the form_valid function. I have tried a few options to try and get the list (one in the sample below) but none have worked thus far. form valid: def form_valid(self, form): form.instance.site_data = self.site assigned_subnets = form.cleaned_data.getlist('assigned_subnets') print(assigned_subnets) return super(EditDevice, self).form_valid(form) Full form if needed: class EditDevice(UpdateView): model = DeviceData form_class = DeviceForm template_name = "config/device_form.html" @method_decorator(user_passes_test(lambda u: u.has_perm('config.edit_device'))) def dispatch(self, *args, **kwargs): self.site_id = self.kwargs['site_id'] self.site = get_object_or_404(SiteData, pk=self.site_id) return super(EditDevice, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("config:device_details", args=(self.site_id,)) def form_valid(self, form): form.instance.site_data = self.site assigned_subnets = form.cleaned_data.getlist('assigned_subnets') print(assigned_subnets) return super(EditDevice, self).form_valid(form) def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs() kwargs['site_id'] = self.site_id kwargs['device_id'] = self.object.pk return kwargs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['SiteID']=self.site_id context['SiteName']=self.site.location context['FormType']='Edit' context['active_devices']='class="active"' context['used_subnets']='class="active"' return context -
change-over system - Rails to Django: how should I treat with `encrypted_password` column in django?
I've decided to move my rails app to django app. What I'd like to know is how to treat with encrypted_password column in django app. In rails, password column is automatically saved as encrypted_password, and there is no password column. I've created User model and in database users table exists. by runnning syncdb method, I could create models.py from existing mysql database. I've set AUTH_USER_MODEL = 'myapp.Users' but mysql_exceptions.OperationalError: (1054, "Unknown column 'users.password' in 'field list'") occurs. -
Django - Generate a pdf with html block text
I'm working on a project with Django (1.12) and python(2.7). I have a function which returns me in a string the content of an html page. I need to create the html page with this string, and after to transform it to pdf (already have the function), but WITHOUT leaving my actual page. I search since this morning on the internet but i don't find something like my case. Does anybody knows if it's possible ? and if yes, how? Thanks, @Nikotine -
Django Template Nested for with If Statement
I'm trying to create a selection box in a HTML table where the given name should be selected in the combo box. In order to do this, I need to create a nested loop. The outer loop creates the rows, whereas the inner loop fills the grid cell with options for "Resources". For this example I'm only showing the code creating the Resource cell. The nested loop creates the items, and contains an if statement comparing the action.owner value with the resource.name value. If the items match, the option value should be selected. The server runs with the code, and I cannot find any hidden problems. However I'm not getting the expected results. No item is being selected. Any idea what I'm doing wrong? {% for action in actions %} <tr> <td> <SELECT class="custom-select" value = "{{action.owner}}"> {% for resource in resources %} <option value = "{{resource.name}}" {% if action.owner == resource.name %}selected="selected"{% endif %}>{{resource.name}}</option> {% endfor %} </SELECT> </td> </tr> {% endfor %} -
Returning information from database through django to UI
Can anyone tell me why information is not being displayed in my html? views.py @login_required(login_url="http://127.0.0.1:8000/accounts/login/") def userprofile(request): data = UserProfile.objects.all() return TemplateResponse(request, 'personalInfo/details.html', {"data": data}) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^details/$', views.userprofile, name='patient'), ] models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullName = models.CharField(max_length = 250, default='', blank=True) address = models.CharField(max_length = 250, default='', blank=True) gender = models.CharField(max_length = 250, default='', blank=True) dob = models.DateField(blank=True) homePhone = models.CharField(max_length = 250, default='', blank=True) personalPhone = models.CharField(max_length = 250, default='', blank=True) emergencyContact = models.CharField(max_length = 250, default='', blank=True) email = models.CharField(max_length = 250, default='', blank=True) ppsn = models.CharField(max_length = 250, default='', blank=True) maritalStatus = models.CharField(max_length = 250, default='', blank=True) employment = models.BooleanField(blank=True) personalPic = models.CharField(max_length = 250, default='', blank=True) def __str__(self): return self.fullName + ' - ' + self.ppsn I am using {{ userprofile.fullname }} to return the name of the person. I am also using profiles with a one to one link to each user. What I want to happen is when a user is logged in that his own information is displayed of course like a profile. Any help would be appreciated. Thanks. -
How to subtract two django dates in template
I want to get the number of days between today and a model field end_date. I defined today in my view as shown below. I will then use the number of days to check if its less than or equal to 50 which will add a class to the element MY TEMPLATE {% for instance in queryset %} <tr> <td>{{forloop.counter}}</td> <td>{{instance.empnumber}}</td> <td>{{instance.name}}</td> <td>{{instance.be}}</td> <td>{{instance.status}}</td> {% if (today - instance.end_date) <= 50 %} <td class="highlight">{{instance.start_date}}</td> <td class="highlight">{{instance.end_date}} : {{ instance.end_date|timeuntil:today }}</td> {% else %} <td>{{instance.status_start_date}}</td> <td>{{instance.status_end_date}}</td> {% endif %} </tr> {% endfor %} MY VIEW if request.user.is_authenticated(): queryset = Employee.objects.all().order_by('-last_updated') today = date.today() context = { "queryset": queryset, "today": today, } -
Search with ajax + django view
can u please help me. I want to create search using ajax function and django view. There are input and submit button. When I clicked on submit button, jQuery takes value of input and create ajax request. Its good. But in the view, when i want to print serch_by value in console, there is an output: None qwer asdf zxvc <- value of input I think it is a problem. But maybe no. Help me, please. HTML: <form id="searchform" {% csrf_token %} <input name="q" type="text" id="search"> <button type="submit" id="searchsubmit"></button> </form> JS: function initSearchForm(){ $('#searchsubmit').on('click', function(e){ e.preventDefault(); q = $('#search').val(); updateContentBySearch(q); }); } function updateContentBySearch(q) { var data = {}; data['search_by'] = q data["csrfmiddlewaretoken"] = $('#searchform [name="csrfmiddlewaretoken"]').val(); $.ajax({ url: "/search_products/", type: 'GET', data: data, success: $('.product_content').load(url, function() { ... }), }); } View: def search_products(request): data = request.GET search_by = data.get('search_by') print(search_by) # The console is displayed first 'None' and at the next line value of search_by if search_by: q = Q() for tag in search_by.split(): q |= Q(brand__brand_name__iexact=tag) | Q(model__iexact=tag) products = Product.objects.filter(q) return render(request, 'main/product_content.html', {'products': product}) -
In a tree filter nodes and its childs
I have an app with categories and products, categories and products can be inactive, on inactive category do not show its children, for example: All categories are active, tree looks like this: Category 1-1 Product 1-1 Category 2-1 Product 2-1 Category 3-1 Product 3-1 Category 3-2 Category 2-2 Product 2-2 If I set Category 2-1 to inactive, I want to see result like this: Category 1-1 Product 1-1 Category 2-2 Product 2-2 I have created a method which do a filter, but I am using a recursion, if a tree has a very high deep for example depth=100 and category is inactive in depth = 2, I get max depth recursion error. def filter_category_products(self): inactive_category_ids = get_inactive_categories_ids() queryset = Category.objects.exclude(id__in=inactive_category_ids).prefetch_related(Prefetch('product_set', queryset=Product.objects.filter(is_active=True))) return queryset def get_inactive_categories_ids(): inactive_categories_ids_query = Category.objects.filter(is_active=False).values_list('id', flat=True) inactive_ids = [] for i in inactive_categories_ids_query: inactive_ids.append(i) ids = [] while inactive_ids: for inactive_id in inactive_ids: if(inactive_id not in ids): ids.append(inactive_id) inactive_ids = Category.objects.filter(parent_id__in = inactive_ids).values_list('id', flat=True) return ids My question would be is there any other algorithm how could I filter that without recursion so I would avoid the error and editing max recursion limit in python sys resource. -
Angular 5 + Django - How to handle user permissions
I have an Angular v5 web application backed by Django REST Framework. Previously the application was totally relying on Django templates. Now, I'm using Angular and it is not clear to me how permissions are managed. The application has different sections. Regarding the product section, the permissions can be summed up as follow: Course grain permissions Can the user see a product? Can the user change a product? Can the user delete a product? Can the user create a product? Fine grain permissions Can the user see product SKU? Can the user see product pricing? ... Fine-grained permissions are very important because there're users that can see the product list where on Angular has been implemented as a table, but few users cannot see certain columns. My question is how I can handle permissions on Django and Angular? My idea was, when the user logs in, Angular got from backend all user permissions and then Angular won't show accordingly to the user. Anyway, I don't think this is a safe solution since permissions can easily manipulated by the user from JS console. What's usually the best practice for this? -
Django: foreign key access through related objects
Suppose I have a model Profile that relates to the standard User model through either a ForeignKey with unique=True relationship, or a OneToOne relationship: class Profile(models.Model): user = (either a ForeignKey/OneToOne relationship) ... If I have understood the documentation, the database representation of the column will be user_id, from Django automatically adding _id. This user_id will contain a series of integers. Suppose again I instantiate an object of this model in the shell, and try and access the user attribute: a_profile = Profile() a_profile.user From what I have read, the user attribute should now be a descriptor, and accessing it will invoke it's __ get __ method, giving me access to the related model instance - in this case the User instance. MY QUESTION: I have noticed that I can access the Profile instance through the User instance as well, through: user_profile = User.objects.all()[0] user_profile.profile What is happening here? Is this working the same way as accessing the user attribute of the Profile instance - is the profile attribute on a User instance a descriptor as well? Thank you! -
How to display all session variables in django 2.0?
How to display all session variables in Django 2.0? result, data1 = GetLoginUser(request) request.session['profile']=data1 ipdb> request.session['profile'] [{'address': 'asdfsd', 'email': 'nitesh@scaledesk.com', 'mobile': '9570277820', 'category': 'getpass', 'designation': 'dsfsd', 'name': 'employee'}] ipdb> request.session['profile'][0] {'address': 'asdfsd', 'email': 'nitesh@scaledesk.com', 'mobile': '9570277820', 'category': 'getpass', 'designation': 'dsfsd', 'name': 'employee'} how to print data in template template.html.j2 {{request.session.GET['profile']}} getting error This page isn’t working localhost redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS -
Django forms - maximum recursion depth exceeded on get_context_data
I'm getting a maximum recursion depth exceeded error on one of my Django forms. The trace is pointing to get_context_data but I am unsure as to why or what the underlying issue is/may be. I use this same code on all my other forms without issue. ive read this is usually due to URLs but I can't seem to find the fault with that either. the add view works which uses almost the same code too traceback is: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/itapp/itapp/circuits/views.py" in dispatch 317. return super(EditFile, self).dispatch(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/edit.py" in get 236. return super(BaseUpdateView, self).get(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/edit.py" in get 174. return self.render_to_response(self.get_context_data()) ... File "/itapp/itapp/circuits/views.py" in get_context_data 332. context = EditFile().get_context_data(**kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in __init__ 43. for key, value in six.iteritems(kwargs): Exception Type: RecursionError at /circuits/file/edit/5/7/site_cl Exception Value: maximum recursion depth exceeded my view is as follows: class EditFile(UpdateView): model = CircuitFiles form_class = FileForm … -
Configure codehilite in Django
I'm a beginner to Django, so I haven't had much luck; what I'm trying to do is seemingly simple. I am working with the Django wiki package, and I'm trying to find out where I can modify the config variable in to the highlight function in wiki/core/markdown/mdx/codehilite.py: def highlight(code, config, tab_length, lang=None): code = CodeHilite( code, linenums=config['linenums'], guess_lang=config['guess_lang'], css_class=config['css_class'], style=config['pygments_style'], noclasses=config['noclasses'], tab_length=tab_length, use_pygments=config['use_pygments'], lang=lang, ) html = code.hilite() html = """<div class="codehilite-wrap">{}</div>""".format(html) return html By simply modifying guess_lang=config['guess_lang'], to guess_land=False, the problem is temporarily fixed by simply ignoring the input value. I'm looking for a permanent solution. -
django rest framwork Column 'product_id' cannot be null
i have this view i want save a record in db when product id recived with post method class PeymentAPIView(APIView): def post(self, request, *args, **kwargs): serilizer = PeymentSerializer(data=request.data) if serilizer.is_valid(): serilizer.save(user=request.user, status=0) return Response("ok") else: #return Response(serilizer.errors) return Response(status=status.HTTP_400_BAD_REQUEST) with post man im sending this with post method : { "product": 2 } but i have this error can you please tell my why (1048, "Column 'product_id' cannot be null") this is my serializer : # product peyment class PeymentSerializer(ModelSerializer): product = serializers.SerializerMethodField() def get_product(self, obj): return obj.product.product_id user = serializers.SerializerMethodField() def get_user(self, obj): return obj.id class Meta: model = Peyment fields = [ 'product', 'status', 'user', 'transfer_id', 'created_date', 'updated_date', ] read_only_fields = ['user'] and it is related model : class Peyment(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='product_id', related_name='product_peyment') status = models.CharField(max_length=30, null=True) user = models.ForeignKey(User, on_delete=models.DO_NOTHING) transfer_id = models.CharField(max_length=100, null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) -
source command no work in bash ubuntu 17.10
I am use ubuntu 17.04 and not work the next command,I work with this command an other time and it worked for me. !/bin/bash APP=personalBlog USER=root cd /opt/src/personalblog/conf/ source /opt/venv/ecomex/bin/activate uwsgi -c uwsgi.ini the error show is: /opt/src/personalblog/conf/run.sh: 7: /opt/src/personalblog/conf/run.sh: -c: not found /opt/src/personalblog/conf/run.sh: 8: /opt/src/personalblog/conf/run.sh: uwsgi: not found -
how to get the USER_TOKEN and USER_SECRET in linkedin
I am not able to get the User_TOKEN and USER_SECRET from linkedin. I got only Client ID and Client Secret and i am unable to fallow steps to get User_TOKEN and User_SECRET please help me to get the steps for interaction for outh 2 -
Allow user to edit once in django
Details: I have a teacher dashboard where a teacher can create and share worksheets with other teachers. When any worksheet is shared with other teachers they can (but not necessary) provide feedback on that worksheet, which will be visible to the creator of worksheet. Now I have a model which stores this sharing thing as follows: class SharingWS(TimeStampWS): shared_by = models.ForeignKey('members.Profile', on_delete=models.CASCADE, related_name='shared_by') shared_with = models.ForeignKey('members.Profile', on_delete=models.CASCADE, related_name='shared_with') worksheet = models.ForeignKey('WorkSheet', on_delete=models.SET_NULL, null=True) flag = models.BooleanField() reason = models.TextField(blank=True) as soon as the worksheet is created, an entry is created in the model with default flag=True. Problem Now how can I give only one chance to other teachers to review the worksheet. Once they have given a feedback, they cant do it again and if they dont give feedback it will be assumed approved after 2 days. There are similar questions but for voting, where there is no previous entry in db and you can lookup. In my case an entry is already created so I cant use that concept. -
Delete object in template using DeleteView without confirmation
I'm trying to write DeleteView for deleting posts: Del - delete button. How can i delete object properly? urls.py urlpatterns = [ # url(r'^$', views.index, name='index'), url(r'^feed$', views.FeedView.as_view(), name='feed'), url(r'^summary(?P<pk>\w{0,50})', views.SummaryCreate.as_view(), name='summary'), url(r'^summary(?P<user_id>\w{0,50})/(?P<pk>\w{0,50})/', views.SummaryDelete.as_view(), name='delete_summary'), url(r'^dashboard$', permission_required('reed.view_dashboard')(views.DashboardListView.as_view()), name='dashboard'), url(r'^dashboard/(?P<pk>\w{0,50})', permission_required('reed.view_dashboard')(views.DashboardUpdate.as_view()), name='review_summary'),] views.py class SummaryDelete(LoginRequiredMixin, generic.DeleteView): model = Summary def get_success_url(self): return reverse('summary', args=(self.request.user.id.hex,)) def get(self, *args, **kwargs): print('i\'m trying to delete') return self.delete(*args, **kwargs) template.html <h3> <a class="delete" href="{% url 'delete_summary' user.id.hex summary.id.hex %}" aria-hidden="true">Del</a> {{summary.title}} </h3> -
Dictionary inside a dictionary in django template
Eg: i have dictionary which has: a = {'card1' :{'name':'abc,'amount':'145820'},'card2':{'name':'dba','amount':'258963'}} now i want to print the crad1.amount in django template. -
Django url with parameters in template in multiple lines
I have this type of url in my template: <a href="{% url 'company-detail' region=ownership.company.city.province.region.slug province=ownership.company.city.province.slug city=ownership.company.city.slug company=ownership.company.slug %}"> That is, as you can see, monstrously long. There is some way to do the same thing in multiple lines? Something like this: <a href="{% url 'company-detail' region=ownership.company.city.province.region.slug province=ownership.company.city.province.slug city=ownership.company.city.slug company=ownership.company.slug %}">