Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create Django global settings with models?
I'm looking for solution in some trivial Django task. I need to create Global settings in Django admin. Not really sure how to implement model which migrate table in database with global settings and connect this settings with Django admin. I'm using Django 2.0.6 Thank yo very much for any clues and tips. -
Django annotate Max, but with condition
The below queryset almost works perfectly: context['user_artists'] = Artist.objects.filter(users=current_profile)\ .prefetch_related(Prefetch('release_groups', queryset=ReleaseGroup.objects.filter(release_date__lte=startdate) .order_by('-release_date'), to_attr='rgs'))\ .annotate(last_release=Max('release_groups__release_date')).order_by('-last_release').filter(last_release__lte=startdate) What it's supposed to do is to list all artists, with their latest release, and sort by that release (latest to earliest). However, it falls short for a simple reason: When an artist has a FUTURE release, it's technically their latest release, but we don't want to show that release, because it's in the future. That's why the last clause says filter(last_release__lte=startdate). However what this does it completely removes the artist from the queryset, because their last release is in the future. If I remove the last clause, I will get future releases in the queryset, which I don't want. Is there a way to insert a conditional in the Max clause, kind of like Max, but only the Max that is no later than today? I have tried with Case and When but my attempts to implement that failed miserably. It seems to be problematic when the field is a related field and not the own model's field (remember we're originally querying Artist not Release Group) -
i don't wanna use namspace home
Blockquote template {% autoescape off %} Hi {{ user.username }}, Thanks for your registration in blog Please click on the link below to confirm your registration, http://{{ domain }}{% url 'home:activate' uid=uid token=token %} {% endautoescape %} Blockquote urls url(r'^home/', include('home.urls')), Blockquote -
Using mailchimp subscribe form - django
I want to merge the mailchimp subscribe form with my django app. That is once the user clicks on subscribe by entering email and name, he can enter the django app and use it. Currently I am using built in django user model but I want to replace the login with subscribe form. Thanks -
JQuery POST request error 200
I'm trying to send a POST request to my Django server. I'm using JQuery in this way: $("#submit_button").click(function(){ $.ajax({type: 'POST', url: '/API/send_news', data: {name:"randomname"}, success: function (response) { if (response.result === 'OK') { return HttpResponse("Done") } else { return HttpResponse("Fail") } } }); }); The API is defined in my view.py (i wrote get_param): @api_view(['POST']) def send_news(request): try: news_title = get_param(request.POST, "newstitle", NOT_NONE) news_small_description = get_param(request.POST, "newssmalldescription", OPTIONAL) news_description = get_param(request.POST, "newsdescription", OPTIONAL) news_image = get_param(request.POST, "newsimage", OPTIONAL) New.objects.create( news_title = newstitle, news_small_description = newssmalldescription, news_description = newsdescription, news_image = newsimage, ) return HttpResponse() When i press the button i get a 200 error (the request is received but no object created). -
Django ValueError: hour must be in 0..23
I have a time field on my sql database. Below is my model for the time fields and the error that i get. models.py monday_open = models.TimeField(db_column='Monday_Open') monday_close = models.TimeField(db_column='Monday_Close') forms.py class OfficeForm(ModelForm): class Meta: model = Office fields =[ 'name', 'monday_open', 'monday_close' ] settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True The error File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site- packages/mysqlclient-1.3.12-py3.4-macosx-10.6-intel.egg/MySQLdb/cursors.py", line 384, in _fetch_row return self._result.fetch_row(size, self._fetch_type) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site- packages/django/db/backends/utils.py", line 151, in typecast_time return datetime.time(int(hour), int(minutes), int(seconds), int((microseconds + '000000')[:6])) ValueError: hour must be in 0..23 All im trying to do is set the time field in my database for opening hours of an office. -
How to use booleanfield in Django?
I have class Order with pay = models.BooleanField(default=False). I want when someone presses a button pay became True. -
Django View Testing: Can't pull context from client's post
I'm trying to make a testing suite for my view. All of my problems seem to stem from me not being able to access the context of my render that is returned from the view. I know the problem has something to do with DjangoTemplate backend but I have no idea what I am supposed to do to get response.context populated with the necessary variables. This is my tests.py code: class JSONHandlerTester(TestCase): def setUp(self): self.client = Client() self.jsonTestPath = os.path.join(settings.MEDIA_ROOT,'json','jsonTests') pass def testing(self): for test in os.listdir(self.jsonTestPath): testFile = os.path.join(os.path.join(self.jsonTestPath),test) split = test.split('.') testName = split[0] testNameArray = re.findall('[a-zA-z][^A-Z]*', testName) project = testNameArray[0] team = testNameArray[1] with open(testFile) as json: response = self.client.post('/JSONChecker', {'json_project': project, 'json_team': team, 'json': json}) print response print response.context if (response.context['title'] == "Congratulations!!! Your JSON Passes!!!" and testNameArray[2] == "Pass") or (response.context['title'][2:] == "The" and testNameArray[2] == "Fail"): print test+': Works' else: print test+': BREAKS: PROBLEM DETECTED' This is what the render looks like: return render(request, 'JSONChecker.html',context = {'title': title, 'validationErrors':validationErrors,'errors':errors, 'isLoggedIn':isLoggedIn, 'form': form, 'post':post}) I'm using Django 1.11 with python 2.7 -
Celery 4.0 KeyError when running worker
I been looking at many similar problems but no matter what I follow, i couldn't solve it. The error is KeyError: backgroundjobs.tasks.test not found. My structure is like this: app |___app |__conf --base.py,development.py.production.py |_celery.py |_urls.py backgroundjobs |__tasks.py mailer |__simplemail.py My celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'agrigo.conf.development') app = Celery('app') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() backgroundjobs.tasks.py: from __future__ import absolute_import, unicode_literals from celery import shared_task from celery.decorators import task from celery.decorators import periodic_task from celery.task.schedules import crontab from mailer.simplemail import send_message #contains rules to send emails @periodic_task(run_every=(crontab()), name="test", ignore_result=True) def test(): send_message('Subject','Content',['jon.doe@gmail.com']) Celery beat does pick up the task and sends it to the worker. I think my imports are correct and adhering to the recommendation on the documentation. -
Requirements.txt greater than equal to and then less than?
I have this line in my requirements file django>=1.10,<1.11 Does that mean I need to have Django version >= 1.10 and then less than 1.11? -
Nested Inlineformset using Dynamic django formset
This is in relation to two nested inline formsets, child and address. In the new image, you can see a nested form with "add child" and an outer "remove" options using the dynamic django formset found here https://pypi.org/project/django-dynamic-formsets/. When I click the "add child", there should be a second nested form that is similar to the first child with the its own address inline formset. If I click the outer "remove", both the child and assoc. address should be removed. When I click "add address" a second address field should be added for child. Eg. Child 1 Name:________________ - Remove Child Address:______________ - Remove Address + Add Address 2 Name:________________ - Remove Child Address:______________ - Remove Address + Add Address + Add Child -
Django fields in form
I am a beginner in Django, hence this might be a simple issue. But I'm not able to get past this successfully. This is my models.py class Category(models.Model): name = models.CharField(max_length=128) abbr = models.CharField(max_length=5) def __unicode__(self): return self.name class Fabric(models.Model): name = models.CharField(max_length=128) abbr = models.CharField(max_length=5) def __unicode__(self): return self.name class Manufacturer(models.Model): name = models.CharField(max_length=128) location = models.CharField(max_length=128) name_abbr = models.CharField(max_length=5, default=None) loc_abbr = models.CharField(max_length=5, default=None) def __unicode__(self): return self.name class Images(models.Model): design_id = models.CharField(max_length=128) file = models.ImageField(upload_to='images') cost_price = models.FloatField() category = models.ForeignKey(Category, on_delete=models.CASCADE) fabric = models.ForeignKey(Fabric, on_delete=models.CASCADE) manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) selling_price = models.FloatField() aliveness = models.IntegerField() date_added = models.DateTimeField(default=datetime.datetime.now) set_cat = models.IntegerField() set_cat_no = models.IntegerField() set_cat_name = models.CharField(max_length=50, blank=True) I'm building an apparel management database system which contains cloth designs. My forms.py is class ImagesForm(forms.ModelForm): class Meta: model = Images fields = ('file','cost_price','set_cat_no','set_cat_name',) My views.py @login_required def uploadphoto(request): context = RequestContext(request) context_dict = {} if request.method == 'POST': form = ImagesForm(request.POST,request.FILES) if form.is_valid(): image = form.save(commit=False) image.save() return render_to_response(request,'cms/upload-photo.html', {'upload_image': form}) else: print form.errors else: form = ImagesForm() context_dict = {'upload_image': form} return render_to_response('cms/upload-photo.html',context_dict, context) My upload-photo.html is {% block main %} <form id="upload_form" method="post" action="/zoomtail/upload-photo/" enctype="multipart/form-data"> {% csrf_token %} {{ upload_image }} </form> {% endblock %} … -
Modify Autofiled primary key
The django applications needs to be deployed on two different stores so that it works even when internet is not available once the internet is up the data will be sync to the cloud database the problem is the primary key since its an autofield both center may produce same key how to overrule it. I have concatenated the auto file id with strore_name which means the store name is unique and auto filed will be unique by default is this a good practice or do you have any other suggestions -
ImproperlyConfigured while porting code from Django 1.8 to Django 2.0
I am trying to make some project described in a book based on Django 1.8. This part should enroll a student to some course: CBV: class CourseDetailView(DetailView): model = Course template_name = 'courses/manage/course/detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['enroll_form'] = CourseEnrollForm(initial={'course': self.object}) Form: class CourseEnrollForm(forms.Form): course = forms.ModelChoiceField(queryset=Course.objects.all(), widget=forms.HiddenInput) HTML with "Enroll" button: {% if request.user.is_authenticated %} <form action="{% url "students:student_enroll_course" %}" method="post"> {{ enroll_form }} {% csrf_token %} <input type="submit" class="button" value="Enroll now"> </form> {% else %} <a href="{% url "students:student_registration" %}" class="button">Register to enroll</a> {% endif %} HTML after successful enrollment (shortened): {% with subject=course.subject %} <h1>{{ object.title }}</h1> <div class="module"> <h2>Overview</h2> <p> <a href="{% url "elearning:course_list_subject" subject.slug %}">{{ subject.title }}</a>. {{ course.modules.count }} modules. Instructor: {{ course.owner.get_full_name }} </p> </div> {% endwith %} With this I get an error NoReverseMatch - next I comment out <a> tag - the page loads, but with all empty {{ }} template variables. And when I click Enroll button - I get: ImproperlyConfigured at /students/enroll-course/ TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()' It looks like a Course model instance was not passed into the Django template. But why does this happen? A book says that … -
Send notification to a specific user by django channel
X and Y two person. 'X' send a friend request to Y so in 'Y' profile there will be appear a notification of friend request. Then 'Y' accept the Friend request so in 'X' profile also be appeared a notification of accepting friend request. I know real time notification can be handle by django channel and it will be solve by creating group by user . But is it best practice to create group for every particular user ? Is there another way to solve this problem? -
form.save() populates lates row instead of creating a new - Django
I'm trying to create a Klient with a post statement, but instead of creating a new row in the DB it replaces the latest one. Model: class Klient(models.Model): namn = models.CharField(max_length=124) adress = models.CharField(max_length=124) kontakt = models.CharField(max_length=124) class KlientForm(ModelForm): class Meta: model = Klient fields = ['namn', 'adress', 'kontakt'] class Bokning(models.Model): klient = models.ForeignKey('Klient', on_delete=models.CASCADE) referens = models.IntegerField(null=True, blank=True) pumpStr = models.IntegerField(null=True, blank=True) slangStr = models.IntegerField(null=True, blank=True) pump = models.IntegerField(null=True, blank=True) maskinist = models.CharField(max_length=124, blank=True) betongLev = models.CharField(max_length=124, blank=True) betongKvalite = models.CharField(max_length=124, blank=True) bestalld = models.IntegerField(null=True, blank=True) pumpMng = models.IntegerField() datum = models.DateField() littNr = models.IntegerField() arbNr = models.IntegerField(null=True, blank=True) resTid = models.IntegerField() grundavgift = models.IntegerField() pumpStart = models.DateTimeField() pumpSlut = models.DateTimeField() ovrigInfo = models.CharField(max_length=124, blank=True class BokningForm(ModelForm): class Meta: model = Bokning fields = [ 'referens', 'pumpStr', 'slangStr', 'pump', 'maskinist', 'betongLev', 'betongKvalite', 'bestalld', 'pumpMng', 'datum', 'littNr', 'arbNr', 'resTid', 'grundavgift', 'pumpStart', 'pumpSlut', 'ovrigInfo'] View: def bokning(request): if request.method == 'POST': klientForm = KlientForm(json.loads(request.body.decode())) bokningForm = BokningForm(json.loads(request.body.decode())) if klientForm.is_valid() and bokningForm.is_valid(): klient = klientForm.save() bokning = bokningForm.save(commit=False) bokning.klient = klient bokning.save() return HttpResponse(status=201) else: return HttpResponse(status=400) else: return HttpResponseNotAllowed(['POST']) Trying to create several Boking or Klient in a row results in an updated version of the latest one created. It does … -
Django model formset cannot be saved
I have a web page include a job request and inlinformset for the possible candidates with a button to set an interview which works fine. For each candidate, there should be one Interview or more for the same job request. when the user click on interview button he will be transfered to another page for the interviews with URL Para for the job requisition id (jid) and candidate id (cid), as the follwoing class InterviewForm(ModelForm): class Meta: model = Interview exclude = () InterviewFormSet = modelformset_factory(Interview,form=InterviewForm, extra=1) Interview Model class Interview(models.Model): jobRequisition = models.ForeignKey(JobRequisition, on_delete=models.PROTECT) interviewer = models.ManyToManyField(Employee) candidate = models.ForeignKey(Candidate, on_delete=models.PROTECT) interview_date = models.DateField( blank = True) interview_type = models.CharField(max_length=150, choices= interview_type ) view: class InterviewCreate(CreateView): model = Interview form_class = InterviewForm success_url = reverse_lazy('jobRequisitions-list') def get_context_data(self, **kwargs): # bring all interviews related to the selected candidate and job request qu = Interview.objects.filter(jobRequisition=self.kwargs['jid'], candidate=self.kwargs['cid']) context = super(InterviewCreate, self).get_context_data(**kwargs) if self.request.POST: context['candidateinterviews'] = InterviewFormSet(self.request.POST) else: context['candidateinterviews'] = InterviewFormSet(queryset=qu) return context My issues: 1- cannot save: when I click on save button, I get some error to fill in the missing data, so, the validation is working well, but after that, I couldn't save the data in the formset. I have … -
Django with postgresql db, query with ONLY keyword to look only parent table?
I have a table my django model is pointing to, db side i set a series of triggers to route information in child tables (by table inheritance) for a rotation system. Querying the parent table i can still have my full set of information even if dislocated in many tables,but to improve my performance i want to search only in parent table, corresponding with a query where i specify "ONLY" to make db not search in child tables. Is there a way to do it with django models? -
Django single-app project, staticfiles and templates urls
I followed this guide: https://zindilis.com/blog/2017/01/06/django-anatomy-for-single-app.html to setup django as a single-app project. However, I am now very confused when reading documentation on getting templates and statics to work correctly. Here are a few of the points I am confused about: I have two settings-files: one in the root, and one the single app I have. Which one do I edit? I have two url-files: one in the root, and on the single app I have. Wich one serves what? In terms of templates, I did not have to set the DIRS field in either settings.py-file to have templates be served correctly. Even when placed in app/templates Statics is the main issue right now. I have tried to set STATICFILES_DIR in both root's settings.py and the app's settings. Same for adding to urlpatterns in both urls.py-files, according to official documentation. Either way does not serve static-files. -
Failure while converting text column to binary data type
I have a text column in my database which was being used to store pickled python data. This of course became a problem because this pickled data was being decoded as UTF-8 as it was being stored and occasionally caused issues. I would like to alter the type of the column to the binary data type bytea to properly store this data. To test all the currently stored data could be converted I ran the following query: SELECT text_column::bytea as result FROM table; Which ran without issues. However, attempting to ALTER the column's type using the query: ALTER TABLE table ALTER COLUMN text_column TYPE bytea USING text_column::bytea; Results in the error: ERROR: invalid input syntax for type bytea Similarly: ALTER TABLE table ALTER COLUMN text_column TYPE bytea USING CAST(text_column AS bytea); To test this wasn't actually a syntax error I converted to text without any issues: ALTER TABLE table ALTER COLUMN text_column TYPE text USING CAST(text_column AS text); At this point I'm not really sure what the issue is if I can cast without issue when SELECTing the results. The column has no default. My only thought now would be to create a temporary table containing the casted values, dropping … -
near "None":syntax error when running the python program
I am dynamically creating models in sqlite3 database based on excel data.I am reading the excel data using pandas readexcel() method. When i run the program system is showing the error 'near "None":syntax error'. Error message OperationalError at /home/ near "None": syntax error Request Method: GET Request URL: http://localhost:61157/home/ Django Version: 1.11.13 Exception Type: OperationalError Exception Value: near "None": syntax error Exception Location: C:\Users\1297805\Documents\Visual Studio 2013\Projects\DashBoardApplication\DashBoardApplication\DashBoardEnv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 326 Python Executable: C:\Users\1297805\Documents\Visual Studio 2013\Projects\DashBoardApplication\DashBoardApplication\DashBoardEnv\Scripts\python.exe Python Version: 3.6.5 Python Path: ['C:\Users\1297805\Documents\Visual Studio ' '2013\Projects\DashBoardApplication\DashBoardApplication', 'C:\Users\1297805\Documents\Visual Studio ' '2013\Projects\DashBoardApplication\DashBoardApplication\DashBoardEnv\Scripts\python36.zip', 'C:\Users\admin\AppData\Local\Programs\Python\Python36\DLLs', 'C:\Users\admin\AppData\Local\Programs\Python\Python36\lib', 'C:\Users\admin\AppData\Local\Programs\Python\Python36', 'C:\Users\1297805\Documents\Visual Studio ' '2013\Projects\DashBoardApplication\DashBoardApplication\DashBoardEnv', 'C:\Users\1297805\Documents\Visual Studio ' '2013\Projects\DashBoardApplication\DashBoardApplication\DashBoardEnv\lib\site-packages'] Server time: Wed, 13 Jun 2018 09:08:35 -0500 **Reading excel data ** df = pd.read_excel(path_to_csv, encoding='utf-8') col_names = df.columns fields = {} for name in col_names: fields[name] = models.CharField() return create_model('userdata',fields,'startapp') creation of model def create_model(name, fields=None, app_label='', module='', options=None,admin_opts=None): class Meta: # Using type('Meta', ...) gives a dictproxy error during model creation pass if app_label: # app_label must be set using the Meta inner class setattr(Meta, 'app_label', app_label) # Update Meta with any options that were provided if options is not None: for key, value in options.iteritems(): setattr(Meta, key, value) # Set up a dictionary to simulate declarations within a … -
I want to use Django template langue with JavaScript syntax
So, I want to get user input from my form (addDatabase.html) and display output of what they entered and let them download txt file with yaml formatted output (output.html). It was working when I used Django's models.py using request.POST["fieldname"]. What I did was using JS to grab the tag of innerHTML and display out put of it output.html JS code var name = document.getElementById("name"); formContents += name.innerHTML + "\n"; var type = document.getElementById("type"); formContents += " " + type.innerHTML + "\n"; But my problem now is since I decided to use form.py using modelform instead of model.py. I don't know how to retrieve data from my model like i did from my model before. output.html <li id="type">type: {{ form.type}}</li> <li id="vlanid">vlan_id: {{ form.vlan_id}}</li> <li id="rdp">rdp: {{ form.rdp}}</li> <li id="subnet">subnet:</li> View.py (using Model from models.py) def output(request): Form_info.objects.all() print("The button is clicekd") name = request.POST["name"] type = request.POST["type"] vlan_id = request.POST["vlanid"] rdp = request.POST["rdp"] ip_master = request.POST["ipmaster"] ip_backup = request.POST["ipbackup"] vip = request.POST["gateway"] nat_ip = request.POST["natip"] cidr = request.POST["cidr"] dns = request.POST["dns"] dhcp = request.POST["dhcp"] dhcp_pool_start = request.POST["dhcpstart"] dhcp_pool_end = request.POST["dhcpend"] form_info = Form_info(name=name, type=type, vlan_id=vlan_id, rdp=rdp, ip_master=ip_master, ip_backup=ip_backup,vip=vip, nat_ip=nat_ip, cidr=cidr, dns=dns, dhcp=dhcp, dhcp_pool_start=dhcp_pool_start,dhcp_pool_end=dhcp_pool_end) form_info.save() context = { 'form': form_info } … -
What is the default value for TextField in django
You are trying to add a non-nullable field 'note_title' to note without a default; we can't do that (the database needs something to populate existing rows). from django.db import models from django.utils import timezone import datetime # Create your models here. class Note(models.Model): note_title = models.CharField(max_length = 125) note_description = models.TextField(max_length = 500) entry_time = models.DateTimeField('The date and time') def __str__(self): return self.note_title def was_added_recently(self): return self.entry_time >= timezone.now() - datetime.timedelta(days=1) -
Facebook login is not working on website
can someone please help me. I am getting the following error when trying to login with Facebook: URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs. My redirect URI is: http://127.0.0.1:8000/auth/complete/facebook -
Django - Get Model Primary Key after saving on view
I need some help on this view I have. This view is for registering a new Person on database, the Person Model needs Address and a Phone. All three have forms on the view. Phone and Address have foreign key that lead to Person. The problem is that I save the Person, but I can't get it's primary key to save Address and Phone, it returns None no matter what I try. I searched for all kinds of answers but none works for me. This code should work because I tried get the Address and Phone by the same method and it works. view: def cadastrar_cliente(request): success = request.GET.get('success', False) if request.POST: pessoaForm = PessoaForm(request.POST) enderecoForm = EnderecoForm(request.POST) TelefoneFormSet = formset_factory(form=TelefoneForm, max_num=2, extra=2, can_delete=False) TelefoneFormSet = TelefoneFormSet(request.POST) if pessoaForm.is_valid() and enderecoForm.is_valid() and TelefoneFormSet.is_valid(): with transaction.atomic() : pessoaForm = pessoaForm.save(commit=False) pessoaForm.hide = 0 pessoaForm.st_pessoajuridica = 'F' pessoaForm.fkid_tipopessoa = Tipopessoa.objects.get(pkid_tipopessoa=1) if pessoaForm.dt_nascimento in ('', None): pessoaForm.dt_nascimento = datetime.date.today() pessoaForm.save() enderecoForm = enderecoForm.save(commit=False) enderecoForm.hide = 0 enderecoForm.fkid_pessoa = pessoaForm.pk # Can't get the id enderecoForm.save() for form in TelefoneFormSet: form = form.save(commit=False) if form.numero == '' or not form.numero: continue form.hide = 0 form.fkid_pessoa = pessoaForm.pk # Here the same form.ddi = '55' …