Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extending django admin views
I am trying to extend the admin views and I followed this guide. The given example did end up extending the views and I did end up getting localhost/admin/my_url/ working, however, it did end up removing the urls for all of the other Apps that I have. Is there a simpler way to extend the admin views? I am trying to get a better grasp on how the views work and I wanted to extend the change_form.html with a button redirecting to a simple view, consisting of HttpResponse("Hello, this is get_model_instance_name"). Registering the url as normal in the urls.py should end up working fine, however, I was wondering, whether I can extend the admin urls and end up with something like myapplication/admin/modelname/new_view -
Django ImageField Image Not Displaying
I'm trying to use Django 2.0. I'm using the development 'runserver' right now, so please keep in mind that I'm not in production yet. I am familiar with the differences between the two with regard to static files. I have a Blog Post model. In the admin, I want to be able to add an image to my model using ImageField. I'd like it to be optional, and provide a default image if none is added. I am able to load images in admin. I am unable to render my image in my template. The console shows that Django is trying to GET my image, but my configurations have not worked so far. Here's my model and relevant field: from PIL import Image class Post(models.Model): .... thumbnail = models.ImageField(default='/img/default.png', upload_to='img', blank=True, null=True) .... My model works well aside from the ImageField. My View works well, and I don't think there is any issue there. Here is my urls.py .... from django.conf.urls.static import static from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns from . import views urlpatterns = [ .... path('posts/', views.PostListView.as_view(), name='post_list'), path('post/<int:pk>/', views.PostDetailView.as_view(), name='post_detail'), path('post/random/', views.random_post, name='random_post'), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I'm not at all … -
(Django)form.is_valid() is returning false when using ModelForm
I am creating a form using ModelForm to let the users upload a file along with a description . The is_valid() function isn't returning true and I am really confused. I have searched and there are many questions with same title as mine but they don't solve my problem. here is forms.py: class PostForm(forms.ModelForm): document = forms.FileField(widget=forms.FileInput) class Meta: model = FeedModel fields = ['description', 'document'] Here is models.py: class FeedModel(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField() like = models.IntegerField(default=0) dateTime = models.DateTimeField(auto_now=True, auto_created=True) user = models.ForeignKey(User, on_delete=models.CASCADE, default=0) def get_absolute_url(self): u=self.user return reverse('home:feed',u.primary_key) Here is views.py: class PostView(CreateView): form_class = PostForm template_name = 'home/feedModel_form.html' def get(self, request, *args, **kwargs): form=self.form_class(None) return render(request, self.template_name, {'form':form }) def post(self, request, *args, **kwargs): logger = logging.getLogger(__name__) form=self.form_class(request.POST) if form.is_valid(): user=request.user self.object=form.save(commit=False) self.object.user=user self.object.save() logger.error("voila") redirect({'home:feed'}, user.id) return render(request, self.template_name, {'form':form }) def feedview(request, user_id): user = User.objects.get(pk=user_id) return render(request, 'home/feed.html', {'user': user}) Here is feedModel_form.html: {% extends 'home/navbar.html' %} {% block body %} <div class="form"> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'home/form.html' %} <button type="submit" class="button button-block" ` name="reg_btn">Post</button>` </form> </div> {% endblock %} Here is form.html: {% for field in form %} <div class="field-wrap"> <label> {{ field.label_tag … -
Django - difficulty in image upload using forms
I want to upload an image from django forms and process it using OpenCV. Here is the code I've written with the help of Django documentation: 1.forms.py: class UploadFileForm(forms.Form): image = forms.ImageField() 2.views.py: def upload_file(request): context = {'status':'not working'} if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): context['status'] = 'working' process(request.FILES['test_01.png']) return render(request,'create.html',context) else: form = UploadFileForm() return render(request, 'create.html', {'form': form}) Here process() is the function which processes the uploaded image.Running this code gives me MultiValueDictKey Error on the line where I call process() After searching for the error, referring to this SO answer I changed process(request.FILES['test_01.png']) to process(request.FILES.get('test_01.png')) I get Attribute Error on the same line(which I guess is because I'm not able to retrieve the uploaded image properly) Where am I going wrong and what is the correct way of doing so? -
Wagtail Django group pictures into albums based on their tags
I was wondering if it's possible to arrange pictures uploaded to wagtail into galleries based on their tags. I have an album app, and its models.py contains : from django.db import models from wagtail.wagtailcore.models import Page # Create your models here. class Category(Page): name = models.CharField(max_length=250) slug = models.SlugField() image = models.ImageField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children') def __str__(self): return self.name class Post(Page): title = models.CharField(max_length=120) category = models.ForeignKey('Category', null=True, blank=True) publish = models.DateField(auto_now=False, auto_now_add=False, ) slug = models.SlugField(unique=True) -
Django Add Edit Form - Field has no attribute assigned to it?
Im trying to combine an add and edit form into one and am receiving an error The 'site_image' attribute has no file associated with it. I could edit files but could not add files, but now when I load the site files page I am receiving the below error, I havent changed the model so am unsure as to why im receiving this error. the list of files shouldn't really care if site_image is there or not as its set to blank and null? my file model: class SiteFiles(models.Model): site_data = models.ForeignKey(SiteData, verbose_name="Site", on_delete=models.PROTECT) site_image = models.ImageField(upload_to='site_files/', blank=True, null=True) site_image_thumbnail = ImageSpecField(source='site_image', processors=[ResizeToFill(200, 150)], format='JPEG', options={'quality': 60}) site_file = models.FileField(blank=True, upload_to=site_files_path, \ validators=[validate_file_extension]) file_name = models.CharField(max_length=200, verbose_name="File Name") file_type = models.CharField(max_length=100, verbose_name='File Type', \ choices=settings.FILE_TYPE) class Meta: verbose_name = "Site Files" verbose_name_plural = "Site Files" def __str__(self): return '%s | %s | %s ' % (self.site_data.location, self.site_data.location, self.file_name) my forms.py class FileForm(forms.ModelForm): class Meta: model = SiteFiles fields = ['site_image', 'site_file', 'file_name','file_type'] def __init__(self, *args, **kwargs): super(FileForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'file_form' self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Save', css_class='btn-primary')) self.helper.layout = Layout( Div( Div( Div( Div(HTML('<i class="fa fa-camera-retro fa-fw"></i> Add File or Photo'), css_class='panel-heading'), Div( Field('site_image', placeholder='Image'), Field('site_file', … -
advance order_by() for manytomany field in django python
I have a challenging query ahead: The situation concerns 2 models: models.py: class result(modles.Model): job_id_list = models.ManyToManyField(JobId , related_name='JobId', blank=True) class JobId(models.Model): user = models.ForeignKey(User, blank=True, null=True, default=None) job_time = models.DateTimeField(auto_now_add=True) I do following query: final_results = result.objects.filter(job_id_list__user=request.user).distinct() Basically, a final_results has multiple result-objects, which on their turn have multiple JobId-objects attached. Some of these (one or more) JobId-objects are related to the user. How do I order my final_results on the earliest job_time for jobs that only concern that specific user? In other words, get for every result in final_results the earliest JobId for the user and order then final_results on those times. Is this even possible? -
Serving matplotlib graphs with django without saving
I am using a package called matplotlib to create some graphs, based on user input. Creating these graphs can be done like so plt.plot([1,2,3,4]) plt.ylabel('some numbers') some_plot = plt.figure() Moreover it is possible to then save these graphs as images, some_plot.savefig(path, format='png') The problem is that I don't really want to save every single user generated graph, but rather I would like to just display them. I have tried to look up some solutions for related problems. One such solution was to use IoBytes. Following along these answer I get something like from io import BytesIO some_plot_io = BytesIO() plt.plot([1,2,3,4]) plt.ylabel('some numbers') some_plot = plt.figure() some_plot.savefig(some_plot_io, format='png') Is it possible to somehow pass on the BytesIO object to the template and serve the image or does this method not work? Would there be some other method to do this? -
Django - Add / Edit form no data currently saved, no errors
im trying to do an add/edit form in django and have the following, when I try add a new file, I just get redirected to the same page with no errors, I think its because the hidden field is not being populated with the site_data id (each file is linked to a sites id) and as its hidden I am not getting the error displayed. is my method for adding the site_id incorrect? views.py @login_required @user_passes_test(lambda u: u.has_perm('sites.add_sitefile')) def add_edit_file(request, site_id): from sites.forms import FileForm site_data = get_object_or_404(SiteData, pk=site_id) form = FileForm() if request.method == 'GET': form = FileForm(initial={"id_site_data":site_id}) if request.method == 'POST': form = FileForm(request.POST) if form.is_valid(): form.save() return redirect('sites:site_detail_files', site_id) return render(request, 'sites/add_edit_file.html', { 'add_edit_file_form': form, 'SiteName' : site_data.location, 'SiteID' : site_id, }) forms.py class FileForm(forms.ModelForm): class Meta: model = SiteFiles fields = ['site_data', 'site_image', 'site_file', 'file_name','file_type'] def __init__(self, *args, **kwargs): super(FileForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'file_form' self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Save', css_class='btn-primary')) self.helper.layout = Layout( Div( Div( Div( Div(HTML('<i class="fa fa-camera-retro fa-fw"></i> Add File or Photo'), css_class='panel-heading'), Div( Field('site_data', type="hidden"), Field('site_image', placeholder='Image'), Field('site_file', placeholder='File'), Field('file_name', placeholder='Display Name'), Div('file_type', title="File Type"), css_class='panel-body' ), css_class='panel panel-default', ), css_class='col-lg-3' ), css_class='row' ), ) html rendered: <div class="panel-body"> … -
Button add new element (instance) Django
I need that my template html have a button to add a new element/field, for the class model, it should be a new instance. My html form is created by 2 diferent models and they has a foreign_key, they are the following: models.py class Url_activity (models.Model): url_de_la_actividad = models.URLField() nombre_url = models.CharField(max_length=10, null=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, null=True) lastModification = models.DateTimeField(auto_now_add=False, auto_now=True, null=True) def __unicode__(self): return self.url_de_la_actividad class ActivityProposed (models.Model): nombre_actividad = models.CharField(max_length=50) detalle_de_la_actividad = models.TextField() metodologia = models.CharField(max_length=50) foreign_url = models.ForeignKey(Url_activity, on_delete=models.CASCADE, null=True, blank=True) nombre_de_la_norma = models.CharField(max_length=50) nombre_de_la_competencia = models.CharField(max_length=100) nombre_del_curso = models.CharField(max_length=50) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, null=True) lastModification = models.DateTimeField(auto_now_add=False, auto_now=True, null=True) foreing_activity = models.ForeignKey(Activity, on_delete=models.CASCADE, null=True, blank=True) def __unicode__(self): return self.nombre_actividad so, the main thing is a need to show at the user a "plus" button to add a new URL so many times it is necessary for the user, but I do not know how to do that in django forms, or in the template. forms.py class ActivityProposedForm(forms.ModelForm): class Meta: metodologias_choices = [(metodologia.id, metodologia.methodology_name) for metodologia in Methodology.objects.all()] normas_choices = [(normas.id, normas.norm_name) for normas in Norm.objects.all()] # competencias_choices = # CHOICES = {('1', 'Activa'), ('2', 'Tradicional')} model = ActivityProposed fields = [ 'nombre_actividad', 'detalle_de_la_actividad', 'metodologia', 'nombre_de_la_norma', … -
Trying to print with python but can't manage to find the default printer
Hi i'm working on a python/django project where i need to print a txt file. import win32api import win32print def printFile(): filename = "path/test.txt" win32api.ShellExecute (0,"print",filename, '/d:"%s"' % win32print.GetDefaultPrinter (), ".", 0) I first tried this code directly in a cmd prompt, and it worked. I then made a py file to define the print function as it is above, but when i call it from my view i always get the same error "The default printer was not found" i tried to put the import in the path variable, but i don't see what i did wrong, the import seem to work because i get no error calling the function, only the printer not found error. -
Signal with requests module does not work
I am trying to make a post request using the requests module in order to save data to a remote url. But the signal seems not working, nothing happen when a record is saved and I got no log... Can you tell me what's wrong and how can I get more informations ? models.py @receiver(post_save, sender=Record) def post_record(sender, instance, **kwargs): if kwargs['created']: record = instance payload = { 'name': record.name } r = requests.post('http://.../', data = payload) print(r.status_code) if r.status_code != 200: raise ValueError( 'Request to server returned an error %s, the response is:\n%s' % (r.status_code, r.text) ) -
How to Upload a text file in django using templateview based view and model based forms
I am new to django and stuck on uploading a simple file. I am using TemplateView as views and model based form. I am stuck here. I have no idea what to do. I am using django 2.0. I have attached the code what I have done so far. Please help me to get through this problem ASAP. Thanks in advance. setting.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'key_hash' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Aamir.apps.AamirConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'first.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'first.wsgi.application' DATABASES = { 'default': { 'NAME': 'dbname', 'ENGINE': 'django.db.backends.mysql', 'USER': 'arshad', 'PASSWORD': 'arshad', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", 'charset': 'utf8mb4', } } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' … -
Assign class using python dictionary filters
I want to add class according to index if dictionary key is found in my list area_stats = {'85': (True, False, False, False, False), '11': (False, False, False, False, True)} which the dictionary keys area arrange as top,right,bottom,left,center {% with '18 17 16 15 14 13 12 11 21 22 23 24 25 26 27 28' as list_upper %} {% for x in list_upper.split %} <ellipse name="centerArea_{{ x }}" class="{% if area_stat[center]==true, highlight, no_highlight %}" /> <path name="leftArea_{{ x }}" class="class="{% if area_stat[left]==true, highlight, no_highlight %}""/> <path name="topArea_{{ x }}" class="{% if area_stat[top]==true, highlight, no_highlight %}"/> <path name="bottomArea_{{ x }}" class="{% if area_stat[bottom]==true, highlight, no_highlight %}"/> <path name="rightArea_{{ x }}" class="{% if area_stat[right]==true, highlight, no_highlight %}"/></svg> </td> {% endfor %} </tr> {% endwith %} is this possible in django? What I tried so far is to use dictionary filters but I don't have idea how to display dictionary values according to index. @register.filter(name='is_dict_key') def is_dict_key(key, d): return key in d @register.filter(name='get_dict_value') def get_dict_value(d, key): try: return d[key] except KeyError as e: print(e) return None -
Get JSON data from POST in Django with REST Framework
I am attempting to build a REST API in Django for a Google Spreadsheet with Gspread, I'm running into a lot of issues (so if anyone happens to have a full example lying around, feel free to share... please? :)). One of those issues it that I'm trying to receive JSON for a POST request (and later on other requests, of course). This is, however, failing. This is my code: view.py (I'm aware that that IF-statement is not how it works elif request.method == 'POST': received_json_data = json.loads(request.body.decode("utf-8")) content = received_json_data['content'] if content != "" return JsonResponse(content, safe=False, status=status.HTTP_201_CREATED) else: return JsonResponse([], safe=False, status=status.HTTP_400_BAD_REQUEST) A test that has been written for this: def test_post_all_training_returns_201_when_correct_format(self): """ A POST request on /trainings/ should create a new training """ headers = {'content-type': 'application/json'} response = self.client.post('/trainings/', json=json.dumps(self.training_json_body), headers=headers, format="json") self.assertEqual(response.status_code, status.HTTP_201_CREATED) The contents of the training_json_body: self.training_json_body = { "date": "1/1/2018", "days": 1, "firstname": "Data", "lastname": "Data", "team": "Data", "training": "Data", "company": "Data", "city": "Data", "cost": 1, "invoice": "Data", "info": "Data" } I have searched for a solution for a couple of days now but can't get it to work, so I would be really greatful if someone could push me in the … -
Apache WSGI vs. Django Development Server
I recently decided to deploy my Django project using Apache and mod_WSGI. So, whereas my dev server runs on localhost:8000, my "Apache WSGI" server runs on localhost. Everything looked good until I tried to POST to my Django REST API. For whatever reason, I can post perfectly fine to the Django dev server, but I cannot post to the Apache WSGI server. As a matter of fact, I do not even see that a POST attempt was logged when I look at my Apache logs--I can see url errors there (when I purposefully try to go to a page that doesn't exist for example) but no failed POST attempts. What can be causing this problem and how can I troubleshoot it? Could it be that the Django REST Framework is incompatible with WSGI? I am puzzled why everything else: admin page, logins, navigation, update views, forms, etc, work perfectly fine but this one thing is not even showing up in the logs. -
Django server not responding to Android app
I have a django rest framework api server which is currently being used with a react web application, and a chrome extension using react as well. The next step in the process is a react-native mobile application, but I'm having issues connecting to my api server from the mobile app. I've tried 2 libraries, fetch and axios. My web application and chrome extension are using axios, and they work just fine. When I do a simple get request to my server, I just get a "Network request error" with no other information. Requests to other servers work fine, which makes me think there's some configuration issue I have on my API server that is not allowing the android application to communicate with my API. The requests are just basic GET requests such as axios.get("https://example.com/endpoint/") or fetch("https://example.com/endpoint/"). -
Django cache_page doesn't work on production
I can't figure out why cache_page work's on my local Ubuntu 16.04 with redis and doesn't work on remote DigitalOcean droplet with the same configuration except I use daphne asgi as a server instead of Django built in runserver. Development: Ubuntu 16.04withredis, server: Django's runserver Production: DigitalOcean Ubuntu 16.04 with redis, asgi daphne server cache settings CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "example" } } view @method_decorator(cache_page(5 * 60), name='dispatch') class AjaxGetAllCities(View): """ returns, serialized, all cities currently being visited by at least one user """ def get(self, request, *args, **kwargs): cities = City.objects.currently_being_visited() return JsonResponse(CityMapSerializer(cities, many=True).data, safe=False) For debugging cache, I use Django-debug-toolbar with history where I see that if I call this url on my development server, it does either 2 or 3 cache calls but 0 cache calls on production server. What am I missing? -
Django Crispy forms - positional argument follows keyword argument error
Im new to crispy forms and am trying to use bootstrap to style some form fields into a bootstrap panel, then I will add some other fields into another panel and so on. Building the first panel I am getting the below error. something is awry but am not sure what? Traceback: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/itapp/itapp/sites/views.py" in edit_site 829. from sites.forms import EditSiteForm Exception Type: SyntaxError at /sites/edit/7 Exception Value: positional argument follows keyword argument (forms.py, line 53) this is my forms.py class EditSiteForm(forms.ModelForm): class Meta: model = SiteData fields = ['location', 'site_type', 'bgp_as', 'opening_date','last_hw_refresh_date','is_live', 'tel','address','town','postcode', 'regional_manager','regional_manager_tel','assistant_manager','assistant_manager_tel' ,'duty_manager','duty_manager_tel'] def __init__(self, *args, **kwargs): super(EditSiteForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'edit_site_form' self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Save', css_class='btn-primary')) self.helper.layout = Layout( Div(title='', css_class='panel panel-primary', Div(title='Details', css_class='panel-heading'), Div(css_class='panel-body', Field('location', placeholder='Location'), Div('site_type', title="Site Type") ), ) ) -
How to properly test your models in django
In rails I can easily test my models using rspec. How do you write tests for this example and verify if the choice model has a FK field? from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) -
django-recurrence is displaying a text field in admin instead of the proper field in django 2.0
It works fine in 1.11 but for some reason is not working in 2.0. I'm not sure what the issue is but would appreciate any feedback. I have been stuck with this issue for the past two days unfortunately. Here is the fields.py file from django-recurrence from django.db.models import fields from django.utils.six import string_types import recurrence from recurrence import forms from recurrence.compat import Creator try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], [ "^recurrence\.fields\.RecurrenceField", ]) except ImportError: pass # Do not use SubfieldBase meta class because is removed in Django 1.10 class RecurrenceField(fields.Field): """Field that stores a `recurrence.base.Recurrence` to the database.""" def __init__(self, include_dtstart=True, **kwargs): self.include_dtstart = include_dtstart super(RecurrenceField, self).__init__(**kwargs) def get_internal_type(self): return 'TextField' def to_python(self, value): if value is None or isinstance(value, recurrence.Recurrence): return value value = super(RecurrenceField, self).to_python(value) or u'' return recurrence.deserialize(value, self.include_dtstart) def from_db_value(self, value, *args, **kwargs): return self.to_python(value) def get_prep_value(self, value): if not isinstance(value, string_types): value = recurrence.serialize(value) return value def contribute_to_class(self, cls, *args, **kwargs): super(RecurrenceField, self).contribute_to_class(cls, *args, **kwargs) setattr(cls, self.name, Creator(self)) def value_to_string(self, obj): return self.get_prep_value(self._get_val_from_obj(obj)) def formfield(self, **kwargs): defaults = { 'form_class': forms.RecurrenceField, 'widget': forms.RecurrenceWidget, } defaults.update(kwargs) return super(RecurrenceField, self).formfield(**defaults) -
PyCharm: [08004] The server requested password-based authentication, but no password was provided
Can't figure out why is PyCharm keeping raises this error: I have set everything including Django server configuration. Don't know if it's database problem. Connection works properly. The DB is remote on DigitalOcean droplet. in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'our_db', 'USER': 'django', 'HOST': '<ip>', 'PASSWORD': '<pwd>', 'PORT': 5432, 'ATOMIC_REQUESTS': True, } } I have connection to remote Ubuntu 16.04 where I use ssh key to authenticate. Do you know where is the problem? -
Django filter with Q and Exclude returning incorrect result
I will try and simplify everything to get to my issue. I am using Django==1.11.4 I have 3 models: class Booking(models.Model): provider = models.ForeignKey(Provider, null=True) class Provider(models.Model): title = models.CharField(max_length=100) class BreakHours(models.Model): weekday = models.CharField(max_length=9, choices=WEEKDAY_CHOICES) start_time = models.TimeField() end_time = models.TimeField() provider = models.ForeignKey(Provider) When a user makes a booking, I need to choose a provider such that the booking time chosen wont conflict with the provider's other booking times and break hours. Here is my implementation: Lets assume: total_assessment_time = 30 #in minutes booking_start_time_with_assessment = booking_start_time - timedelta(minutes=total_assessment_time) booking_end_time = booking_start_time + timedelta(minutes=total_assessment_time) st = datetime.strptime(str(booking_start_time.date()), '%Y-%m-%d') booking_weekday = str(calendar.day_name[st.weekday()]) breakhours = BreakHours.objects.filter( Q(provider__store__name=self.cleaned_data['store']) & ( ( Q(weekday=booking_weekday) & Q(start_time__lte=booking_start_time.time()) & Q(end_time__gt=booking_start_time.time()) ) | ( Q(weekday=booking_weekday) & Q(start_time__lt=booking_end_time.time()) & Q(end_time__gt=booking_end_time.time()) ) ) ).values_list('pk', flat=True) provider = Provider.objects.filter( Q(store__name=self.cleaned_data['store']) & Q(services__in=self.cleaned_data['services'])).exclude( ( Q(booking__starts_at__gte=booking_start_time_with_assessment) & Q(booking__starts_at__lte=booking_end_time) ) | ( Q(breakhours__pk__in=breakhours) ) ).distinct() if provider: return provider.first() My issue is that this query works fine, but for some reason the query doesnt return any of the providers even if there are absolutely NO bookings on the day chosen, and he doesnt have any breaks at the time of the booking. Is there any issue with Q or the exclude function in … -
Timezone settings django postgresql linux
I have a django website on linux using Postgre SQL in New Jersey server USA (linode.com) But the users are in a different timezone (Brazil). It is something fool I know, but I do some tests changing settings but nothing positive. Here is some enviroment settings: Linux Server (USA): $cat /etc/timezone Etc/UTC Postgres Console (USA): postgres=# show timezone; UTC Django settings.py (USA): TIME_ZONE = 'America/Sao_Paulo' USE_TZ = True Now the results. Brazil time now: 10:07h Linux Server time(USA): 12:07:52 UTC Here is something wrong! But ok, I don´t use system local time in my website! POSTGRE Console (USA): select now(); 2018-01-16 12:07:36.967415+00 I have a model 'coleta' with a field DATA_LEITURA. data_leitura = models.DateTimeField(null=True) Now I insert a register with 10:07:16h. This is correct time in Brazil! See: br_tz = timezone('America/Sao_Paulo') coleta.data_leitura = datetime(2018, 01, 16, 10, 07, 16, tzinfo=br_tz) In postgre console (USA): SELECT data_leitura FROM coleta; 2018-01-16 15:13:16+00 So incorrect! When the users (Brazil) open the website, they see: 15:13:16 I put this line br_tz = timezone('America/Sao_Paulo') This line solves the NAIVE warning and auto convertion! I am now changing each configuration to see the results... but nothing positive. I think that are two changes to do. My … -
Django ArrayField. How to save nested array of time?
Question is stupid, by i cant find solution. What a valid format for saving nested array of time from simple form text field? I have ArrayField like this: schedule = ArrayField( ArrayField( ArrayField( models.TimeField(null=True), ), size=2, null=True, ), size=7, null=True, blank=True, ) When i am trying to save it from django admin like: ((09:00, 09:00), (09:00, 09:00), (09:00, 09:00), (09:00, 09:00), (09:00, 9:00), (9:00, 9:00), (9:00, 9:00)) I'm getting errors Item 0 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 1 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 2 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 3 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 4 in the array did not validate: Item 0 in the array did not validate: Item 0 …