Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Queryset filter by time
Hey i have a database model with a datetimefield. Out of this i want to get every entry with time> 2:30 pm our 14:30. Can you help me? db = Event.objects.filter(date__time__gte=datetime.time(14, 30)) the query below dosent give me entrys back... -
Variable Subsitution When Using Django? [duplicate]
This question already has an answer here: Django use a variable within a template tag 2 answers Currently, I use the following code to include another HTML file: {% include "machines/opennebula/resources.html" %} I am adding another folder to add another version of resources.html (specifically to support OpenStack when I want to swap to using that cloud platform): machines/openstack/resources.html I want to have the path change based on whichever is set in a config file (which I incorporate into other parts of the file I'm working on using): {{ cloudPlatform }} I tried: {% include "machines/{{ cloudPlatform }}/resources.html" %} This worked when using it in association with the script tag however it hasn't worked with Django's include statement. My question is how do I make something equivalent (that works in HTML) with Django? -
extended userena signup form fields not shown in template
I'm trying to add fields to the signup form in userena. I followed the documentation but could not figure out why the added fields do not appear in the signup form template. Forms.py: from django.utils.translation import ugettext_lazy as _ from django import forms from userena.forms import SignupForm from models import UsersData class SignupFormExtra(SignupForm): first_name = forms.CharField(label=_(u'first name'), max_length=20) last_name = forms.CharField(label=_(u'last name'), max_length=20) phone_number = forms.IntegerField(label=_(u'phone number')) city = forms.CharField(label=_(u'city'), max_length=20) def save(self): new_user = super(SignupFormExtra, self).save() UsersData.objects.create(user=new_user, first_name=self.cleaned_data['first_name'], last_name= self.cleaned_data['last_name'], phone_number= self.cleaned_data['phone_number'], city= self.cleaned_data['city']) return new_user Models.py: from django.db import models from django.contrib.auth.models import User from userena.models import UserenaBaseProfile class UsersData(models.Model): user = models.OneToOneField(User, unique=True, verbose_name=('user')) first_name = models.CharField(max_length=20, verbose_name=('first name')) last_name = models.CharField(max_length=20, verbose_name=('last name')) phone_number = models.IntegerField(verbose_name=('phone number')) city = models.CharField(max_length=20, verbose_name=('city')) URLs.py: from django.conf.urls import include, url from django.contrib import admin from accounts.forms import SignupFormExtra urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('core.urls')), url(r'^accounts/signup$','userena.views.signup',{'signup_form':SignupFormExtra}), url(r'^accounts/', include('userena.urls')), ] any help please :( -
DRF: Django apps resolving to wrong URL
Djangs apps with same model name causes incorrect url. Django (DjangoRestFramework) project has multiple apps and app A and app B has a model, 'userdata', which has the same name. In urls.py of app A and app B the viewset is registered as: router.register(r'userdata', UserDataViewSet) The databases are different as they belong to different apps. But in the page for localhost:8000/A and localhst:8000/B, it shows localhost:8000/B/userdata. The router is not able to differentiate based on the apps when the model name is the same. I think this is because django does not have the app when it is registering. Can we use a custom 'base_name' as the base_name is usually the model name? e.g. router.register(r'userdata', UserDataViewSet, 'auserdata') in app A and router.register(r'userdata', UserDataViewSet, 'buserdata') in app B. It raises ImproperlyConfigured and NoReverseMatch errors. How can we have models with same name across different apps in a single project or it is not possible? -
django-rest-auth - Facebook social login raises unique constraint violation for existing email
I implemented registration and login with django-allauth and django-rest-auth. I can successfully login with Facebook to the server with both allauth and rest-auth (web and mobile). When I'm trying to login with FB account that its email already exists, it shows the signup form. However, when I'm trying doing the same using rest-auth, I get an error: Internal Server Error: /rest-auth/facebook/ IntegrityError at /rest-auth/facebook/ duplicate key value violates unique constraint "auth_user_username_key" DETAIL: Key (username)=() already exists. My Configuration: ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'optional' SOCIALACCOUNT_AUTO_SIGNUP = True SOCIALACCOUNT_EMAIL_VERIFICATION = False SOCIALACCOUNT_EMAIL_REQUIRED = True SOCIALACCOUNT_QUERY_EMAIL = True -
Gunicorn socket file creation when receiving request from nginx
In my configuration if 'N' number of nginx worker running and 'M' number of gunicorn worker running and gunicorn bind to a socket file( --bind unix:/opt/sockets/gunicorn.run.sock ). When i do ps aux | grep gunico, I'm able to see 'M' processes running, but when I do ss -xn | grep gunicorn ( It basically list all listening unix socket), I see sockets creating and destroyed, no fixed allocated socket. Need help in how gunicorn creates the socket after getting request from nginx. Nginx config : location /endpoint/ { proxy_pass http://unix:/opt/sockets/gunicorn.run.sock; } -
APscheduler operation when Django and gunicorn --preload
I am still working in my home automation based on django and I am now facing the following problem: I use APScheduler (APS) to periodically pool my devices for new data. So, in order to have only one pool per APS trigger, I have configured Gunicorn with the "--preload" flag so that the scheduler is initiated in the Master process of guinicorn. scheduler = BackgroundScheduler() url = 'sqlite:///scheduler.sqlite' scheduler.add_jobstore('sqlalchemy', url=url) This works fine and the initialization of the system works as expected. The problem comes when, after initialization, I try to start the polling from one device that was stopped during init. This is performed by one of the workers of gunicorn by executing the instruction scheduler.add_job(func=callback,trigger='interval',id=id,args=(self, DG, id),seconds=self.Sampletime,replace_existing=True,max_instances=1,coalesce=True,misfire_grace_time=30) This raises an error logged as : ValueError: This Job cannot be serialized since the reference to its callable (<function update_requests.<locals>.<lambda> at 0x71e41bb8>) could not be determined. Consider giving a textual reference (module:function name) instead. The thing is that when the same job is added during initialization, everything works!! So, I wonder if it is possible to add a job from a gunicorn worker to a scheduler created in the main process. Anyone can help??? -
How in the method of POST, save the value of the variable of the Django class
How in the method of POST, save the value of the variable of the Django class. There is a select on the form, when selecting a value, the valuation needs to be saved to a variable and reload the page, already with the saved data. class MovementsListView(TemplateView, CurrentURLMixin): allow_empty = True template_name = "movement_index.html" accounts = None info_account = None case_account = None def get(self, request, *args, **kwargs): self.accounts = Account.objects.all() print(self.case_account) # !!!print always - None, it's necessary - 1 self.info_account = Account.objects.filter(account_code=self.case_account) return super(MovementsListView, self).get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(MovementsListView, self).get_context_data(**kwargs) context["accounts"] = self.accounts context["info_account"] = self.info_account return context #Get case_account def post(self, request, *args, **kwargs): self.case_account = request.POST["case_account"] print(self.case_account) # !!!print example - 1 return redirect("movement_index") -
Python 3.6 - heroku local command cannot find Procfile - Help troubleshooting error message
I am trying to get a working example of my Django app before deployment to Heroku server. If I run python manage.py or heroku open the website runs with no problems. When I attempt to run heroku local web I get the following error: C:\Users\Jup\Drop>heroku local web [OKAY] Loaded ENV .env File as KEY=VALUE Format [WARN] Cannot read property '1' of null [FAIL] No Procfile and no package.json file found in Current Directory - See run_foreman.js --help My Procfile is definitely there, in my root directory where my .env file and my manage.py files are located. I then try heroku local -f Profile which force searches for the Procfile in a location (which defaults to current folder) and I get a similar error: C:\Users\Jup\Drop>heroku local -f Procfile [WARN] Cannot read property '1' of null [FAIL] No Procfile and no package.json file found in Current Directory - See heroku.js --help ! Cannot convert undefined or null to object It still can't find the file, and I have no idea what .json file it's looking for. I search my directory for "null" and there are a bunch of files in my bootstrap that has that name, but it's just a warning and … -
How to fix Permission denied in python?
I am trying to access index.html from apache configuration. my apache config is Listen 8080 ServerName localhost WSGISocketPrefix /var/run/wsgi WSGIDaemonProcess python-path=/opt/codebase/git/.pyenv/versions/3.5.2/envs//lib/python3.5/site-packages user=apache group= display-name=%{GROUP} WSGIProcessGroup WSGIScriptAlias /api /codebase/projects//src/apps/apps/wsgi.py process-group= Timeout 1800 SSLEngine off SSLCertificateFile /etc/pki/tls/certs/apache.crt SSLCertificateKeyFile /etc/pki/tls/private/apache.key DocumentRoot /codebase/projects/<project>/src/client/<project> <Directory /codebase/projects/<project>/src/client/<project>> Require all granted <IfModule expires_module> ExpiresActive On ExpiresDefault "modification plus 2 seconds" # ExpiresDefault "access plus 1 day" ExpiresByType image/gif "access plus 1 month" ExpiresByType image/png "access plus 1 month" </IfModule> Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-eval'; connect-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'; child-src 'self'; form-action 'self'; media-src 'self'; object-src 'self'; report-uri /api/csp/report" </Directory> <Directory /codebase/projects/<project>/src/files> Require all granted </Directory> I am using centos 7 and apache2.4 Ia ma getting 13)Permission denied: [client 3.204.115.205:64720] AH00035: access to /index.html denied (filesystem path '/codebase/projects//src/client//index.html') because search permissions are missing on a component of the path. I gave full permission from parent most dir to file. but getting permission denied problem. can some one help me. I am running all this env in EC2 instance. -
Image Compression before Upload
I'm using django 1.11 & Python 3.6. In my project I'm trying to reduce the image size before uploading it. This is what I tried, import PIL from PIL import Image from django.db import models from django.core.files.uploadedfile import InMemoryUploadedFile from django.utils.six import StringIO class PicturePost(models.Model): # Picture picture = models.ImageField(upload_to='user_images') def save(self, *args, **kwargs): # Do extra stuff before saving # If new post, get the picture and resize it on the fly if self.pk is None: # 1200px width maximum basewidth = 1200 img = Image.open(self.picture) # Keep the exif data exif = None if 'exif' in img.info: exif = img.info['exif'] width_percent = (basewidth/float(img.size[0])) height_size = int((float(img.size[1])*float(width_percent))) img = img.resize((basewidth, height_size), PIL.Image.ANTIALIAS) output = StringIO() # save the resized file to our IO ouput with the correct format and EXIF data ;-) if exif: img.save(output, format='JPEG', exif=exif, quality=90) else: img.save(output, format='JPEG', quality=90) output.seek(0) self.picture = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.picture.name, 'image/jpeg', output.len, None) super(PicturePost, self).save(*args, **kwargs) After doing this I uploaded a 14mb size image but it's still not compressing the picture size. How can we do that? Or please comment if there's some better way to do it? Thank You . . . -
InvalidSignatureError in my line bot which was made by django
I reference network information using dajongo to do echo-line-bot I can receive text I typed However, InvalidSignatureError occurs Then there is such a message 'POST / echobot / callback / HTTP / 1.1' 403 0 ' I google the problem but can not find the problem to solve Anybody can give me a direction to solve it? @csrf_exempt def callback(request): if request.method == 'POST': # pprint.pprint(request.META) signature = request.META['HTTP_X_LINE_SIGNATURE'] body = request.body.decode('utf-8') try: handler.handle(body, signature) except InvalidSignatureError: return HttpResponseForbidden() except LineBotApiError: return HttpResponseBadRequest() return HttpResponse() else: return HttpResponseBadRequest() -
Django Admin: change displayed column name in inline ManyToMany field
I try to translate Django Admin site and I have a problem with ManyToMany TabularInline. My models.py are: class Doctor(models.Model): (...) specializations = models.ManyToManyField(Specialization, blank=True, verbose_name='Specjalizacje') class Meta: verbose_name = 'Lekarz' verbose_name_plural = 'Lekarze' class Specialization(models.Model): name = models.CharField(max_length=191, verbose_name='Nazwa') class Meta: verbose_name = 'Specjalizacja' verbose_name_plural = 'Specjalizacje' And my admin.py looks like: class SpecializationInline(admin.TabularInline): model = Doctor.specializations.through verbose_name = 'Specjalizacja' verbose_name_plural = 'Specjalizacja' @admin.register(Specialization) class SpecializationAdmin(admin.ModelAdmin): list_display = ['name',] @admin.register(Doctor) class DoctorAdmin(admin.ModelAdmin): inlines = [SpecializationInline,] # this field is added as inline exclude = ['specializations',] The resulting Django Admin Page looks like: Everything is translated except of the 'Specialization' column. How can I change its name? -
How to use conditional if statements in Jinja 2?
So I am new to Django and can use some help. I have used a for loop to display a list from my database. But I want to add an if statement such that, if the user input matches my database item, only then it should be displayed. Take a look : {%for inc in all_items%} <ul> {#I want to add an if statement here, if user input == inc_element#} <li><p>{{inc.item_name}}<p></li> </ul> <hr> {%endfor%} I know I 'd have to use HTML forums for taking user input. But how do I match it in if statement. Help would be appreciated. -
Cannot see the bottom part of html page in Django
I visualized pandas dataframe into html template in Django referring to this page. However, the bottom part of table cannot be seen as below image.(cannot scroll down) Does anyone know what is causing this problem and how to fix it? Thank you. -
How run Django server on public ip in Android
Using termux I am able to run Django server on localhost but I am not able to run the server on Public ip (Intranet-ip) -
redefine response in django-rest-social-auth
My question, how me can redefine standard response_code and response in django-rest-social-auth sent on endpoint /login/social/token/ this is link https://github.com/st4lk/django-rest-social-auth on documentation -
How to add few fields in admin to the same model
I have django app (django 1.11) Here is my model: class News(models.Model): title = models.CharField(max_length=500) subtitle = models.CharField(max_length=1000, blank=True) text = models.TextField() link = models.ForeignKey('.'.join(LINK_MODEL), null=True, blank=True) link_title = models.CharField(max_length=500) date = models.DateField(null=True) image = FilerImageField() related_news = models.ForeignKey('news.News', on_delete=models.CASCADE, null=True, blank=True) My admin.py file: from django.contrib import admin from modeltranslation.admin import TranslationAdmin from news import models class NewsInLine(admin.TabularInline): model = models.News extra = 1 class NewsAdmin(TranslationAdmin): list_display = ['title', 'subtitle', 'text', 'link_title'] date_hierarchy = 'date' inlines = [ NewsInLine ] admin.site.register(models.News, NewsAdmin) My problem is that I do not want to connect only a few "related_news" fields to one of the News objects. But my solutions allow you to connect new ones instead of existing objects. -
How can i add an unsubscription link for email using django
I don't know how can I add unsubscription option to receive emails for users in Django? I need to add this option urgently in case any user don't want to receive email from me Models.py: class User(AbstractUser): username_validator = UnicodeUsernameValidator() username = models.CharField( _('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) email = models.EmailField(_('email address'), unique=True) Views.py: @csrf_exempt def email_users_date(request): if not request.method == 'POST': return json_data = json.loads(json.loads(request.body)[0]) date=json_data.get('date') print(json_data) # date = request.POST.get('date') for user in User.objects.all(): subject = 'Data updated' template = get_template('interface/emaildata.html') context = {'user': user, 'date':date} text_msg = strip_tags(msg) send_mail(subject, text_msg, settings.DEFAULT_FROM_EMAIL, [user.email], html_message=msg) return HttpResponse() -
TypeError when running objects.all() on model
This is my model: class Workout(models.Model): datetime = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.CASCADE) lifts = fields.LiftsField(null=True) cardios = fields.CardiosField(null=True) def __str__(self): return str(self.datetime)+" "+self.user.email __repr__ = __str__ And I'm trying to do this from the django shell: (workout) Sahands-MBP:workout sahandzarrinkoub$ shell Python 3.6.2 (default, Jul 17 2017, 16:44:45) [GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from workoutcal.models import Workout >>> Workout.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/query.py", line 226, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __iter__ self._fetch_all() File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/query.py", line 62, in __iter__ for row in compiler.results_iter(results): File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 842, in results_iter row = self.apply_converters(row, converters) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 827, in apply_converters value = converter(value, expression, self.connection, self.query.context) TypeError: from_db_value() takes 4 positional arguments but 5 were given What's the explanation behind this error? I haven't sent any arguments anywhere, so as far as I can tell, the error must lie in my declaration of the model, but I can't see the mistake I made. Thankful for help. -
jquery not working on django
jquery does not work on django project I used with bootstrap. please help me .html <div class="domains-slider marquee"> <ul> <li><a href="#">BTC/USD</a><span class="price"> $2,33 CAD</span></li> </ul> </div> {% load static %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/script.js' %}"></script> </body> </html> script.js jQuery(window).load(function() { jQuery(".marquee").marquee({ duration: 10 * jQuery(".marquee").width(), duplicated: true, pauseOnHover: true }); }); -
Generate date alerts in Django
I need to generate an alert in a birthday software tell me with an alert that a certain person's birthday will arrive How can I do it? the data is with a table in mysql that has the identification number and its date of birth Please, how can I do it? -
Django transactions not working when using MS SQL
I am parsing a file and would like to import the rows line by line inside of a transaction into my MS SQL database so I don't have to load it all into RAM. try: with transaction.atomic(using='mssql'): with open(filepath, 'r', newline='\n') as clean_file: for row in clean_file: measurement = json.loads(row) current_measurement = Measurementdata( mea_datetime=measurement['imp_datetime'], dun=measurement['dun_id'], exp=measurement['exp_id'], ptr=measurement['ptr_id'], mea_value=measurement['imp_value'] ) current_measurement.save() This code works fine using SQLite as the database engine ... 'mssql': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'mssql.sqlite3'), } ... and the log shows that the transaction worked ... (0.000) BEGIN; args=None (0.000) INSERT INTO "MeasurementData" ("MEA_DateTime", "DUN_ID", "EXP_ID", "PTR_ID", "MEA_Value") VALUES ('2000-01-01 07:51:24', 5, 12, 24, 44.22); args=['2000-01-01 07:51:24', 5, 12, 24, 44.22] (0.000) INSERT INTO "MeasurementData" ("MEA_DateTime", "DUN_ID", "EXP_ID", "PTR_ID", "MEA_Value") VALUES ('2000-01-01 07:51:24', 5, 12, 24, 343.22); args=['2000-01-01 07:51:24', 5, 12, 24, 343.22] (0.000) INSERT INTO "MeasurementData" ("MEA_DateTime", "DUN_ID", "EXP_ID", "PTR_ID", "MEA_Value") VALUES ('2000-01-01 07:51:24', 5, 12, 24, 44.22); args=['2000-01-01 07:51:24', 5, 12, 24, 44.22] (0.000) INSERT INTO "MeasurementData" ("MEA_DateTime", "DUN_ID", "EXP_ID", "PTR_ID", "MEA_Value") VALUES ('2000-01-01 07:51:24', 5, 12, 24, 343.22); args=['2000-01-01 07:51:24', 5, 12, 24, 343.22] (0.000) INSERT INTO "MeasurementData" ("MEA_DateTime", "DUN_ID", "EXP_ID", "PTR_ID", "MEA_Value") VALUES ('2000-01-01 07:51:24', 5, 12, 24, 44.22); args=['2000-01-01 07:51:24', 5, 12, … -
How to Make Iterator for do sum of a field from n number of objects
Lets say i have a model class Testmodel(): amount = models.IntegerField(null=True) contact = models.charfiled() Now I am making a query like: obj1 = Testmodel.objects.filter(contact = 123) and suppose its returning n number objects in any case like (obj1,obj2,obj3 ...) So, if I want to make the sum of amount from all the returning object (obj1,obj2,obj3 ...) then how to do by the best way. any help will be appreciated. -
Global queue on server side
Is there any way to create a global queue (A Data Structure) which hold the data and can be called with server-side frameworks such as django?