Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django / Memcached error: The request's session was deleted before the request completed.
Here is the full error: The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. I am using python-memcached with my sessions using my cache. Every few days I get one of these errors. Its thrown by an UpdateError on request.session.save(). It comes from line 60 in sessions/middleware.py. 99% of the time everything works normally. Users report that they are not clicking the logout button. They are also reporting that this happens 5 minutes after logging in, so their sessions are not expiring. I have 0 evictions on my cache for over a month it has been running. If I Google this error, it looks like no one has ever gotten it before. I think the connections to memcached might be closing for some reason. Its running on localhost. The only other time I saw this error is when I set my cache config to a server that had memcached running but it was not listening on that interface. That would generate this exact exception on every request. So is there some way that memcache is refusing to listen for a second or two or dropping connections? Here are … -
Effectively use Multi-table inheritance (one-to-one relationships)
I need several models that inherit from a base class in a one-to-one relationship. In keeping with the Django example: from django.db import models class Place(models.Model): name = models.CharField(max_length=50) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) class Garage(Place): car_brands_serviced = Models.ManyToManyField(Brands) class Boutique(Place): for = Models.ChoiceField(choices=( ("men", "m"), ("women", "w"), ("kids","k")) # etc Now how do I effectively distinguish between the various types of Places when I iterated them in a template (or view function)? Right now, I only see this solution (if I want to iterate over Places, rather than child models individually): for place in Place.objects.all() try: r = place.restaurant # Do restaurant stuff here except ObjectDoesNotExist: try: g = place.garage # Do garage stuff here except ObjectDoesNotExist: try: b = place.boutique # Do boutique stuff here except ObjectDoesNotExist: # Place is not specified Not even sure how that would translate to a template, but this code seems very wrong and inefficient. As an escape, I guess you could make a choicefield in Place to track which child model is related, but that equates to dangerous denormalisation. Am I somehow overthinking this? How do you do this? -
Using ajax to load a Django template containing Angularjs directives
I'm attempting to use Angularjs's $http method to fetch given Django templates depending on the users selection, each of which includes Angular directives (ng-if) to further filter the content. But while the templates are being inserted just fine, and I can see the directives when I check the html, the filtering isn't actually taking place. When I have the templates insert console logs they cannot find $scope variables that are accessible just above and below where the template is inserted. A template I'm inserting looks like this: <div class="data_point_popup"> {% if id in values_dict %} {% if values_dict|get_item:id|get_item:"not_applicable" == True %} n/a # ... {% else %} {% if id in definitions_dict %} {% if definitions_dict|get_item:id|get_item:"data_type" == "Integer" %} {{ values_dict|get_item:id|get_item:"value"|floatformat:0 }} {% elif definitions_dict|get_item:id|get_item:"data_type" == "Currency" %} <div class="currency eur" ng-if="Page.getCurrencySelection() === 'eur'">€{{ values_dict|get_item:id|get_item:"value_json"|get_item:"eur_value"|floatformat:2 }}</div> <div class="currency gbp" ng-if="Page.getCurrencySelection() === 'gbp'">£{{ values_dict|get_item:id|get_item:"value_json"|get_item:"gbp_value"|floatformat:2 }}</div> <div class="currency usd" ng-if="Page.getCurrencySelection() === 'usd'">${{ values_dict|get_item:id|get_item:"value_json"|get_item:"usd_value"|floatformat:2 }}</div> <div class="currency base" ng-if="Page.getCurrencySelection() === 'base'">Base:{{ values_dict|get_item:id|get_item:"value_json"|get_item:"base_value"|floatformat:2 }}</div> <script>console.log(Page.getCurrencySelection())</script> # ... {% else %} <span style="color: red;">ERROR-NO_DEFINITION</span> <script>console.warn("Unable to find definition for data point {{ id }}.");</script> {% endif %} {% endif %} {% else %} - {% endif %} </div> And my controller looks like: function CompaniesDetailTabController($scope, … -
Optimize django-postgreSQL query with annotations
I have the following code to generate a report, it contains 2 counts and one sum: kwargs = {} kwargs['t_suppliers_awarded'] = RawSQL(""" SELECT COUNT("supplier_awarded"."supplier_id") FROM ( SELECT DISTINCT "GCEstadisticas_supplier"."id" as "supplier_id" FROM "GCEstadisticas_requisition" LEFT OUTER JOIN "GCEstadisticas_awarded" ON ("GCEstadisticas_requisition"."id" = "GCEstadisticas_awarded"."requisition_id") LEFT OUTER JOIN "GCEstadisticas_supplier" ON ("GCEstadisticas_awarded"."supplier_id" = "GCEstadisticas_supplier"."id") WHERE ( "GCEstadisticas_requisition"."entity_id" = "GCEstadisticas_entity"."id" AND "GCEstadisticas_requisition"."end_date" >= %s AND "GCEstadisticas_requisition"."end_date" <= %s ) ) "supplier_awarded" """,[start_date, final_date]) kwargs['t_nogs'] = RawSQL(""" SELECT COUNT("GCEstadisticas_requisition"."id") AS "t_nogs" FROM "GCEstadisticas_requisition" WHERE ( "GCEstadisticas_requisition"."entity_id" = "GCEstadisticas_entity"."id" AND "GCEstadisticas_requisition"."end_date" >= %s AND "GCEstadisticas_requisition"."end_date" <= %s ) """,[start_date, final_date]) kwargs['t_ammount'] = RawSQL(""" SELECT SUM("GCEstadisticas_awarded"."ammount") FROM "GCEstadisticas_awarded" WHERE "GCEstadisticas_awarded"."requisition_id" IN ( SELECT "GCEstadisticas_requisition"."id" FROM "GCEstadisticas_requisition" WHERE ( "GCEstadisticas_requisition"."entity_id" = "GCEstadisticas_entity"."id" AND "GCEstadisticas_requisition"."end_date" >= %s AND "GCEstadisticas_requisition"."end_date" <= %s ) ) """,[start_date, final_date]) all_data = Entity.objects.annotate(**kwargs) models used in the query are: class Requisition(models.Model): entity = models.ForeignKey(Entity, on_delete=models.PROTECT) nog = models.CharField(max_length=16, null=False, unique=True) state = models.CharField(max_length=40) modality = models.CharField(max_length=100) competition_type = models.CharField(max_length=70) purchasing_unit = models.CharField(max_length=125) categories = models.ManyToManyField(PurchaseCategory) description = models.TextField() publication_date = models.DateTimeField('fecha de publicación') presentation_date = models.DateTimeField('fecha de presentación de ofertas', null=True) close_date = models.DateTimeField('Fecha de cierre') reception_type = models.CharField(max_length=125) end_date = models.DateTimeField('Fecha de finalización') class Supplier(models.Model): lprv = models.IntegerField('id proveedor en guatecompras', null=True) nit = models.CharField(max_length=20, … -
How can I instantiate a class that is associated with multiple tables and save it in multiple tables?
I am trying to model business processes. I have defined a class to keep the process blue prints (and two classes to keep activities and flows) and then I need to define the same number of tables to keep all of the data associated with the instances of that class. I have a class called ProcessBluePrint. This class is practically defined by two classes called ActivityBluePrint and FlowBluePrint. So far everything works fine. I need to define similar classes to hold data of the instances when created, namely Processes, Activities and Flows. I tried to define the Process class to keep all of the instances of ProcessBluePrint, but I cannot get it right. In the django admin, when i try to add a new process (create an instance of ProcessBluePrint and save it in appropriate tables) Name and Description for the ProcessBluePrint is shown as a text while it should be a drop down. Perhaps the best way to do this is to make this a two step instantiating: step 1=select the ProcessBluePrint option and Step2=Select all the fields associated with that process model. I have attached snapshots to help you get what my problem is. I would really appreciate … -
Django CMS Plugin: How to store combo setting and retrieve on setting window load?
First of all pardon my ignorance as I am kind of new into it. I have been able to show a Dropdown list in Settings Window that fetches data from Db. Now I want to select some value, save and on re-opening of setting modal window I wanna show selected field. So far I figured out that CMS Plugin model actually appears on setting modal window. Below are details models.py class Survey(models.Model): name = models.CharField(max_length=400) description = models.TextField() def __unicode__(self): return (self.name) def questions(self): if self.pk: return Question.objects.filter(survey=self.pk) else: return None class SurveyPluginModel(CMSPlugin): name = models.CharField("Survey Name", max_length=255, default='Survey Name', help_text='Enter Survey Name') description = models.CharField("Survey Description", max_length=500, blank=True, help_text='Write Description here') def __str__(self): return "Returning some Survey Text" forms.py from django import forms from src.survey.models import Survey from src.survey.models import SurveyPluginModel class SurveyForm(forms.ModelForm): all_surveys = Survey.objects.only('name') surveys = forms.ModelChoiceField(queryset=all_surveys) class Meta: model = SurveyPluginModel fields = '__all__' Now if I add a model field in SurveyPluginModel it instantly appears on screen. What I want to save surveys = forms.ModelChoiceField(queryset=all_surveys) selected value to place where other plugin setting is stored and next time it makes it selected. What I guess instance is not going to help, the Plugin model field … -
Django Rest Framework + Postman
Got a new project, and at the moment I'm kinda lost with this. It seems I can't do any POST by Postman, kinda weird. Doing a GET is ok: url: {{base_url}}/api/sign/user/ headers: Cookie: csrftoken=izFfd3Sn5....; sessionid=dp90f6x0... But when I try to do some POST, I always get this error: http://127.0.0.1:8000/api/sign/account { "detail": "CSRF Failed: CSRF token missing or incorrect." } I used exactly same Headers on this call. csrftoken and sessionid I took it from cookie in the WebApp, as I can't do a login by postman Can some one provide some help? Thanks in advice -
creat views.py to administration page
i need to make a page that can save a lot of students information for example when we want to add a new user/student we should enter some required field..actually i can add and save a name,last name,NO, etc...but i cant save a many lessons for one student like this picture. my page what i want is a view for my project . i try a lot Algorithm but i cant save to data base / admin page. my admin.py from django.contrib import admin from .models import Students class StudentsAdminInline(admin.TabularInline): model =Students class StudentsAdmin(admin.ModelAdmin): list_display = ["__str__","o_no","f_name","l_name","University","date","timestamp","update"] inlines = [StudentsAdminInline] admin.site.register(Students) my model.py from django.db import models class Students (models.Model): email=models.EmailField() f_name=models.CharField(default="",max_length=50) l_name = models.CharField(default="",max_length=50,blank=False) o_no=models.CharField(default="",null=False,max_length=50) University=models.CharField(default="",max_length=50) date=models.DateField(editable=True,null=True) timestamp=models.DateTimeField(auto_now_add=True,auto_now=False) update=models.DateTimeField(auto_now_add=False,auto_now=True) def __str__(self): return '{}'.format(self.id) class Student (models.Model): student=models.ForeignKey(Students,related_name='items') Lessons=models.CharField(default="",max_length=50,blank=False) Code=models.DecimalField(max_digits=2, decimal_places=1,null=True) Success=models.CharField(default="",max_length=50,blank=False) def __str__(self): return '{}'.format(self.id) my forms.py class students_form_admin(forms.ModelForm): class Meta: model=Students fields=["__str__","o_no","f_name","l_name","University","date","timestamp","update"] class student_form_admin(forms.ModelForm): class Meta: model=Student fields=["Lessons","Code","Success"] -
Validation in patch method in django rest framework
Following is my model definition class ProfessionalQualification(Log_Active_Owned_Model_Mixin): PROF_TEACHER = 1 PROF_ENGINEER = 2 PROF_DOCTOR = 4 PROF_PROFESSOR = 8 PROF_MANAGER = 16 PROF_CLERK = 32 PROF_SALESMAN = 64 PROF_BUSINESSMAN= 128 PROF_OTHER = 129 VALID_PROFESSIONS = ( (PROF_TEACHER, "Teacher" ), (PROF_ENGINEER, "Engineer" ), (PROF_DOCTOR, "Doctor" ), (PROF_PROFESSOR, "Professor" ), (PROF_MANAGER, "Manager" ), (PROF_CLERK, "Clerk" ), (PROF_SALESMAN, "Salesman" ), (PROF_BUSINESSMAN, "Businessman"), (PROF_OTHER, "Other" ) ) profession_type = IntegerField(choices=VALID_PROFESSIONS, null=False, blank=False) profession_type_name = CharField(max_length=60, null=True, blank=True) institue = CharField(max_length=160, null=False, blank=False) address = ForeignKey(to=City, null=False) year_start = CurrentYearField(null=False, blank=False) in_progress = BooleanField(null=False, blank=False) year_end = CurrentYearField(null=True, blank=True) Following is my serializer class ProfQualSerializer(OwedModelSerializerMixin, ModelSerializer): #address = ConcreteAddressSerializer() class Meta: model = UserProfessionalQual fields = ( "profession_type", "profession_type_name", \ "institue", "address", "year_start", "in_progress", "year_end" ) def validate(self, dict_input): errors = defaultdict(list) profession_type = dict_input["profession_type"] if profession_type == UserProfessionalQual.PROF_OTHER: try: RestAPIAssert(dict_input.get("profession_type_name", None), "Profession-type-name must be passed, for other type of profession", log_msg="Profession-type-name not passed", exception=ValidationError) except ValidationError as e: errors["profession_type"].append(str(e)) year_start = dict_input["year_start"] year_end = dict_input.get("year_end", None) in_progress = dict_input.get("in_progress", None) request = self._context["request"] user_dob = request.user.dob age = request.user.age current_time = datetime.datetime.now() if not user_dob: user_dob = relativedelta(current_time, years=age) if year_start < user_dob.year: errors["year_start"].append("Year-start can't be before user's DOB") elif year_start > year_end: errors["year_start"].append("Year-end … -
Haystack-Elasticsearch Autocomplete not working
I'm trying to configure Autocomplete using Haystack and Elasticsearch. Done all configurations as suggested in Haystack's official document. This is how my model looks like class Model(models.Model): name = models.CharField(max_length=50) make = models.ForeignKey(Make, on_delete=models.CASCADE) url_name = models.CharField(max_length=250, null = True) price = models.IntegerField() is_active = models.BooleanField(default=True) class Meta: db_table = "models" def __str__(self): return self.name search_indexes.py from haystack import indexes from web.models import Model class AutoCompleteIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) url_name = indexes.CharField(model_attr='url_name') # add this for autocomplete. content_auto = indexes.EdgeNgramField(model_attr='name') def get_model(self): return Model def index_queryset(self, using=None): return Model.objects.filter(is_active=1) views.py class AutoCompleteModel(APIView): def get(self, request): sqs = SearchQuerySet().autocomplete(name_auto='caad')[:5] suggestions = [result.name for result in sqs] the_data = json.dumps({ 'results': sqs }) return HttpResponse(the_data, content_type='application/json') **Getting the following exception while querying. ** File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/satish/Workspace/cyclearena/web/views.py", line 30, in make make = Make.objects.get(url_name=make) File "/usr/local/lib/python3.5/dist-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 385, in get self.model._meta.object_name web.models.DoesNotExist: Make matching query does not exist. -
Django - Mongoengine Group By + Where + Sort + Limit and print the results
I make a query to my database and select the collection reviews. I want to filter, to organize, to group, to sort and to limit my results from the query. The query is in views.py. It works fine but i have a problem to print the content of context variable "best_hotels" in the html file. from __future__ import unicode_literals from django.db import models from mongoengine import * class Reviews(Document): # _id = IntField(primary_key=True) content_lenght = IntField() title_score = IntField() content_eval = StringField() review_stars = FloatField() hotel_name = StringField() review_score = IntField() city = StringField() helpful_reader = IntField() title = StringField() content_score = IntField() stars_eval = StringField() content = StringField() title_eval = StringField() review_eval = StringField() Here is the views.py from el_pagination.decorators import page_templates from django.shortcuts import render from django.http import HttpResponse from models import Reviews, Evaluation def reviews(request): best_hotels = Reviews.objects.aggregate( { "$match": {"review_eval": "positiv"} }, { "$group" : {"_id" : "$hotel_name", "sum" : { "$sum" : 1 } } }, { "$sort" : {"sum" : -1} }, { "$limit": 10 } ) context = { 'best_hotels' : best_hotels } return render(request, 'review/reviews.html', context ) Her is the reviews.html ... <h2>The 10 best hotels with the most positiv ratings</h2> <ul> … -
Django SearchVector matching phone numbers
I have a model that stores phone numbers in a format such as (xxx) xxx-xxxx, and I am currently using SearchVector to search first name, last name, email, and phone number, so that any of the above can be used to find a customer in an autofill form field. The problem I have is that no matter what I do, I don't seem to be able to get phone numbers to match quite smoothly. What I would like to do is have it return anything that matches any number of digits in the phone number, as it is typed. If I use queryset = Customer.objects.annotate(search=SearchVector('phone', 'last_name', 'first_name', 'email')).filter(search=self.q) It will match if I put in xxx or (xxx), and will match if I put in (xxx) xxx or (xxx) xxx- or even xxx xxx-, and it will match the full number, as long as there is a hyphen in the second section. It will not match xxx x or xxx xxx-xx etc. I assumed that this was a problem with it not being formatted correctly, so, just for testing, I tried this: if any(x.isdigit() for x in self.q): q = re.sub("[^0-9]", "", self.q) if len(q) > 6: q = '(' … -
Poll application with indefinite options, prevent voting from off the options displayed
I'm working on a django voting system where you get displayed a small random amount of options from a pool of candidates, and the way i submit the votes is by using the ID's of the options, but i can't think of a way to keep people from just changing the source code and submitting votes on the same option over and over, the options get displayed on the view and template like this: return render(request, '/vote.html', {'p': po, 'opts': opts.order_by('?')[:3] {%for v in opts%} <div class='votebox' name='{{v.id}}' onclick='vote()'></div> {%endfor%} What's a code efficient way to check if the user voted on an option that was displayed to them? -
Django 1.10 : view function() takes exactly 2 arguments (1 given)
This is my first django project and I'm struggling to finish it. I've been working to function that editing post. When user clicks button, it send no(int)for that article, and get information related to no and display on page. User can edit that post in the same form and when user click submit, it redirect to home.html However, the function I made keep sending me an error message that it takes 2 arguments even though I did not use any function that takes 2 arguments. Here is views.py @login_required def edit_article(request, article_no): article = Article.objects.filter(pk=article_no) form = ArticleForm(request.POST, instance=request.article) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, _('Article correctly saved.')) # If the save was successful, redirect to another page redirect_url = reverse('blog/home.html') return HttpResponseRedirect(redirect_url) else: form = ArticleForm(instance=request.article) return (request, {'form': form}, context) This is form in detail.html where send no value to edit_article.html <form action="{% url 'blog:edit_article' %}" method="post" style="display: inline;"> {% csrf_token %} <input type="hidden" name="no" value="{{ item.no }}" /> <button type="submit">edit></button> </form> -
Django aggregation optimization - multiple aggregations on a single reverse foreign key query without requerying the database
I am attempting to use aggregations instead of for loops to calculate year end amounts. To reduce code, I created a method on the model to fetch my queryset, then created multiple @cached_properties to run different calculations with that queryset. All of these calculations are called in the same view, and I am using select_related() to grab the models containing hours before calculating. Unfortunately, when I use aggregations, even with select_related(), I get hits on the database for every @cached_property that has aggregate(Sum()). When I use for loops and values() to get the hours hours, it still hits once for every employee (causing 50+ database hit, but thats better than 600 o_O) Looking for a better way to write this code to further reduce the amount of queries,make the code cleaner, and ideally use aggregation to let the database do the work? Maybe I am not fully understanding how Django handles queries or theres a tool I am unaware and could use some pointers Employee and Activity Models: class Employee(Model): name = CharField() class Activity(Model): a, b = range(2) choices = ( (a, 'a'), (b, 'b') ) employee = ForeignKey(Employee) type = IntegerField(choices=choices) hours = DecimalField() added = DateField() Aggregation … -
[django]how to pass a dataframe from view.py to template but it is showing me a string instead
Below is the code i'm using to format my data, however, it seems that i'm unable to pass the whole dataframe to my template. May I know if there is a way to do it properly? Currently, I'm loading from a file so I'm not using any models. view.py host_groups = pd.DataFrame(columns =('host_group', 'hosts')) uni_host_groups = df.host_group.unique() for host_group in uni_host_groups: cur_host_group = df[df['host_group'] == str(host_group)] cur_host = cur_host_group['Host'] cur_host = cur_host.unique() host_groups.loc[len(host_groups)] = [host_group, cur_host] context = { 'host_groups': host_groups, } return render(request, 'search/index.html', context) index.html {% load staticfiles %} <link rel="stylesheet" type="text/css" href= "{% static 'search/style.css' %}"/> <h1>hellloooo</h1> {% for row in host_groups.iterrows %} {{ row }} '\n {{ row.host_group }} {% endfor %} -
How to get the date of the last activity on a Pull Request in Github using PyGithub?
I want to check whether a PR is abandoned or not. I could use the PyGithub but I am not getting the workflow of it. -
Revert a dictonary
In django, I would like to 'revert' a dictionary. For instance, d={'brown':1, 'blue':2} e = d.get('brown') e will give me 1. From e, could I come back to brown with something like e.revert(1)? -
LDAP: 'Populating Django user' causes error 'INSUFFICIENT_ACCESS'
I am attempting to authenticate a Django application against an LDAP server and am receiving some strange behavior. Please keep in mind I don't know much about LDAP so if I misuse some LDAP terminology, excuse me. Also note that throughout this question my_domain is the domain name of my company and user_id is the uid of the authenticating user. Here is the pertinent part of my settings.py configuration file: AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend' ] AUTH_LDAP_SERVER_URI = 'ldaps://ipa.my_domain.com:636' AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,cn=users,cn=accounts,dc=my_domain,dc=com" AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "cn=all,cn=groups,cn=accounts,dc=my_domain,dc=com", "is_staff": "cn=all,cn=groups,cn=accounts,dc=my_domain,dc=com", "is_superuser": "cn=all,cn=groups,cn=accounts,dc=my_domain,dc=com" } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_GROUP_SEARCH = LDAPSearch("cn=groups,cn=accounts,dc=my_domain,dc=com", ldap.SCOPE_SUBTREE, "(objectClass=member)" ) AUTH_LDAP_GLOBAL_OPTIONS = { ldap.OPT_X_TLS_REQUIRE_CERT: False, ldap.OPT_REFERRALS: False, } AUTH_LDAP_USER_ATTR_MAP = {"first_name": "givenName", "last_name": "sn"} When I attempt to log in to my application, I receive this error: Populating Django user user_id search_s('uid=user_id,cn=users,cn=accounts,dc=my_domain,dc=com', 0, '(objectClass=*)') returned 1 objects: uid=user_id,cn=users,cn=accounts,dc=my_domain,dc=com Caught LDAPError while authenticating user_id: INSUFFICIENT_ACCESS({'desc': 'Insufficient access'},) However, when I flip this flag from True to false: AUTH_LDAP_ALWAYS_UPDATE_USER = False Authentication succeeds. Now here is the strange part: even though authentication succeeds, my attributes are not mapped to my Django User object (the ones specified in AUTH_LDAP_USER_ATTR_MAP = {"first_name": "givenName", "last_name": "sn"}). When I manually inspect request.user.ldap_user.attrs all … -
How to exclude delete field from inlineformset but still allow delete
I have an inlineformset that I render in my template so the rows are horizontal. Annoyingly, when I loop through the fields to generate the html, this automatically also renders a delete checkbox. I've seen that this is part of visible_fields https://code.djangoproject.com/ticket/20929#comment:4 How can I get rid of this? I want to be able to hide it for now and then use javascript to show the checkboxes with a button. This way I can enter a 'delete mode'. So I still want the user to be able to delete things, I just want the field to stop rendering in my table on page load. <--form is here, management form etc --> {% for form in existing_formset.forms %} <--field headings generated here--> <tr class="{% cycle row1,row2 %}"> <-- visible fields: apparently includes delete checkbox--> {% for field in form.visible_fields %} <--generate horizontal rows with fields--> <td> {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} <--more stuff--> -
Can I make a django forms ChoiceField scrollable?
I have a ChoiceField drop down menu in Django form. It has times from 9:00 AM up until 5:30 PM - about 18 items. When someone clicks on the drop down, it shows all the values at once. What I'd like it to do is show only about 3 or 4 values with a scroll bar to the right, so that the user can do the scrolling. The reason I want it this way is because it takes less space and looks better. Anyway to get this going? This is what I have so far: MY_CHOICES = ( ('1', '9:00AM'), ('2', '9:30AM'), ('3', '10:00AM'), ('4', '10:30AM'), ('5', '11:00AM'), ('6', '11:30AM'), ('7', '12:00PM'), ('8', '12:30PM'), ('9', '1:00PM'), ('10', '1:30PM'), ('11', '2:00PM'), ('12', '2:30PM'), ('13', '3:00PM'), ('14', '3:30PM'), ('15', '4:00PM'), ('16', '4:30PM'), ('17', '5:00PM'), ('18', '5:30PM'), ) my_choice_field = forms.ChoiceField(choices=MY_CHOICES) -
Django Setup - multiple project with same domain name
i want to develop two project with same look with different data because of that i duplicated my poject as project2. now i have two projects like project1 and project2. i configure like below. if i call www.xyz.com/project2 i am getting project2 result(no problem getting correct result). if i call www.xyz.com/project1 i am getting project2 only not getting project1 result. Help me how to solve this. is there any change require to conf file? apache2.conf Include sites-enabled/ WSGIPythonPath /var/www/project2/blog:/var/www/project1/blog ServerName 107.170.00.04 <Directory "/var/www/"> options Indexes FollowSymLinks AllowOverride None # Require all granted </Directory> /etc/apache2/sites-available/default <VirtualHost *:80> ServerName xyz.com ServerAlias www.xyz.com ServerAdmin xyz@gmail.com Errorlog /var/www/logs/error.log CustomLog /var/www/logs/custom.log combined WSGIScriptAlias /project2 /var/www/project2/blog/blog/wsgi.py <Directory "/var/www/project2/"> Options FollowSymLinks AllowOverride None </Directory> WSGIScriptAlias / /var/www/project1/blog/blog/wsgi.py Alias /static /var/www/project1/blog/static # Set access permission <Directory "/var/www/project1/"> Options FollowSymLinks AllowOverride None </Directory> </VirtualHost> -
Django site cant be reached
Hi i run the server in c9 (django workspace). There were no errors and it said \Starting development server at http://127.0.0.1:8000//.However, when i open this site it says "This site can’t be reached 127.0.0.1 refused to connect." Can anyone help me fix this issue -
pass User obj to view trough custom authentication
class Authenticate(authentication.BaseAuthentication): def authenticate(self, request): token = request.data.get('token') if token: user = User.objects.get(pk=token) return (user, None) else: raise exceptions.AuthenticationFailed() this is my custom authentication in Django Rest Framework, I would like to pass user = User.objects.get(pk=token) this user object to the view, so I may have a similar request.auth which is build in DRF how can I pass this User obj to the view ? and how can i catch it to the view ? -
Sub-Domain Routing Issue on Production Server Django
I'm using Django-Hosts to handle sub-domain routing in my Django app. Django-hosts is working perfectly fine on my development server. But it's not working fine on the production server. when I visit m.example.com it will redirect me to example.com. I have one project with different apps. I only want the sub-domain to make use of mravmomentapp. E.g project name: mrav apps under: mrav/moneapp mrav/mtwoapp mrav/mravmomentapp My stack is nginx, wsgi, gunicorn. I placed the hosts.py in mrav/hosts.py In my hosts.py if socket.gethostname()=="AM-PC": host_patterns = patterns('', host(r'examplelocal.com:8000', mrav_base_settings.ROOT_URLCONF, name='www'), host(r'm.examplelocal.com:8000', 'mravmomentapp.urls', name='m'), ) ###use this settings in production else: host_patterns = patterns('', host(r'example.com', mrav_base_settings.ROOT_URLCONF, name='www'), host(r'm.example.com', 'mravmomentapp.urls', name='m'), ) In my mravmomentapp.urls I have urlpatterns =[ url(r'^$', mo_views.home_page, name='home_page'), #homepage for subdomain m.example.com ] in my nginx.conf server { listen 80; listen [::]:80; server_name example.com www.example.com *.example.com m.example.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name example.com www.example.com; index index.html index.htm index.php; include snippets/ssl-example.com.conf; include snippets/ssl-params.conf; location / { include proxy_params; proxy_pass http://mrav_app_server; } #othersettings } I also created an A host file in my DNS and added my IP ADDRESS to it. What am I missing?