Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Concatenation of a field related to multiple rows of a record in query set in Django
I have to models with one to many relation with which I try to distinguish the type of my records. Let's say First model is dedicated to Book information and second model is some types such as A, B , C and there is an indirect relation from the Type table to Book, so each book could be A, B or C or any possible combination of Types. I want to use concatenation (or any other possible function in annotation to gather all the types in a field). Book.objects.all( ).annotate( Types = F('TableRelation__Type__Name') ).annotate( CombinedTypes = Concat('Types') ) which throws an error since only one argument is passed to be Concatenated. The result I am looking for is a CombinedTypes field filled with "ABAB" for any unique id of Book which shows that that record is an "AB" (or any other combination of A,B and C). How can I achieve this? -
django - post_save signal import different app
I have a post_save signal which is creating an object in a separate model in another app which references a model in the current app and it's giving an import error. Here's the signal from passwordfolders.models import PasswordFolder @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_personal_list(instance=None, created=False): if created: PasswordFolder.objects.create(name='Personal', description='Personal Folder', owner=instance, personal=True, parent='') here is the traceback: File "D:\Projects\enterpass\api\core\models.py", line 10, in <module> from passwordfolders.models import PasswordFolder File "D:\Projects\enterpass\api\passwordfolders\models.py", line 2, in <module> from core.models import AccessLevel, Owner, User The logic flow is it's a post_save on an BaseAbstractUser model in the core app which is calling PasswordFolder in the passwordfolders app which has an FK reference to AccessLevel in the core app. It's failing when trying to reference the import on AccessLevel which is clearly there so I'm not sure why it's failing. -
How to permanently have /xxx sub domain
I have a several applications running in a same cluster and want to set up subdomain for each application. To give you brief description of current set up, I have a Django app, Jira, and Gitlab running in a cluster. It would be nice I can redirect all requests to Django App via: xxxx.com(even localhost)/django-app Jira: xxx.com(+ localhost)/jira Also, I need to make sure any links within Django app should pick up this subdomain from the frontend so when if there is an <a href="category/page"> tag, it should always send users to xxx.com(localhost)/django-app/category/page I have been looking at Nginx reverse proxy but I cannot get subdomains to work like I want above. Please help! -
What is the difference between following in exclude query in django
can any one please help me with difference between this two exclude queries Consider I have Model TableA 1. TableA.objects.exclude(id__in=[1,3,4], is_active=False) 2. TableA.objects.exclude(Q(id__in=[1,3,4]) and Q(is_active=False)) I am asking this because 2nd query give me proper output but in 1st query is_active condition is not working. -
GoDaddy forward naked-domain for heroku app
Browsed around a few different answers here and can't seem to get this to work. There's a very similar question w/ the same problem as me I can't seem to locate again or I'd link. Essentially it is all of the following work on my heroku app (ssl is enabled). http://examle.com http://www.example.com/ https://www.example.com/ But, not https://example.com One of the suggestions in this question was to use wwwizzer to forward the naked domain. I tried this w/ no success using the following setup on GoDaddy and forwarding / A record linked below. My setup on GoDaddy wwwizzer forwarding attempt As an alternative will simply setting the forwarding to https://www.example.com/ work? Those are the only two things I can think of. -
DJango-tables2 how do I refresh/update the table on the webpage without hitting refresh button
I followed the DJango-tables2 official tutorial and was able to create data set in the terminal using: Person.objects.bulk_create([Person(name='Jieter'), Person(name='Bradley')]) However, the new data in the table on the website doesn't show up until I hit the refresh button. My question is how the table can be updated/refreshed without any human interaction on the webpage. What I'm trying to achieve is to update the table on the webpage without human interaction as soon as new data comes in. I'm relatively new to this, any suggestions would be greatly appreciated. Thank you. -
RuntimeError main thread is not in main loop Why sometimes does this error happen?
I got an error,RuntimeError at /accounts/draw_img main thread is not in main loop .I wrote codes, def draw_img(request): return render(request, 'draw_img.html', {'chart': _view_plot(request)}) def _view_plot(request): results = ImageAndUser.objects.filter(user=request.user).order_by('date') if len(results) == 0: plt.fill_between(x=[0,6], y1=0, y2=6, facecolor='yellow', alpha=0.2) jpg_image_buffer = io.BytesIO() plt.savefig(jpg_image_buffer) array = base64.b64encode(jpg_image_buffer.getvalue()) jpg_image_buffer.close() return array dates = [r.date for r in reversed(results)] xlist = [r.x for r in reversed(results)] ylist = [r.y for r in reversed(results)] if len(dates) > 5: dates = dates[-5:] xlist = xlist[-5:] ylist = ylist[-5:] image_data = [] for i in range(len(dates)): if dates[i] != None: image_data.append(dates[i]) image_data.append(xlist[i]) image_data.append(ylist[i]) plot_dates = [] plot_xlist = [] plot_ylist = [] for j in range(0, len(image_data), 3): plot_dates.append(image_data[j]) plot_xlist.append(image_data[j + 1]) plot_ylist.append(image_data[j + 2]) font = {'family': 'IPAexGothic'} matplotlib.rc('font', **font) for i in range(len(plot_xlist)): if i == 0: plt.plot(plot_xlist[i], plot_ylist[i], color="red", marker="x", linewidth=0, label=plot_dates[i]) elif i == 1: plt.plot(plot_xlist[i], plot_xlist[i], color="blue", marker="x", linewidth=0, label=plot_dates[i]) elif i == 2: plt.plot(plot_xlist[i], plot_xlist[i], color="green", marker="x", linewidth=0, label=plot_dates[i]) elif i == 3: plt.plot(plot_xlist[i], plot_xlist[i], color="yellow", marker="x", linewidth=0, label=plot_dates[i]) else: plt.plot(plot_xlist[i], plot_xlist[i], color="gray", marker="x", linewidth=0, label=plot_dates[i]) plt.legend() plt.xlim(0,100) plt.ylim(0, 100) plt.fill_between(x=[0, 95], y1=0, y2=80, facecolor='#CCFFFF') plt.fill_between(x=[0, 90], y1=0, y2=80, facecolor='#99FFFF') plt.fill_between(x=[0, 85], y1=0, y2=75, facecolor='#66FFFF') plt.fill_between(x=[0, 80], y1=0, y2=70, facecolor='#33FFFF') plt.fill_between(x=[0, 75], … -
Build an html table with session data in Django
I'm using sessions to persist data that hasn't been saved to the database for a multi-screen registration form. On the second screen in the form the user can add multiple rows of data (each row is an object that would be saved in the database) which are each saved to a django session variable using ajaj. The structure looks like this: request.session['data'] = [{'category': 'light jet', 'seats': 1, 'user': None, 'serial_number': '123abc', 'crew': 'one_crew', 'manuf_year': 2019, 'make_model': 'Pilatus/PC-12', 'tail_number': '456def', 'base_airport': 'Bozeman', 'ownership': 0.25, 'prof_pilot': False, 'op_cert': 'cert_part_91'}, {'category': 'light jet', 'seats': 1, 'user': None, 'serial_number': '123abc', 'crew': 'one_crew', 'manuf_year': 2019, 'make_model': 'Pilatus/PC-12', 'tail_number': '456def', 'base_airport': 'Bozeman', 'ownership': 0.5, 'prof_pilot': False, 'op_cert': 'cert_part_91'}] If the user fills out multiple rows and then chooses to navigate back to the first screen (to edit it or whatever) and then forward to the screen with the table using form buttons, I'm planning to rely on the session variable to repopulate the table. The Django endpoint looks like this: def applyAircraft(request): initial = {'aircraft': request.session.get('aircraft', None)} form = AircraftForm(request.POST or None, initial = initial) #del request.session['aircraft'] if request.method == 'POST': if form.is_valid(): if not 'aircraft' in request.session: request.session['aircraft'] = [] aircraft = request.session['aircraft'] aircraft.append(form.cleaned_data) … -
Django and django rest framework storing binary image and convert to image
I am using django to create API only and i am working together with my partner to integrate with his IOS phone. He told me that the image he sent will be in byte/binary format. And then i have to convert that binary data into image ? Also, the bigger the size of the image, the larger it is ? As i am not sure if i am storing in byte or byte array. This is the first time i heard of using about being able to store binary/byte and convert it to image. As i only know about using ImageField to store image. There are also very limited post regarding on storing image in byte and the conversion. Even the django documentation on BinaryField is very limited There is also a third party package which help the conversion but i have no idea on how to use it as there isnt much documentation on how to use it on the API. source: https://github.com/JeffreyATW/binaryimage I know this may be asking a lot but please help me Here is my code currently: models.py class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=9, blank=True, null=True) birthday = models.DateField(blank=True, … -
djangorestframework JWT prefixing custom header "AUTHORIZATION" with "HTTP_AUTHORIZATION" automatically
I need help with this. I'm using django rest framework api_view() with JWT Token Authentication. When I try to send "Authorization" header from my android app, it automatically gets converted to "HTTP_AUTHORIZATION". I also tried it with a variety of other custom headers, but still got the same results. This is the result I get when I print request.META {'HTTP_AUTHORIZATION': 'JWT daf2f1f0aef9a3db70d5c3443445a92fce830f0e', 'RUN_MAIN': 'true', 'XDG_GREETER_DATA_DIR': '/var/lib/lightdm-data/ashish', 'QT4_IM_MODULE': '', 'SERVER_SOFTWARE': 'WSGIServer/0.1 Python/2.7.12', 'UPSTART_EVENTS': 'started xsession', 'SCRIPT_NAME': u'', 'XDG_SESSION_TYPE': 'x11', 'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': '218', 'SERVER_PROTOCOL': 'HTTP/1.1', 'HOME': '/home/ashish', 'DISPLAY': ':0.0', 'LANG': 'en_IN', 'VIRTUAL_ENV': '/home/ashish/Lore/venv', 'SHELL': '/bin/bash', 'PATH_INFO': u'/api/users/details/bio/update/', 'XDG_DATA_DIRS': '/usr/share/xubuntu:/usr/share/xfce4:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop:/usr/share', 'QT_LINUX_ACCESSIBILITY_ALWAYS_ON': '1', 'MANDATORY_PATH': '/usr/share/gconf/xubuntu.mandatory.path', 'CLUTTER_IM_MODULE': '', 'UPSTART_INSTANCE': '', 'JOB': 'dbus', 'SESSION': 'xubuntu', 'SERVER_PORT': '8000', 'XMODIFIERS': '', 'JAVA_HOME': '/usr/lib/jvm/java-8-oracle', 'GTK2_MODULES': 'overlay-scrollbar', 'XDG_RUNTIME_DIR': '/run/user/1000', 'HTTP_HEADERLINE4': 'headerLine4Val', 'CONTENT_TYPE': 'application/json; charset=UTF-8', 'J2SDKDIR': '/usr/lib/jvm/java-8-oracle', 'HTTP_CONNECTION': 'Keep-Alive', 'HTTP_HOST': '192.168.1.106:8000', 'wsgi.version': (1, 0), 'XDG_CURRENT_DESKTOP': 'XFCE', 'XDG_SESSION_ID': 'c2', 'DBUS_SESSION_BUS_ADDRESS': 'unix:abstract=/tmp/dbus-do9HpUjbpz', 'GTK_MODULES': 'gail:atk-bridge', 'DESKTOP_SESSION': 'xubuntu', 'LESSCLOSE': '/usr/bin/lesspipe %s %s', 'GNOME_KEYRING_PID': '', 'wsgi.run_once': False, 'wsgi.errors': <open file '<stderr>', mode 'w' at 0x7fce73cf81e0>, 'wsgi.multiprocess': False, 'INSTANCE': '', 'XDG_MENU_PREFIX': 'xfce-', 'LS_COLORS': 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:', 'XDG_SEAT': 'seat0', 'GLADE_PIXMAP_PATH': ':', 'LESSOPEN': '| /usr/bin/lesspipe %s', 'QUERY_STRING': '', 'QT_IM_MODULE': '', 'LOGNAME': 'ashish', 'USER': 'ashish', 'GNOME_KEYRING_CONTROL': '', 'XDG_VTNR': '7', 'PATH': '/home/ashish/Lore/venv/bin:/home/ashish/bin:/home/ashish/TMI/venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin', 'PS1': '(venv) \\[\\e]0;\\u@\\h: \\w\\a\\]${debian_chroot:+($debian_chroot)}\\u@\\h:\\w\\$ ', 'SSH_AGENT_PID': '1538', 'TERM': 'xterm', 'HTTP_USER_AGENT': … -
Django bulk create objects from QuerySet
If I have a QuerySet created from the following command: data = ModelA.objects.values('date').annotate(total=Sum('amount'), average=Avg('amount')) # <QuerySet [{'date': datetime.datetime(2016, 7, 15, 0, 0, tzinfo=<UTC>), 'total': 19982.0, 'average': 333.03333333333336}, {'date': datetime.datetime(2016, 7, 15, 0, 30, tzinfo=<UTC>), 'total': 18389.0, 'average': 306.48333333333335}]> Is it possible to use data to create ModelBobjects from each hash inside the QuerySet? I realize I could iterate and unpack the QuerySet and do it like so: for q in data: ModelB.objects.create(date=q['date'], total=q['total'], average=q['average']) But is there a more elegant way? It seems redundant to iterate and create when they're almost in the bulk_create format. -
Staticfiles don't load in admin on production server
As the title says, my staticfiles wont load in admin on my production server (though works fine locally). I'm using s3boto3 for staticfiles_storage. However, i've recently changed aws buckets/accounts. in my admin templates, {% url static 'static/file.js' %} still points to the old bucket/account. (e.g. https://myoldbucket.s3.amazonaws.com/admin/css/base.css?Signature=sdmlfnsdkfl%3D&Expires=1514514737&AWSAccessKeyId=AKdsfjsodifnsdiofs ) I've run collectstatic and i still have no current staticfiles. does anyone know what could be wrong? Here is my related code in settings.py: STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' AWS_ACCESS_KEY_ID = key AWS_SECRET_ACCESS_KEY = key AWS_STORAGE_BUCKET_NAME = 'mynewbucket' AWS_HEADERS = { 'Expires': 'Thu, 15 Apr 2010 20:00:00 GMT', 'Cache-Control': 'max-age=86400', } STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'staticfiles/'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static')` -
Django modal content
I have weard problem with bootstrap 4 modals and django. I need to display the modal to edit the address and return to the previous page after editing. For this purpose, i pass 2 parameters in the URL address. when both parameters are given instead of modal to edit the address, the entire page is loaded this is my view class AddresssUpdateView(generic.UpdateView): model = Address template_name = 'Order_app/address_form.html' form_class = AddressForm def get_success_url(self): return reverse_lazy('Order_app:detail', kwargs={'pk': self.object.pk}) this is my modal content (address_form.html) <div class="modal-dialog modal-lg"> <div class="modal-content"> {% if adres %} <form role="form" action="{% url 'Order_app:edit_address' pk address_id %}" method="POST"> <div class="modal-header"> <h3>Edit</h3> </div> {% endif %} <div class="modal-body"> {% csrf_token %} <div class="panel panel-default"> <div class="panel-body"> {{ form.as_p }} </div> </div> </div> <div class="modal-footer"> <div class="col-lg-12 text-right"> <input type="submit" class="btn btn-primary" name="submit" value="Save"> <button type="button" class="btn btn-default" onclick="return hide_modal()"> exit </button> </div> </div> </form> </div> this is my urls.py file url(r'^$', views.ZleceniaListView.as_view(), name='lista_zlecen'), url(r'^(?P<pk>[0-9]+)', views.OrderDetailView.as_view(), name='detail'), url(r'^(?P<pk>[0-9]+)/edit/(?P<adres_id>[0-9]+)/$', views.AddressUpdateView.as_view(), name='edit_address'), my home page template fragment <button type="button" class="btn btn-warning btn-sm" onclick="return abrir_modal('{% url 'Order_app:edit_address' order.pk address.pk %}')" data-toggle="modal" data-target="#Modal"> edit <div class="modal" id="Modal" tabindex="-1" role="dialog"></div> <script> function abrir_modal(url) { $('#Modal').load(url, function () { $(this).modal('show'); }); return false; } function … -
Getting an error 'BadRequestException' object has no attribute 'get'
I am a newbie in python and django. Trying to setup django to work with Dropbox but keep getting error "'BadRequestException' object has no attribute 'get'". Here is my code. def get_dropbox_auth_flow(web_app_session): APP_KEY= '****' APP_SECRET = '****' redirect_uri = "http://localhost:8000/dropbox" return DropboxOAuth2Flow(APP_KEY, APP_SECRET, redirect_uri, web_app_session, "dropbox-auth-csrf-token") # URL handler for /dropbox-auth-start def dropbox_auth_start(request): authorize_url = get_dropbox_auth_flow(request.session).start() return HttpResponseRedirect(authorize_url) # URL handler for /dropbox-auth-finish def dropbox_auth_finish(request): try: access_token, user_id, url_state = get_dropbox_auth_flow(request.session).finish(request.GET) # oauth_result = get_dropbox_auth_flow(request.session).finish(request.query_params) except oauth.BadRequestException as e: return e except oauth.BadStateException as e: # Start the auth flow again. return HttpResponseRedirect("http://localhost:8000/dropbox_auth_start") except oauth.CsrfException as e: return HttpResponseForbidden() except oauth.NotApprovedException as e: raise e except oauth.ProviderException as e: raise e I am following the documentation here -
Django Rest Framework Token User with MongoEngine User
i try to get token using Django Rest Framework but doesn't accept my user ValueError: Cannot assign "<User: gaurav>": "Token.user" must be a "User" instance. models class User(Document): first_name = StringField(max_length=20, required=True) last_name = StringField(max_length=20, required=True) email = StringField(max_length=20, required=True) password = StringField(max_length=200, required=True) def set_password(self,password): self.password = make_password(password) class Meta: db_table = 'User' view token = Token.objects.create(user=user) Please let me know how I can get this to work. -
Django 2.0 CreateView not working
I am very new to Django - been at it for five weeks. Not sure whether this is a bug or my own stupidity. Here is my model in an app called gcbv (for generic class-based view) from django.db import models from core.models import TimeStampModel from django.urls import reverse # Create your models here. class Vehicle(TimeStampModel): maker = models.CharField(max_length=100) model_year = models.IntegerField() vehicle_type = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) vehicle_model = models.CharField(max_length=100) website = models.URLField(max_length=100, blank=True) email = models.EmailField(max_length=100, blank=True) notes = models.TextField(blank=True, default='') def __str__(self): x = self.maker + ' ' + self.vehicle_model return x And here are the URLs from django.contrib import admin from django.urls import path, include from django.conf.urls import url from . import views from django.urls import reverse #from django.views.generic.base import TemplateView app_name = 'gcbv' urlpatterns = [ path('sub1/', views.SubView.as_view(), name='sub1'), path('vehicle_list/', views.VehicleListView.as_view(), name = 'vehicle_list'), path('vehicle/<str:slug>/', views.VehicleDetailView.as_view(), name='vehicle_detail'), path('vehicle/create', views.VehicleCreateView.as_view(), name='vehicle_create'), path('', views.IndexTemplateView.as_view(), name='index'), ] And here is the relevant view class VehicleCreateView(CreateView): model = Vehicle fields = ['maker', 'model_year', 'vehicle_type', 'slug', 'vehicle_model', 'website', 'email', 'notes'] labels = {'maker':'Maker', 'model_year':'Year', 'vehicle_type':'Type', 'vehicle_model':'Model', 'website':'Website', 'email':'Email', 'notes':'Notes'} Here is the template: {% extends "core/base.html" %} {% block body_block %} <h1>Vehicle Create for GCBV</h1> <form action="POST" action=""> {% … -
How to style a Django radio select form?
I would like to style the input button. My form already has an id on its attrs to target it on CSS. Does anyone know how I can do that? -
Django intersection of non commited model objects and commited model objects
What I have is a list of model objects I haven't run bulk_create on: objs = [Model(id=1, field=foo), Model(id=2, field=bar)] What I'd like to do is intersect objs with Model.objects.all() and return only those objects which aren't already in the database (based on the field value). For example, if my database was: [Model(id=3, field=foo)] Then the resulting objs should be: objs = [Model(id=1, field=bar)] Is something like this possible? -
Unable to add some foreign key fields
I'm getting an odd error when I run migrations that add foreign key fields ever since I upgraded to Django 2.0 django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "auth_user" Any ideas why? This is my model class: class Tag(models.Model): """ """ titles = models.ManyToManyField('main.Sentence') parent = models.ForeignKey('Tag',null=True,blank=True, on_delete=models.SET_NULL) author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True) This is the migration file instantiation of it: migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)), ('parent', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='coach.Tag')), ('titles', models.ManyToManyField(to='main.Sentence')), ], options={ 'ordering': ['-created'], }, ), And here's how the SQL is generated: ALTER TABLE "coach_tag" ADD CONSTRAINT "coach_tag_author_id_6e9296b3_fk_auth_user_id" FOREIGN KEY ("author_id") REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED; SQL Error [42830]: ERROR: there is no unique constraint matching given keys for referenced table "auth_user" org.postgresql.util.PSQLException: ERROR: there is no unique constraint matching given keys for referenced table "auth_user" I did rename some tables in my DB and had to do some modification via SQL to make things work. I'm using PostgreSQL. I renamed tables I made sure I renamed entries in django_content_type I have not renamed entries in Postgres "sequences", but the auto-inc primarykey for each table seems to still … -
django_rest_auth issue with confirmation email link
I have encountered a weird problem regarding email confirmations with the django_rest_auth app. Once I register an account I get an email with a link to account verification. However, once I click that link I get the following issue. I suspect that it is having trouble recognizing the correct url. My code in urls.py looks like this: urlpatterns = [ path('registration/account-confirm-email/<str:key>/', allauthemailconfirmation, name="account_confirm_email"), path('registration/', include('rest_auth.registration.urls')), path('facebook/', FacebookLogin.as_view(), name='fb_login'), path('twitter/', TwitterLogin.as_view(), name='twitter_login'), path('', include('rest_auth.urls')), ] The entire link to the confirmation looks something like this: http://127.0.0.1:8000/userauth/registration/account-confirm-email/NQ:1eUhNY:63MLLVxQ0bCKzspyXk4pO8VBqxA/ Thanks -
How to perform float to datetime conversion in the Django queryset
I have been searching a lot, and it's strange to me that nobody here had a similar problem. Well, in general, I need to query "available" tests which could be submitted. Let me explain this in details: I have my model (and not a permission to change it): class ScheduledTest(BaseModel): start = models.DateTimeField() duration = models.DecimalField(verbose_name="Duration (in hours)", max_digits=5, decimal_places=2) test_setup = models.ForeignKey(TestSetup, related_name="scheduled_tests") creator = models.ForeignKey(AppUser, related_name="scheduled_tests") def __str__(self): return self.test_setup.title + " | " + self.test_setup.subject.title + \ " | {}".format(self.start.date()) + " | Duration: {} h".format(self.duration) Now I want to query for ScheduledTests that have their start datetime between timezone.now() and timezone.now() + test.duration plus tests that have their start datetime bigger than timezone.now(). So this is my try: self.queryset = ScheduledTest.objects.all() available_tests = \ self.queryset.filter(start__gte=timezone.now())\ .union(self.queryset.filter(start__range=(timezone.now(), timezone.now() + timezone.timedelta(hours=F('duration')))) ) But... of course I get an exception because F('duration') cannot be calculated before the query is executed. Precisely, I get an error that hours expects float as an argument and not the F() Please help, what can I do? My idea is to somehow make a statement that will achieve conversion from float to date directly in the DB query, but I don't know how to … -
MySQL-python installation not working within virtualenv
I am trying to connect a MySQL database to my Django project, but when I try to install MySQL-python, it gives me the following error: Collecting mysql-python Using cached MySQL-python-1.2.5.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/fr/3k1nrq490dzdz9s48k49m9640000gn/T/pip-build-4dsuxwwv/mysql-python/setup.py", line 13, in <module> from setup_posix import get_config File "/private/var/folders/fr/3k1nrq490dzdz9s48k49m9640000gn/T/pip-build-4dsuxwwv/mysql-python/setup_posix.py", line 2, in <module> from ConfigParser import SafeConfigParser ModuleNotFoundError: No module named 'ConfigParser' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/fr/3k1nrq490dzdz9s48k49m9640000gn/T/pip-build-4dsuxwwv/mysql-python/ I have tried pip3 install ConfigParser, but while it gets installed, the error still occurs. When I try to run my Django server, it prints out a long error log, and at the end: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? and when I looked at the following link, it said that I should install MySQL-python: Django mysqlclient install May seem like a newbie question, but I can't seem to find similar errors elsewhere online. -
Change Date Time Format in Django REST Object
I've been trying to tackle this problem for quite a while now. please help if possible... I have a REST framework response where one of the datetime values is in UTC format. I want to change this format into a more readable view. rest framework output: { "data": [ { "id": "1", "start_time": "2017-12-28T12:56:55-08:00", }, { "id": "2", "start_time": "2017-12-28T12:14:10-08:00", }, { "id": "3", "start_time": "2017-12-28T09:37:35-08:00", }, ] } views: (my code to change the start_time format in the display) serializer = ChangeLogSerializer(changelog['items'], many=True) for log in serializer.data: serializer.data[log]['start_time'] = log['start_time'].strftime('%Y-%m-%d %T') Observations: serializer.data[log] doesn't appear to be correct way to update this item gives error message: File "/root/venv/dashbaord/lib/python3.4/site-packages/rest_framework/utils/encoders.py", line 68, in default return super(JSONEncoder, self).default(obj) Tried in my serializers.py file to adjust the format: start_time = serializers.DateField(format="%y-%m-%d %H:%M:%S"), but it doesn't do anything -
How to get the absolute string from a name-spaced Django URL?
You know how in a Django app, you can redirect to a different view using a simple function in your views? Its usually something like this: return redirect('myapp:my_url') The above redirect would redirect me to an absolute URL which could be something like this: https://example.com/my-url/ Now, my question is, how can I get the https://example.com/my-url/ as a string using a function in my view? I don't want to redirect, I just want to get it, and save it in my variable. So, by doing something like this: print my_function('myapp:my_url') We would get an output in the terminal like so: https://example.com/my-url/ Any help? Thanks! -
'>' not supported between instances of 'method' and 'int'
So i'm working on this matchmaking app. There's a class in my models.py that goes: class PositionMatchManager(models.Manager): def update_top_suggestions(self, user, match_int): matches = Match.objects.get_matches(user)[:match_int] for match in matches: job_set = match[0].userjob_set.all() if job_set.count > 0: for job in job_set: try: the_job = Job.objects.get(text__iexact=job.position) jobmatch, created = self.get_or_create(user=user, job=the_job) except: pass try: the_loc = Location.objects.get(name__iexact=job.location) locmatch, created = LocationMatch.objects.get_or_create(user=user, location=the_loc) except: pass try: the_employer = Employer.objects.get(name__iexact=job.employer_name) empymatch, created = EmployerMatch.objects.get_or_create(user=user, employer=the_employer) except: pass When i ran my server, i got an error message saying TypeError at /accounts/login/ '>' not supported between instances of 'method' and 'int'