Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django object data disappears when I refresh page
When I load the page for the first time, the object data is there (so three links in the example below), after starting runserver on my computer. If I reload the object data is not longer there (so zero links in the example below). template {% for url in urls %} <a href="{{ url }}"> link </a> {% endfor %} view class IntroView(View): template_name = '[app_name]/template.html' model_names = ['shoe', 'hat', 'bag'] urls = [reverse_lazy('%s:%s' % ('[app_name]', name)) for name in model_names] dict_to_template = {'urls': urls} def get(self, request, *args, **kwargs): return render(request, self.template_name, context=self.dict_to_template) It's probably something really simple, but it's got me. Thank you for your time. -
Using LDAP authentication - extending user model
I'm currently using 'django_python3_ldap.auth.LDAPBackend', which I have working correctly were a user authenticates with their network login / password then a user is created in the data base with username, password, email, first_name, and last_name, user_created_at all extracted from LDAP, which is what I want to stay the same. Now The network login is the username in the auth_user table. I have another table, which stores user information with a field titled employee_ntname, the table below is a pre-existing table in the database which can not be changed or updated for this use case. class AllEeActive(models.Model): employee_ntname = models.CharField(db_column='Employee_NTName',max_length=50) # Field name made lowercase. employee_last_name = models.CharField(db_column='Employee_Last_Name', max_length=50, blank=True, null=True) # Field name made lowercase. employee_first_name = models.CharField(db_column='Employee_First_Name', max_length=50, blank=True, null=True) # Field name made lowercase. b_level = models.CharField(db_column='B_Level', max_length=10, blank=True, null=True) # Field name made lowercase. group_name = models.CharField(db_column='Group_Name', max_length=100, blank=True, null=True) # Field name made lowercase. r_level = models.CharField(db_column='R_Level', max_length=10, blank=True, null=True) # Field name made lowercase. division_name = models.CharField(db_column='Division_Name', max_length=100, blank=True, null=True) # Field name made lowercase. d_level = models.CharField(db_column='D_Level', max_length=10, blank=True, null=True) # Field name made lowercase. market_name = models.CharField(db_column='Market_Name', max_length=100, blank=True, null=True) # Field name made lowercase. coid = models.CharField(db_column='COID', max_length=50, blank=True, null=True) # Field … -
Altering href after document load with jQuery
I have the following jQuery fs_body.append('<div class="fs_title_wrapper ' + set_state + '"><a href=""><h1 class="fs_title"></h1></a><h3 class="fs_descr"></h3></div>'); With this, what I would like to do is target the href attribute of the element and add in the link dynamically. On the templating side I have the following: <script> gallery_set = [ {% for feature in features %} {type: "image", image: "{{ MEDIA_URL }}{{ feature.image_scroll_1.url }}", title: "{{ feature.title }}", description: "{{ feature.lead_in }}", href:{{ % feature.get_absolute_url %}}, titleColor: "#ffffff", descriptionColor: "#ffffff"}, {% endfor %} ] </script> How do I now target that href in the appended body inside the fs_title_wrapper class div? -
update_or_create Django 1.10
Hi I have live data coming in from an API, Since we have the same SKU, in multiple markets, I need a composite PK, (SKU, Country), I know Django does not support this, so I am using the update_or_create function. My issue is that the data keeps duplicating as the quantity values change country merch quantity sku USA CC 2807 1005 B00VQVPRH8 USA CC 2806 1004 B00VQVPRH8 Here is the call to save the data: obj, created = FBAInventory.objects.update_or_create( Account=merchant["company"], ASIN=ASIN, TotalSupplyQuantity=TotalSupplyQuantity, InStockSupplyQuantity=InStockSupplyQuantity, FNSKU=FNSKU, EarliestAvailability=EarliestAvailability, defaults={'SellerSKU': SellerSKU, 'Country': merchant["country"]}, ) Am I using the function incorrectly, I want to update the SKU/Country row, I do not want a duplicate with different quantity values. I know I can use get, but I want to take advantage of this function so I don't have to write a conditional statement. Should defaults hold the update values and the kwarg hold the values to match? -
Django form not saving to database
I'm having trouble saving form fields to my database. I know that it isn't saving because if I look at the Player model in django, there is always 0 data. If anyone could take a look and correct me, I would be very thankful. models.py - from django.db import models class Player(models.Model): player_one_name = models.CharField(max_length=30, default='') player_two_name = models.CharField(max_length=30, default='') forms.py - from django import forms class PlayerInfo(forms.Form): player_one_name = forms.CharField(max_length=30, label='First player name') player_two_name = forms.CharField(max_length=30, label='Second player name') views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, render_to_response import os from .forms import PlayerInfo from .models import Player def start(request): if request.method == 'Post': form = PlayerInfo(request.POST) if form.is_valid(): obj = Player() obj.player_one_name = form.cleaned_data['fp_name'] obj.player_two_name = form.cleaned_data['sp_name'] form.save() return HttpResponseRedirect('/game/') else: form = PlayerInfo() args = {'form': form} return render(request, 'start.html', args) start.html - Meant to submit each player's name {% block botRow %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} game.html - Meant to render each player's name {% extends 'base.html' %} {% block midRow %} <p>{{ fpn }}</p> <p>{{ spn }}</p> {% endblock %} -
Django conditional javascript file in template causes missing staticfile error in production only
I have a conditional in a template used by several views which will include a js file if passed in by the view: in the template: {% if js_file %} {% block inner_js %} <script defer type="text/javascript" src="{% static js_file %}"></script> {% endblock inner_js %} {% endif %} which is eg used by a view by: ....... context = {'title': 'Sign up', 'form': form, 'js_file': 'js/supplier.js'} return render(request, 'pages/signup.html', context) This produces no errors in development, but when pushed to production I get the error: ValueError at /users/example/ Missing staticfiles manifest entry for '' If I remove the template if block above then this error dissapears (and works fine for those views which use the template without a js file). I would rather not have to create a new version of the template for every view which uses a js file, is their a better way to fix this? (seems a bit of a weird error). -
Django post form lost filed
I post form then lost a file, but it happens sometimes. enter image description here this is the from: class UniversityForm(forms.Form): # Select Dropdown university = forms.ModelChoiceField( queryset=University.objects.filter( recommended=True ), empty_label='Other', required=False ) school_country = forms.ChoiceField(choices=CIIP_COUNTRIES, label='University Country', required=False) school_name = forms.ChoiceField(choices=DEFAULT_CHOICES, label='University', required=False ) school_name_other = forms.CharField(label='University Name', required=False) # name = forms.CharField(label='University Name', required=False) contact_name = forms.CharField(label='Contact Name', widget=forms.TextInput(attrs={'placeholder': 'University Representative'}), required=False) contact_title = forms.CharField(label='Contact Title', widget=forms.TextInput(attrs={'placeholder': 'University Representative'}), required=False) contact_email = forms.EmailField(label='Contact Email', widget=forms.TextInput(attrs={'placeholder': 'University Representative'}), required=False) # country = forms.CharField(label='Country', widget=forms.TextInput(attrs={'placeholder': 'University Country'}), required=False) current_degree = forms.CharField(label='Current Degree', required=False) degree_type = forms.ChoiceField(label='Degree Type', required=False, choices=DEGREE_TYPES) last_gpa = forms.DecimalField(label='Grade Point Average', required=False, widget=forms.TextInput(attrs={'placeholder': 'Grade Point Average'})) graduation_year = forms.IntegerField(label='Graduation Year', widget=forms.TextInput(attrs={'placeholder': 'eg: 2017'}), required=False, min_value=1950, max_value=2045) if request.method == 'POST': # Instantiate the university form params.update({ 'form':UniversityForm( request.POST ) }) # Update university dropdown with our ajax choices so it can pass validation sem = request.POST.get('school_name') params.get('form').fields['school_name'].choices = [(sem, sem)] # Verify that the form is valid if params.get('form').is_valid(): gpa = params.get('form').cleaned_data['last_gpa'] if gpa > 100: params.update({'error': 'The GPA you entered is too high.'}) return render(request, 'student/index.html', params) else: # if no university data is entered, and it needs to be entered always. if params.get('form').cleaned_data['school_country'] == '' … -
Django query: Getting data over two relationships
I already googled much and read this site https://docs.djangoproject.com/en/1.11/topics/db/queries/ several times but I still have problems to get the right data. I extended the standard Django-User-Model with a MAC-Adress because I will need it later. I also have a relationship between the models like this: One "Django-Standard-User" has ONE UserProfile ONE "UserProfile" has MANY CalData from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User) mac = models.CharField(max_length=17, default='00:00:00:00:00:00') def __str__(self): return self.user.username class CalData(models.Model): user = models.ForeignKey(UserProfile) date = models.DateField(default="1970-01-01") timestamp = models.TimeField(default="00:00:00") entry_id= models.CharField(max_length=100, default="NoID") Now from the view, after the User has logged in, i want to make a query like this: "give me a Query (nor Objects) of Caldata where user = "the username of the Standard-Django-User" and where Date = Today. The second Question is: Is it better to set the ForeignKey of Caldata to "UserProfile" like I did or is it better to set it to "User" (standard Django-Model). My Goal is to say: One User has one unique MAC-Adress and many CalData. -
How do you paginate a viewset using a paginator class?
According to the documentation: Pagination is only performed automatically if you're using the generic views or viewsets But this doesn't seem to be the case. Here's what I have for my viewset: views.py class EntityViewSet(viewsets.ModelViewSet): def list(self, request): queryset = Entity.objects.all() serializer = EntitySerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Entity.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = EntitySerializer(user) return Response(serializer.data) Here's my urls entity_list = views.EntityViewSet.as_view({'get':'list'}) entity_detail = views.EntityViewSet.as_view({'get':'retrieve'}) ... url(r'^entity/$', entity_list, name='entity-list'), url(r'^entity/(?P<pk>[0-9]+)/$', entity_detail, name='entity-detail'), ... This is my pagination class class PagePaginationWithTotalPages(pagination.PageNumberPagination): page_size = 30 page_size_query_param = 'page_size' max_page_size = 1000 def get_paginated_response(self, data): return Response({ 'next': self.get_next_link(), 'previous': self.get_previous_link(), 'count': self.page.paginator.count, 'total_pages': self.page.paginator.num_pages, 'results': data }) and I set it in settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_PAGINATION_CLASS': 'myapp.pagination.PagePaginationWithTotalPages', 'UNICODE_JSON': False, } Now while this works for ListAPIView it doesn't appear to work for my viewset. Is there a step that I'm missing? -
bulk_create - TypeError: cannot convert the series to <class 'float'>
When I run this code records = [] for dt in rrule(DAILY, dtstart=a, until=b): records.append( Object(price=predictions_df1.loc[dt.strftime("%Y-%m-%d")], symbol = 'TFSM', date=dt.strftime("%Y-%m-%d"))) Object.objects.bulk_create(records) I get an error - TypeError: cannot convert the series to <class 'float'>. Does anyone have an idea how can I solve it? I tried .apply(np.float64) , .convert_objects(convert_numeric=True) etc. but nothing works. My Object looks in this way: class Object(models.Model): symbol = models.CharField(max_length=200) date = models.DateField(default=datetime.now, blank=True) price = models.FloatField() -
Django trigger post_save on update()
So I am using django-simple-history module that tracks changes in Model instances. However, it uses post_save signal to do so. In my project, I also need it to trigger on update(). My question is: How to overwrite the update() method to trigger post_save signals? -
module 'oscar' has no attribute 'OSCAR_MAIN_TEMPLATE_DIR'
I try to deploy my django-oscar app on heroku but when I run the migration : heroku run sandbox/manage.py migrate the following error occured: (the database used is postgresql and i've installed all requirements but i don't know the source of the problem) 2017-10-24T16:02:49.121254+00:00 heroku[run.8440]: Starting process with command `sandbox/manage.py migrate` 2017-10-24T16:02:49.731452+00:00 heroku[run.8440]: State changed from starting to up 2017-10-24T16:02:52.721398+00:00 heroku[run.8440]: State changed from up to complete 2017-10-24T16:02:52.595920+00:00 app[run.8440]: Traceback (most recent call last): 2017-10-24T16:02:52.595939+00:00 app[run.8440]: File "sandbox/manage.py", line 10, in <module> 2017-10-24T16:02:52.596126+00:00 app[run.8440]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line 2017-10-24T16:02:52.596124+00:00 app[run.8440]: execute_from_command_line(sys.argv) 2017-10-24T16:02:52.596439+00:00 app[run.8440]: utility.execute() 2017-10-24T16:02:52.596734+00:00 app[run.8440]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ 2017-10-24T16:02:52.596730+00:00 app[run.8440]: settings.INSTALLED_APPS 2017-10-24T16:02:52.597070+00:00 app[run.8440]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ 2017-10-24T16:02:52.596912+00:00 app[run.8440]: self._setup(name) 2017-10-24T16:02:52.597067+00:00 app[run.8440]: self._wrapped = Settings(settings_module) 2017-10-24T16:02:52.596915+00:00 app[run.8440]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup 2017-10-24T16:02:52.597249+00:00 app[run.8440]: mod = importlib.import_module(self.SETTINGS_MODULE) 2017-10-24T16:02:52.597438+00:00 app[run.8440]: return _bootstrap._gcd_import(name[level:], package, level) 2017-10-24T16:02:52.597622+00:00 app[run.8440]: File "<frozen importlib._bootstrap>", line 961, in _find_and_load 2017-10-24T16:02:52.597996+00:00 app[run.8440]: File "<frozen importlib._bootstrap_external>", line 678, in exec_module 2017-10-24T16:02:52.597748+00:00 app[run.8440]: File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked 2017-10-24T16:02:52.598147+00:00 app[run.8440]: File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed 2017-10-24T16:02:52.597443+00:00 app[run.8440]: File "<frozen importlib._bootstrap>", line 978, in _gcd_import 2017-10-24T16:02:52.597878+00:00 app[run.8440]: File "<frozen importlib._bootstrap>", line 655, in _load_unlocked 2017-10-24T16:02:52.597253+00:00 app[run.8440]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", … -
Django sites framework and authentication
I want to build a web application using Django. Basically a CRM for specific business type. Lets say it's for Gyms for this explanation. I will have multiple customers. The customers will each get their own 3rd level domain name. Like golds.gym.com and 24hrfitness.gym.com. Each customer will have their own customers that will use the site as well. I want to allow overlapping usernames across sites, but unique to each site. I would also like to use the built in admin pages, but I will need to be sure that the admin pages are site specific. My question is more or less, "Is this possible". But I think what I really want to know is "Is this possible using something built in or something someone else has out there for Django?" I have looked at the sites framework documentation and that seems to be what I need, however I have not found any documentation on how to make the admin and the users site specific. -
AttributeError: module 'django.contrib.postgres.fields' has no attribute 'JSONField'
Installing project from GitHub repo and receive following error after all File "/Users/TheKotik/closer/blog/models.py", line 5, in <module> from rest_framework import serializers File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/rest_framework/serializers.py", line 1534, in <module> ModelSerializer.serializer_field_mapping[postgres_fields.JSONField] = JSONField AttributeError: module 'django.contrib.postgres.fields' has no attribute 'JSONField' Have no idea, what it's related to. Please help.. The whole traceback: File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/Users/TheKotik/closer/blog/models.py", line 5, in <module> from rest_framework import serializers File "/Users/TheKotik/closer/denv/lib/python3.5/site-packages/rest_framework/serializers.py", line 1534, in <module> ModelSerializer.serializer_field_mapping[postgres_fields.JSONField] = JSONField AttributeError: module 'django.contrib.postgres.fields' has no attribute 'JSONField' -
reverse() got an unexpected keyword argument 'pk_url_kwarg' - UpdateView
I am trying use Django built-in class UpdateView to update an image model The model is: def get_image_path(instance, filename): return '/'.join(['studyoffer_images', instance.study_offer.slug, filename]) class UploadStudyOffer(models.Model): study_offer = models.ForeignKey(StudiesOffert, related_name='uploadsstudyoffer') image = models.ImageField(upload_to=get_image_path, verbose_name='Seleccionar imagen') # images folder per object featured = models.BooleanField(default=False, verbose_name='Destacada', help_text='Indica si la imagen aparecera en el carrusel') thumbnail = models.BooleanField(default=False) active = models.BooleanField(default=True, verbose_name='Activa', help_text='Indica si una imagen de oferta esta habilitada o disponible') objects = UploadStudyOfferManager() def __str__(self): return self.study_offer.ad_title The form of this model is: class StudyOfferImagesUploadForm(forms.ModelForm): class Meta: model = UploadStudyOffer fields = ('image', 'active', 'featured') What I want now is to allow the user to edit an image and can change it and change the status image (featured, active, thumbnail) Then I build my StudyOfferImageUpdateView to update the image attributes: class StudyOfferImageUpdateView(SuccessMessageMixin, UserProfileDataMixin, LoginRequiredMixin, UpdateView): model = UploadStudyOffer form_class = StudyOfferImagesUploadForm success_url = reverse_lazy("host:edit-study-offer-image", pk_url_kwarg='pk') success_message = "Imagen actualizada" def get_context_data(self, **kwargs): context = super(StudyOfferImageUpdateView, self).get_context_data(**kwargs) user = self.request.user return context def get_object(self): return get_object_or_404(UploadStudyOffer, pk=self.kwargs.get('pk')) The URL to access this view is: url(r"^study-offer/edit/images/(?P<pk>\d+)/$", StudyOfferImageUpdateView.as_view(), name='edit-study-offer-image' ), When I want edit my image the template is this: {% block body_content %} <h2>Editar imágen</h2> <form role="form" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ … -
How to extract values from queryset objects in python?
I'm trying to compare values to each other for a quiz in django. I'm using POST data for object data and trying to compare each other. Current code: answerList = [] answerList2 = [] for i in Question.objects.filter(related_quiz = examid): answerList.append(i.answer) form = EditQuizForm() form = EditQuizForm(request.POST) if request.method == "POST": form = EditQuizForm(request.POST) submittedObject = request.POST.copy() newList = (dict(submittedObject.lists())) values = newList.values() for i in values: answerList2.append(i) print(answerList) print(answerList2) This returns the values: ['A', 'D'] [['A'], ['D']] However, I cannot iterate over these to compare them as they are not the same. I do not how get answerList2 to appear like answerList1 so i can compare the values. Any help would be appreciated as i am fairly new to python/django. -
Django foreign key default
I'm using CreateView to add a Section with a foreign key to Course. If I have a default value for the foreign key, it always saves as the default value. If I don't have a default value, it always saves as null or blank. class Course(models.Model): course_name = models.CharField(max_length=50) course_code = models.CharField(max_length=8, unique=True) atype = models.CharField(max_length=10, default='Course') def get_absolute_url(self): return reverse('calculate:course_detail', kwargs={'pk': self.pk}) def __str__(self): return self.course_name class Section(models.Model): section_name = models.CharField(max_length=50) percentage = models.IntegerField(default=100, validators=[ MaxValueValidator(100), MinValueValidator(1) ]) atype = models.CharField(max_length=10, default='Section') section_section = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE) section_course = models.ForeignKey('Course', blank=True, null=True, on_delete=models.CASCADE) def get_absolute_url(self): if self.section_course is None: pk = self.section_section.pk else: pk = self.section_course.pk return reverse('calculate:course_detail', kwargs={'pk': pk}) def __str__(self): return self.section_name Here's the CreateView: class SectionCreate(CreateView): model = Section fields = ['section_name', 'percentage', 'section_section', 'section_course'] def get_initial(self): pk = self.kwargs['pk'] course = Course.objects.get(pk=pk) return {'section_course': course} def get_form(self, form_class=None): pk = self.kwargs['pk'] course = Course.objects.get(pk=pk) form = super(SectionCreate, self).get_form(form_class) form.fields['section_section'].queryset = Section.objects.filter(section_course=course) return form def get_context_data(self, **kwargs): pk = self.kwargs['pk'] s_type = self.kwargs['s_type'] context = super(SectionCreate, self).get_context_data(**kwargs) if s_type == 'Course': course = Course.objects.get(pk=pk) self.model.section_course = course if s_type == 'Section': s = Section.objects.get(pk=pk) section.section_section = s context['course'] = course context['pk'] = pk context['s_type'] = … -
The best way to hash password with Django & custom user in all the possible create/save cases?
I have a custom user which is inherited from Django's AbstractBaseUser and PermissionsMixin. From that custom user I'm going to inherit two other user types. I'm also using Django Rest Framework. For the custom user I've made a custom user manager which hashes the password. I already overrode the create method for serializer linked to that custom user model and models inherited from it. I need to hash the password no matter through which functionality/method the user is created (also in the cases when a object of model inherited from the custom user is created). I also need to hash the password in case the user wants to reset his/her password (this goes for those inherited models too). How do I ensure that? In other words, how many and what create/save methods I have to override? To the architecture itself, could it be possible to use Django's default user model so that the email is a username and that username and email fields are always synced together? -
How do I pass an array to a custom Django database function?
I'm trying to write a Django wrapper for PostgreSQL's width_bucket like this: from django.db.models import Func from django.db import models class Log2Bucket(Func): template = "width_bucket(%(expressions)s::double precision[])" def __init__(self, expression, a, b, **extra): buckets = [] while a <= b: buckets.append(str(a)) a *= 2 buckets = Value(buckets, output_field=ArrayField(models.FloatField())) super().__init__(expression, buckets, output_field=models.PositiveSmallIntegerField(), **extra) This works for queries like Foo.objects.annotate(b=Log2Bucket('bar', 125, 100000)).values('b') But for from django.db.models import Count (Foo.objects.annotate(b=Log2Bucket('bar', 125, 100000)) .values('b').annotate(count=Count('pk'))) I get a TypeError: unhashable type: 'list' from inside Django. How do I fix this? Is there an approach that makes this function less hacky? I've tried using function = 'width_bucket' instead of template = ..., but then I get a PostgreSQL error function width_bucket(double precision, numeric[]) does not exist. -
Django class based view form_class choice
I've a single View, that can be called with or without the label_rif attribute, based on this I can switch the form_class and template? class LabelCreateView(CreateView): model = models.Label if self.kwargs['label_rif'] > 0: form_class = LabelForm template_name = 'AUTO_form.html' else: form_class = LabelManForm template_name = 'MAN_form.html' I've tried to insert the form_class without succes in the method def get_form_kwargs(self): kwargs = super(LabelCreateView, self).get_form_kwargs() if self.kwargs['label_rif']: form_class = LabelForm Or should I define another separate view? I want to keep it DRY, is it possible? -
Python and PG Copy
I have the code below which downloads a CSV to memory using sqlalchemy inside of a Django application. engine = create_engine('postgres://.....') response = requests.get(STOCK_DATA_URL) zip_file = ZipFile(BytesIO(response.content)) data_file_name = zip_file.namelist()[0] new_prices = zip_file.open(data_file_name) df = pd.read_csv(new_prices, names=['ticker', 'name']) Instead of loading it into a dataframe, how would I save it to the database using pg_copy which works manually. \copy stock_tickers (ticker, name) FROM '<FILE NAME>' DELIMITER ',' CSV; -
Django (Ubuntu): What is the best way to use npm for front-end dependency management
How I used to create my Django projects mkvirtualenv env1 - creates virtual environment env1 pip install -r requirements.txt - install some python modules pip install nodeenv - for isolated node environments nodeenv -p - This commands installs nodejs and adds new shell functions to our virtualenvwrapper shell functions. Directory node_modules was put inside env1 directory npm install -g bower - Bower directory was put in node_modules inside env1. pip install django-bower - I set BOWER_COMPONENTS_ROOT = '/PROJECT_ROOT/components/' I set BOWER_INSTALLED_APPS and run ./manage.py bower install. Packages listed in BOWER_INSTALLED_APPS were installed into '/PROJECT_ROOT/components/bower_components' at the end I used django-compressor However Bower is now apparently no longer a thing, so i need a new setup. For now I decided, that I'm gonna use only npm for front-end dependency management. So my question is, if the following setup is good enough. NOTE - I am a complete rookie regarding npm and javascript environments Create nodeenv environment inside virtualenv env1. Then in django project root I run npm init which creates package.json, and then from the same directory I run npm install foundation-sites --save for example. This creates node_modules in project root. Then I could use django-compressor with precompilers that work on … -
Python coding assignment
Design an algorithm to calculate Score for the UNIT. An UNIT contains many SECTIONS. SECTION contains many QUESTION. Question has multiple choices with selected values (each choice has weight associated with it). The score for UNIT is calculated as average score for all SECTIONS in the UNIT. The score for SECTION is calculated as sum of score of all QUESTIONS in that SECTION. The score for QUESTION is calculated as weight of selected choice divided by sum of all choices for that QUESTION. the sample UNIT is like (json): -
How to get objects using a ForeignKey field through another ForeignKey in Django?
My models.py is something like this: class Department(models.Model): name = models.CharField(max_length=255) class Category(models.Model): name = models.CharField(max_length=255) department = models.ForeignKey(Department, related_name="categories") class Product(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(Category, related_name="products") As you can see, the product model does not have a direct connection to the department, it only has one through the category model. However, in my department details for < Department X >, I want to get all the products that have a category that has the department < Department X >. Is there any way to do it with one query? I don't want to use a for loop for this. Thanks! -
How to use nginx-rtmp module to create a Django REST API and hls live stream
https://benwilber.github.io/streamboat.tv/nginx/rtmp/streaming/2016/10/22/implementing-stream-keys-with-nginx-rtmp-and-django.html This article helped me with most of my problems but how to use rest API view with this, and return Json response