Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i put a time into a datetime field
I am getting times in the form of eg. 1:00 from a json file and I need to get them into a datetime field. How do I convert this into a datetime? -
Django's TestCase doesn't seem to clean up database between tests
I have written a test to check the integrity of the data I keep in my fixtures. It is a class inheriting from django.tests.TestCase, and it declares the fixtures it needs. When I run the methods in this class only, they pass. However, when I run all of my tests, some fixtures from other tests remain in the db, which makes the tests fail. I tried different variants, and for now I am overriding the _fixture_setup method to kill all db data before my test, but this can't be right. There must be a better way :) class FixturesTest(TestCase): fixtures = ["tariff.json"] def _fixture_setup(self): TariffModel.objects.all().delete() super()._fixture_setup() def test_tariff_fixtures(self): """Check the fixtures for tariffs""" ... Thanks. -
graphen-django mutation relationships
I am attempting to create a mutation with django-graphene that includes a relationship and return the related objects in the response. Django 1.11.5 graphene-django 1.2.1 Amazon Redshift Models import uuid from django.db import models from dwtools.sources.base_models import BaseModel class MasterAccount(BaseModel): master_id = models.CharField( max_length=36, help_text='''The UUID of the record.''', unique=True, default=uuid.uuid4) account_nm = models.CharField( max_length=255, null=True, blank=True, help_text='''The account's name.''') class Meta: managed = False db_table = 'account_dev' app_label = 'mappings' class PlatformAccount(BaseModel): platform_id = models.BigIntegerField(help_text='''Platform account ID''') master = models.ForeignKey(MasterAccount, to_field='master_id') class Meta: managed = False db_table = 'platform_dev' app_label = 'mappings' GraphQL models import graphene from graphene import ObjectType, String class PlatformAccountGraphQL(ObjectType): platform_id = String() class MasterAccountGraphQL(ObjectType): master_id = String() account_nm = String() platform_account = graphene.Field(PlatformAccountGraphQL) Schema class MasterAccountNode(DjangoObjectType): class Meta: model = MasterAccount interfaces = (relay.Node,) class PlatformAccountNode(DjangoObjectType): class Meta: model = PlatformAccount interfaces = (relay.Node,) class CreateAccount(ClientIDMutation): class Input: account_nm = String() ok = Boolean() master_account = Field(MasterAccountNode) platform_account = Field(PlatformAccountNode) @classmethod def mutate_and_get_payload(cls, args, instance, info): ok = True master_account = MasterAccount(account_nm=args.get('account_nm')) master_account.save(force_insert=True) # Testing ID platform_id = 123456 platform_account = PlatformAccount(master=master_account, platform_id=platform_id) platform_account.save() return CreateAccount(master_account=master_account, platform_account=platform_account, ok=ok) class Mutations(AbstractType): """Mutations for the mappings class.""" create_account = CreateAccount.Field() class Query(AbstractType): """The account query class for … -
JSONDecodeError while paginating using Django framework
I'm trying to add pagination to a custom search page and am running into the following error: JSONDecodeError. Below are two methods inside my view that I am using to get the search results. The first is meant to paginate the results, the second for a total dump of the results i.e., no pagination. def super_search(request): query = "chapel hill" BASEURL = "ip_address" query = request.GET.get("q") ip = request.GET.get("ip") params = { "q": query, } r = requests.get(BASEURL,verify=False, params=params) result_set_list = (r.json())['newsResults'] print("Type:"+str(type(result_set_list))) ## The type is <class 'list'> paginator = Paginator(result_set_list, 10) # Showing 10 results page = request.GET.get('page') try: result_set = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. result_set = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. result_set = paginator.page(paginator.num_pages) context = { "results": result_set, "title": "my Results" } return render(request,"resultsPage.html",context) def super_searchNoPagination(request): query = "chapel hill" BASEURL = "ip_address" query = request.GET.get("q") ip = request.GET.get("ip") params = { "q": query, } r = requests.get(BASEURL,verify=False, params=params) context = { "results": (r.json())['newsResults'], "title": "my Results" } return render(request,"resultsPageNoPagination.html",context) I get no error when calling the method super_searchNoPagination; the results get rendered fine. But … -
Migrating Django from 1.9 to 1.11: trouble with MultiValueField and MultiWidget behaviour
Here is a code that works as expected in Django 1.9: class MultipleBooleanField(forms.MultiValueField): def __init__(self, *args, **kwargs): self.fieldnames = kwargs.pop('fields') fields = [ forms.BooleanField(required=False) for x in self.fieldnames ] super(MultipleBooleanField, self).__init__(fields=fields, require_all_fields=False, *args, **kwargs) self.widget = MultipleBooleanWidget(widgets=[ f.widget for f in fields ]) self.widget.fieldnames = self.fieldnames def compress(self, datalist): # return a list of the fieldnames, datalist is a list of booleans print('compress datalist:', datalist) if self.required and not any(datalist): raise forms.ValidationError('You must choose at least one value') return [ self.fieldnames[i] for i in range(len(datalist)) if datalist[i] ] class MultipleBooleanWidget(forms.MultiWidget): def render(self, name, value, attrs=None, renderer=None): if not value: value = [ False for x in self.fieldnames ] rendered_widgets = [ x.render(name, value[i]) for i,x in enumerate(self.widgets) ] items = [ '%s %s' % (rendered_widgets[i], f) for (i,f) in enumerate(self.fieldnames) ] return ' '.join(items) def decompress(self, value): # return a list of boolean, value is a list of fieldnames print('decompress value:', value) if not value: return [ False for x in self.fieldnames ] return [ x in value for x in self.fieldnames ] With Django 1.11, it no more works, the ValidationError is always raised. The datalist is always a list containing only False. The decompress method is never called. … -
Getting the object from a GCBV in the view?
this feels like a terrible stupid question. But a GCBV (DetailView) uses the get_object_function to make a query and to fetch an object and return obj in the function. I want the obj in my actual view to create a gerneric relation and I don't seem capable of doing so. I'm aware that the solution is probably very simple. Be gentle with me ... I tried this out for about 45 min. and it just won't work ... class PostDetail(PostGetMixin, DateDetailView): model = Post date_field = 'pub_date' content_type = ContentType.objects.get_for_model(Post) obj = DateDetailView.get_object() obj_id = obj.id comments = Comment.objects.filter(content_tye=content_type, object_id=obj_id) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update( {"comments": self.comments} ) return context This line: obj = DateDetailView.get_object() does not work since I did not instanciate the class but I can't really instanciate the class in the view since it cant access all the necessary functions there. -
Class Based Views Inheritance Django
I have a base Class defined as follows: class FundDetailView(TemplateView): template_name = "fund_monitor/fund_details.html" model = FundAccount fund_account_id = None transmission = None start_date = None end_date = None def get_context_data(self, **kwargs): context = super(__class__, self).get_context_data(**kwargs) context['fund_account_id'] = kwargs['fund_account_id'] context['transmission'] = kwargs['transmission'] context['start_date'] = kwargs['start_date'] context['end_date'] = kwargs['end_date'] context['sbar'] = "fund_details" context['account_description'] = self.model.objects.get(id=context['fund_account_id']).account_description self.fund_account_id = kwargs['fund_account_id'] self.transmission = kwargs['transmission'] self.start_date = kwargs['start_date'] self.end_date = kwargs['end_date'] return context and I am creating another API class that would like to use the FundDetailView's parameters. I define it like so: class FundDetailApi(APIView, FundDetailView): option = 'default' model_class = NAV def get(self, request, **kwargs): print(self.fund_account_id) return Response("No Api Selected") However, I get the error: context['fund_account_id'] = kwargs['fund_account_id'] django_1 | KeyError: 'fund_account_id' Any ideas on how to resolve this issue? I simply want to access the fund_account_id , transmission, start_date, end_date specified in the parent class. -
How to overwrite Highcharts credits default settings
I've been trying to customize the settings of the credits on a Highchart but without success. I'm working on Django, passing data from Python to my html file in which the Highchart object is rendered, everything works except for the credits settings. See my code below: <div id={{ chartID|safe }} class="chart"> </div> <!-- Maps the Python template context variables from views.py to the Highchart js variables --> <script> var chart_id = "#chart_ID" var chart = {{ chart|safe }} var title = {{ title|safe }} var xAxis = {{ xAxis|safe }} var yAxis = {{ yAxis|safe }} var series = {{ series|safe }} </script> <!-- Highchart js. Variable map shown above --> <script> $(document).ready(function() { $(chart_id).highcharts({ chart: chart, title: title, xAxis: xAxis, yAxis: yAxis, series: series, plotOptions: {series: {borderColor: '#303030',allowPointSelect: true,cursor: 'pointer'}}, credits: {text: 'MyCompanyName',href:'mywebsite.com',color:'#303030',position:{align:'center',verticalAlign:'center'}} }); }); </script> With the above code, everything shows up nicely when I run it, even the plotOptions settings work ... but the credits update doesn't work. Credits still show the default settings, i.e. highcharts.com is shown at the bottom right corner of the graph and it doesn't update with my new settings. What am I missing here? Thanks. -
send email from djangocms-forms
I use djangocms-forms, I configure SEND FORM DATA TO E-MAIL ADDRESS: , SENDER EMAIL ADDRESS:, EMAIL SUBJECT: but the web-hosted does not send to the email address on the configuration. -
django loaddata fails because of concurrent database query
I am trying to migrate the database of one my django projects from sqlite to mysql. I first dumped the whole thing with ./manage.py dumpdata > dump.json and prepared the database with ./manage.py migrate and deleted any created data in the tables (This was necessary, as the dump holds all the data). When I wanted to import the data into the new database with ./manage.py loaddata, there were a lot of errors I was able to resolve, but I can't find the source of this error: Processed 330984 object(s).Traceback (most recent call last): File "/app/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 69, in handle self.loaddata(fixture_labels) File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 109, in loaddata self.load_label(fixture_label) File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 175, in load_label obj.save(using=self.using) File "/usr/local/lib/python3.5/site-packages/django/core/serializers/base.py", line 205, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/usr/local/lib/python3.5/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python3.5/site-packages/django/db/models/base.py", line 904, in _save_table forced_update) File "/usr/local/lib/python3.5/site-packages/django/db/models/base.py", line 954, in _do_update return filtered._update(values) > 0 File "/usr/local/lib/python3.5/site-packages/django/db/models/query.py", line 664, in _update … -
OSError at /user/1/edit [Errno 13] Permission denied: '/home/django/django_project/media/profile_pics/Square.jpg'
My Django site is live, as far as I know, everything works correctly except for when a user tries to upload a profile image they get this error: OSError at /user/1/edit [Errno 13] Permission denied: '/home/django/django_project/media/profile_pics/Square.jpg' I have never seen this before so I'm not really sure what to do... Here is the traceback: Traceback Switch to copy-and-paste view /usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py in inner response = get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _legacy_get_response response = self._get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/base.py in view return self.dispatch(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/contrib/auth/mixins.py in dispatch return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/base.py in dispatch return handler(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/edit.py in post return super(BaseUpdateView, self).post(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/edit.py in post return self.form_valid(form) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/edit.py in form_valid self.object = form.save() ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/forms/models.py in save self.instance.save() ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/db/models/base.py in save force_update=force_update, update_fields=update_fields) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/db/models/base.py in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/db/models/base.py … -
Django settings module...not possible to run the logger?
I use the python logging module in my my_app/views.py file with no problem. I tried to use it inside the staging_settings.py that I use for my configuration. But the messages never reach the error log, whilst the messages from the views.py work fine. my staging_settings.py: LOGGING= { ..redacted for space.. } # the logging config-dict import logging logger = logging.getLogger(__name__) logger.debug(F"this is staging_ setup") Is it just an impossibility to run a logger inside a setup.py? I guess the server actually isn't running yet, so there is nothing for the logger to send to? I'm running this on pythonanywhere, so I don't really have a console to simply print() to or some other hack alternative. -
How can I ran Gunicorn with NGINX (I wan to move from Django development to test my production)?
This is for learning purpose. I have done the web application with Django + Celery/RabbitMQ. I tried to follow this tutorial. I got everything set until "That’s all for gunicorn.". In sense, my Gunicors runs like what it is describe in the tutorial. Now I am confused with the NGINX settings. I have these configurations in /etc/nginx/nginx.conf in its http block. upstream awesome_app { server unix:/home/notalentgeek/Downloads/awesome_app/run/gunicorn.sock fail_timeout=10s; } server { listen 8080; client_max_body_size 4G; access_log /home/notalentgeek/Downloads/awesome_app/logs/nginx-access.log; error_log /home/notalentgeek/Downloads/awesome_app/logs/nginx-error.log warn; location /static/ { autoindex on; alias /home/notalentgeek/Downloads/awesome_app/static/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://awesome_app; break; } } } Everything else there stay untouched. And then what should I do after this? The tutorial does not way anything. How can I see my web application? Moreover how can I set NGINX for Docker ready? Thanks! -
Chaining Django models: how to format results on the template according to the specific model
I have a view that allows me to work with two different models at once, thanks to itertools chain. I'm rendering the instances of the two chained models inside a table in my template, and I'd need the rows of the table to be formatted differently in case the instances are from one model as opposed to the other. So basically: I'm chaining two models and displaying their instances in a table, and all the rows of the table that contain instances from model A should be formatted with a yellow background and all the rows containing instances from model B should have a blue background instead. This is the view: class BaseView(generic.ListView): template_name = 'base/base_list.html' context_object_name = 'base_list' def get_queryset(self): queryset = Document.objects.order_by('due_date') return queryset def get_context_data(self, **kwargs): context = super(BaseView, self).get_context_data(**kwargs) context['object_list'] = sorted( itertools.chain(Program.objects.all(), Document.objects.all()), key=attrgetter('validity_date'), reverse=True) return context In logic, what I'd need in the template would be something like this: if object in object_list ***belongs*** to Program.objects.all() (etc) else (etc) The question is: how should I express that belongs? I've also looked into template tags but could not find the right way to go. Thank you in advance. -
django 2 fields form not working
2 of my fields from my form not working when i try to search with them. I have about 10 fields total and they all work but those 2 don't this is part of my forms.py with the fields that are not working. class AllTablesForm(forms.Form): title = forms.CharField(label='', max_length=250, required=False, widget=forms.TextInput(attrs={'placeholder': 'Title'})) ....... redirectstatus = forms.IntegerField(label='', required=False, widget=forms.TextInput(attrs={'placeholder': 'Redirect Status'})) created_at = forms.DateTimeField(label='', required=False, input_formats=["%Y-%m-%d"], widget=forms.TextInput(attrs={'placeholder': 'Created At'})) redirectstatus and created_at are not working. The format of my dates are like this. 2017-09-27 13:03:49 and the format for the redirect is simple. 200 300 etc. I want to make the created_at like something like the phpmyadmin date search. this is my views.py def search_form_table(request, pk): table_name = Crawledtables.objects.get(id=pk) t = create_model(table_name.name) if request.method == 'GET': form = AllTablesForm(request.GET) if form.is_valid(): cd = form.cleaned_data title = cd['title'] url = cd['url'] description = cd['description'] canonical = cd['canonical'] robots = cd['robots'] schematype = cd['schematype'] redirectstatus = cd['redirectstatus'] created_at = cd['created_at'] query = t.objects.filter(title__icontains=title, url__icontains=url, description__icontains=description, canonical__icontains=canonical, robots__icontains=robots, schematype__icontains=schematype, redirectstatus__exact=redirectstatus, created_at__range=created_at) return render(request, 'search/search_table.html', {'tbl_name': table_name, 'form': form, 'details': query, 'detail': True}) else: form = AllTablesForm() return render(request, 'search/search_table.html', {'form': form}) Thank you in advance -
how to store a dictionary in django model as a field?
I'm trying to build up a social network and want my users to have 3 privacy options [privtae, public, friends_except], private and public are boolean fields and friends_except is a list of users if it's not possible to store a dict in a model as a field then what do I do to implement want I want to. -
How to set nullable field to None using django rest frameworks serializers
I have a simple view with which I want to be able to set a nullable TimeField to None: class Device(models.Model): alarm_push = models.TimeField(null=True, blank=True) class DeviceSettingsSerializer(serializers.ModelSerializer): class Meta: model = Device fields = ('alarm_push',) class DeviceSettingsView(RetrieveUpdateAPIView): serializer_class = DeviceSettingsSerializer lookup_field = 'uuid' def get_queryset(self): return Device.objects.all() But if I try to PATCH data like {'alarm_push': None} I get an error like {"alarm_push":["Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]."]} How can I set alarm_push to None? -
show forms for model who can have multiple instance
I am creating a simple project which is about creating a resume by user. In resume, a user can have multiple experience, educational background and etc. That is why I have created the following table where experience, educational background, skills are foreignkey to the resume table. class Resume(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, blank=False, null=False, help_text="Full Name") slug = models.SlugField(max_length=50, unique=True) designation = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.name class Education(models.Model): resume = models.ForeignKey(Resume, related_name='education') name = models.CharField(max_length=100, blank=False, null=False, help_text="Name of an institution") course = models.CharField(max_length=200, blank=False, null=False, help_text="Name of a course") description = models.CharField(max_length=400, blank=True, null=True) start_date = models.DateField() end_date = models.DateField() class Experience(models.Model): resume = models.ForeignKey(Resume, related_name='experience') designation = models.CharField(max_length=100, blank=True, null=True) company = models.CharField(max_length=100, blank=True, null=True) description=models.CharField(max_length=400, blank=True, null=True) start_date = models.DateField() end_date = models.DateField() class Skill(models.Model): resume=models.ForeignKey(Resume, related_name="skills") name = models.CharField(max_length=100, blank=True, null=True, help_text="Name of the skill") class Meta: verbose_name='Skill' verbose_name_plural='Skills' def __str__(self): return self.name Now for such situation, do I have to create a ResumeForm, EducationForm, ExperienceForm etc and create an Education, Experience and Skill formset or I have to do something else. I do not have clear idea on how to move forward now for … -
django - Ajax Live Search, What Am I Doing Wrong?
I'm trying to have a live search feature where as soon as you type something in a search box, the results automatically appear right below. I've been following this tutorial with no luck. Nothing seems to be happening when I type a query. Could anybody tell me what I'm doing wrong? urls.py urlpatterns = [ url(r'^$', views.list_of_post, name='list_of_post'), [...] url(r'^search/$', views.search_titles), ] # this is my blog app views. Original view contains # url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), views.py # Main view that displays all my posts def list_of_post(request): post = Post.objects.filter(status='published') categories = Category.objects.all() template = 'blog/post/list_of_post.html' context = { 'posts': posts, 'categories': categories, [...] } return render(request, template, context) # View that should return my results? def search_titles(request): if request.method == 'POST': search_text = request.POST['search_text'] else: search_text = '' classes = Post.objects.filter(title__contains=search_text) return render_to_response('blog/ajax_search.html', {'classes': classes}) template <h3>Search</h3> {% csrf_token %} <input type="text" id="search" name="search"/> <ul id="search-results"> </ul> ajax_search.html {% if classes %} {% for class in classes %} <p>{{ class.title }}</p> {% endfor %} {% else %} <p>No classes found.</p> {% endif %} and finally, ajax.js $(function() { $('#search').keyup(function() { $.ajax({ type: "POST", url: "blog/search/", data: { 'search_text' : $('#search').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' … -
Django test Client submitting a form with a POST request
How can I submit a POST request with Django test Client, such that I include form data in it? In particular, I would like to have something like (inspired by How should I write tests for Forms in Django?): from django.tests import TestCase class MyTests(TestCase): def test_forms(self): response = self.client.post("/my/form/", {'something':'something'}) My endpoint /my/form has some internal logic to deal with 'something'. The problem was that when trying to later access request.POST.get('something') I couldn't get anything. I found a solution so I'm sharing below. -
'NoneType' object has no attribute '__getitem__' On Template Render
I know there are questions already answering this but they all seem specific to the project. I have tried to create a MultiValueField, starting with a more complex one and dumbed it down a little to make it easier to understand and implement. So i thought i did it. But now I’m getting 'NoneType' object has no attribute '__getitem__' So first thing is the MultiValueField that has to be a sub class of a MultiWidget class. class LeadTimeWidget(MultiWidget): def __init__(self, attrs=None): widget = [forms.TextInput(), forms.TextInput()] super(LeadTimeWidget, self).__init__(widget, attrs) def decompress(self, value): if value: return value class LeadTimeMultiField(MultiValueField): widget = LeadTimeWidget def __init__(self, *args, **kwargs): list_fields = [forms.fields.CharField(max_length=31), forms.fields.CharField(max_length=31)] super(LeadTimeMultiField, self).__init__(list_fields, *args, **kwargs) def compress(self, data_list): pass After that its conecting the MultiValueField to the form... class AssessmentForm(FrontEndForm): new_price = forms.DecimalField(max_digits=10, decimal_places=2, required=False, widget=MoneyInput) used_price = forms.DecimalField(max_digits=10, decimal_places=2, required=False, widget=MoneyInput) repair_price = forms.DecimalField(max_digits=10, decimal_places=2, required=False, widget=MoneyInput) exchange_price = forms.DecimalField(max_digits=10, decimal_places=2, required=False, widget=MoneyInput) other_label = forms.CharField(required=False) lead_time = LeadTimeMultiField() other_price = forms.DecimalField(max_digits=10, decimal_places=2, required=False, widget=MoneyInput) quote_note = forms.CharField(required=False, widget=widgets.Textarea(attrs={"rows": 3, "cols": 50})) inbound_shipping_cost = forms.DecimalField(max_digits=10, decimal_places=2, required=False, widget=MoneyInput) outbound_shipping_cost = forms.DecimalField(max_digits=10, decimal_places=2, required=False, widget=MoneyInput) You can see that i have done that lead_time = LeadTimeMultiField(), The next bit would be to render … -
Working with Boolean QuerySet
I'm having troubles working with a Boolean QuerySet. models.py: class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', primary_key=True) firstConnexion = models.BooleanField(default=True) views.py firstConnexion = Profile.objects.filter(user=request.user).values('firstConnexion') if firstConnexion: Profile.objects.filter(user_id=user_id.id).update(firstConnexion=False) return redirect('/one/') else: return redirect('/two/') The problem is I am only getting the first condition even though Profile is updated to False How ? -
NoReverseMatch on Django even when kwargs are provided
The Django cant resovle the url, even though the expected kwarg is provided. Here is root urls.py: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^media/(?P<path>.*)$','django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), url(r'^ckeditor/', include('ckeditor_uploader.urls')), url(r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root': settings.STATIC_ROOT}), url(r'^(?P<domain>\w+)', include('frontend.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here is frontend urls.py: from django.conf.urls import include,patterns,url from . import views from .views import MyprofileView from .views import SuccessView from .views import CompanyView from .views import SubscriptionView from django.views.decorators.csrf import csrf_exempt urlpatterns = patterns('', url(r'/success(/?)$', SuccessView.as_view(), name='success'), url(r'/subscribe(/?)$', SubscriptionView.as_view(), name='subscribe'), url(r'^(/?)$', MyprofileView.as_view(), name='home'), url(r'/api/v1/', include('cpprofile.api.urls')), url(r'/product', include('product_information.urls')), url(r'/corporations/(?P<company>\d+)$', CompanyView.as_view(), name='company_page'), url(r'^/(?P<subscription>\w+)/product/pay/return/(?P<amount>\d+)/(?P<currency>\w+)/(?P<id>\d+)?$', views.payment_return, name='subscription_product_payment_return'), ) And here is how I am trying to reverse call it in view.py MyprofileView: context['subscribe_url'] = redirect('subscribe', kwargs={'domain': 'up'}) What could be wrong here? Thanks -
ImportError: No module named xxxx.settings
i moved a project on a different server and now i got this error everytime i build the project : Traceback (most recent call last): File "E:\Applications\var\www\Gestion_Mouvements\Gestion_Mouvement\clean_html.py", line 4, in <module> directory = settings.CLEAN_DIRECTORY; File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 55, in __getattr__ self._setup(name) File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named Gestion_Mouvements.settings In my wsgi.py : import os import sys project_home = u'E:/Applications/var/www/Gestion_Mouvements/Project_Gestion_Mouvement' if project_home not in sys.path: sys.path.append(project_home) os.environ['DJANGO_SETTINGS_MODULE'] = 'Project_Gestion_Mouvement.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Gestion_Mouvements ├── Project_Gestion_Mouvement │ ├── init.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── Gestion_Mouvement │ ├── init.py │ ├── admin.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py └── manage.py I tried most of the solutions already proposed on the multiples post about that error but nothing seem to work so far. i can still perfectly use the app on a webpage and all, but i can't use any script manualy in the project. Any idea on how to fix this ? Thanks in advance. -
Django - model field value multiple checkbox (default value is checked)
I have a Car model and CarOption model class. class Car(models.Model): car_name = models.Charfield(max_length=20) car_options = models.ManyToMany('CarOption') class CarOption(models.Model): option_name = models.CharField(max_length=20) If user select a car, options that user can add to the car should be displayed as multiple checkbox and default options is checked for each car. How should I implement it? please your valuable opinions...