Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx always falls back to default config
My stack is django, gunicorn, nginx and supervisor running on a VPS from DigitalOcean. Supervisor is running the program correctly but I always get the NGINX welcome page. If I delete the default nginx config file everything works and I get the website. Here are my custom settings: upstream maet_app_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/webapps/maet/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name maet.bg www.maet.com; client_max_body_size 4G; access_log /webapps/maet/logs/nginx-access.log; error_log /webapps/maet/logs/nginx-error.log; location /static/ { alias /webapps/maet/website/static/; } location /media/ { alias /webapps/maet/website/static/; } location / { # an HTTP header important enough to have its own Wikipedia entry: # http://en.wikipedia.org/wiki/X-Forwarded-For proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # enable this if and only if you use HTTPS, this helps Rack # set the proper protocol for doing redirects: # proxy_set_header X-Forwarded-Proto https; # pass the Host: header from the client right along so redirects # can be set properly within the Rack application proxy_set_header Host $http_host; # we don't want nginx trying to do something clever with # redirects, we set the Host: header above … -
Django get_or_create violating unique key constraint with MS SQL (works with PostgreSQL)
I have a Django project that I recently moved from PostgreSQL to MS SQL. In it is the following model: class HIL(UniquelyNamedModel): hil_states = ((i, i) for i in HIL_STATES) app_states = ((i, i) for i in APP_STATES) ip = models.GenericIPAddressField() state = models.CharField(max_length=NAME_MAX_LENGTH, choices=hil_states, default=HIL_STATES.OFFLINE) suite = models.OneToOneField(Suite, related_name='hil', blank=True, null=True, on_delete=models.SET_NULL) application = models.ForeignKey(Application, related_name='hils', blank=True, null=True, on_delete=models.SET_NULL) application_state = models.CharField(max_length=NAME_MAX_LENGTH, choices=app_states, default=APP_STATES.DISCONNECTED) It inherits from a simple abstract model: class UniquelyNamedModel(models.Model): name = models.CharField(max_length=NAME_MAX_LENGTH, unique=True) class Meta: abstract = True def __unicode__(self): return self.name I had no issues with these models when working with PostgreSQL, but now that I've switched to MS SQL, I cannot create more than one HIL. An attempt to add a second row fails with a Violation of UNIQUE KEY constraint, with message Cannot insert duplicate key in object. I using different names and IPs for the two entries. I see the error when using Django's admin tool as well as when using a simple get_or_create: hil = HIL.objects.get_or_create(name=name, ip=ip)[0] hil.save() Django seems to accept the creation of the second entry - the error is from MS SQL. How can I resolve this situation? -
Django login function - TypeError: context must be a dict rather than Context
Context must be a dict rather than Context Hey. I'm relatively new to Python and Django and am working on a project. I need to figure out a problem I'm having with the login view. No matter what I try I keep getting this type error. Here are the html template and login view: login.html template {% extends "base.html" %} {% load bootstrap_tags %} {% block content %} <form role="form" method="post" action="{% url 'login' %}"> <legend>Login</legend> {% csrf_token %} {{ form| as_bootstrap }} <div class="form-group"> <button type="submit" class="btn btn-primary">Login</button> </div> </form> {% endblock %} Login function in accounts/views.py def login(request): if request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): user = auth.authenticate(email=request.POST.get('email'), password=request.POST.get('password')) if user is not None: auth.login(request, user) messages.error(request, "You have successfully logged in") return redirect(reverse('index')) else: form.add_error(None, "Your email or password was not recognised") else: form = UserLoginForm() args = {'form': form} args.update(csrf(request)) return render(request, 'login.html', args) When I attempt to navigate to login template from index on local server it returns a typeError: context must be a dict rather than Context. Would someone please shed some light on this error, not been able to find a solution yet. -
Django failing migration - Cannot query "peterson": Must be "User" instance
I'm on Django 1.9, Python 3.6. I made this migration to try and fill in UserProfiles for any users missing them. But I'm getting the error below. What's strange is the "user" variable seems to be a User instance. from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import User def create_missing_profiles(apps, schema_editor): UserProfile = apps.get_model("myapp", "UserProfile") for user in User.objects.all(): UserProfile.objects.get_or_create(user=user) class Migration(migrations.Migration): dependencies = [ ('myapp', '0004_auto_20170721_0908'), ] operations = [ migrations.RunPython(create_missing_profiles), ] Error: ValueError: Cannot query "peterson": Must be "User" instance. -
How to dump into files request/response pairs in Django?
I want to store (in files) all request/response pairs of views in a Django app. How to do this? I could probably use tcpflow, but would prefer to use a Python solution in Django itself rather than external programs like tcpflow (which also requires root privileges, what I dislike). -
Wrong inheritance behavior in factory boy factories
I have several factories with structure like this: AbstractFactoryMinimal(DjangoModelFactory): comment = '' AbstractFactoryFull(AbstractFactoryMinimal): comment = Faker(provider='text', max_nb_chars=2000) FactoryMinimal(AbstractFactoryMinimal): field = '' class Meta(object): model = SomeModel FactoryFull(FactoryMinimal, AbstractFactoryFull): field = Faker(provider='text', max_nb_chars=2000) obj = FactoryFull() print(obj.comment) # expect some text from faker, but got '' instead print(obj.field) # works like expected, return some random text In models I have AbstractModel(TimeStampedModel) and SomeModel(AbstractModel) I even look at mro and it's looks like exactly how I expected it to look: (FactoryFull, FactoryMinimal, AbstractFactoryFull, AbstractFactoryMinimal, factory.django.DjangoModelFactory, factory.base.Factory, factory.base.BaseFactory, object) So "comment" field should be generated by faker and not just set with ''. Why it is work this way? How I can implement factories to see expected behavior? -
using signals to save on the django model
i have a video model which used pymovieclip to grab the duration of the video file in and then try to add it to the model being saved. i am able to grab the info with no problem but saving it to the instance does not work @receiver(post_save, sender=Video) def save_user_profile(sender, instance, **kwargs): print('Saved: {}'.format(instance.id)) video = Video.objects.get(pk=instance.id) path = os.path.join(settings.MEDIA_ROOT,"{}".format(video.video)) duration = VideoFileClip(path).duration print('Saved: {}'.format(duration)) actual = round((duration / 60), 2) video.video_duration = actual ` but it doesnt work. adding ".save()" also puts the server in a loop -
generating a pdf using report lab with django 1.8 when I add an external style sheet I get the following error
I am using report lab with django 1.8 to generate html pages into pdfs, Although when I include external style sheets I get the error below, Is there any way of fixing this. Selector Pseudo Function closing ')' not found:: (u':not(', u'[controls]){display:') html template <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <title>My Title</title> <style type="text/css"> @page { size: {{ pagesize }}; margin: 1cm; @frame footer { -pdf-frame-content: footerContent; bottom: 0cm; margin-left: 9cm; margin-right: 9cm; height: 1cm; } } </style> </head> <body> <h2>Example PDF conversion</h2> <table class="table table-bordered"> <thead> <tr> <th>name</th> <th>age</th> </tr> </thead> <tbody> {% for item in mylist %} <td>example</td> {% endfor %} </tbody> </table> <div id="footerContent"> {%block page_foot%} Page <pdf:pagenumber> {%endblock%} </div> </body> </html> render to pdf function def render_to_pdf(template_src, context_dict): template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) -
error serializer.data when I'm not accesing it
I have the error: You cannot call .save() after accessing serializer.data.If you need to access data before committing to the database then inspect 'serializer.validated_data' instead. Even if I'M NOT accesing serialized.data but serialized.validate_data. Here is my code: views.py class Login(APIView): """ Verify the login given is correct. #FIXME """ def post(self, request, format=None): """Process the user given """ serializer = LoginSerializer(data=request.data) if not serializer.is_valid(): return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) if serializer.verify_user(serializer.validated_data): serializer.save() return Response( serializer.data, status=status.HTTP_201_CREATED ) verify_user is a custom function I did. If I don't use validated_data in that function, save() is executing. If not It gives that message. Inside I don't modify validated_data: serializers.py class LoginSerializer(serializers.Serializer): """Interface fields for login api """ username = serializers.CharField(max_length=50) password = serializers.CharField(max_length=255) origin = serializers.CharField(max_length=255, required=False) def verify_user(self, validated_data): """ Try to authenticate a user with given credentials :return: True on success """ password_valid = validated_data['password'] username_valid = validated_data['username'] # TODO: Put in utilities _password_crp = self.cryp_password(password_valid) # 1 verify new table user = User.objects.filter( username=username_valid, password=_password_crp ) if user is None or user.count() == 0: return False return True -
Django simple URL Mapping issue
Have a small issue and wondering if some one can help me out. I have a text search box like this that <form class="navbar-form navbar-left" role="search" action="/library/search/"> <div class="form-group" style="display:inline;"> <div class="input-group"> <input class="form-control" id="q" name="P" type="text" placeholder="Book Search""> <span class="input-group-btn"> <button class="btn btn-primary" type="submit"><i class="glyphicon glyphicon-search"></i></button> </span> </div> </div> </form> When I type in a word and hit submit a URL is generated as follows, http://127.0.0.1:8000/library/search/?P=Harry+Potter In the URLs.py I have something like this url(r'^search/(?P<search_result>[\w|\W.@+-]+)/$', views.search_view, name='search_view') However the above url is not being matched by the regex statement. If I manually remove the ?P= from the url it works fine. I have tried some of the following combination and they didn't work either url(r'^search/(?P(.*)<search_result>[\w|\W.@+-]+)/$', views.search_view, name='search_view') Any idea what it could be ? Thanks -
Django creating model with foreign key
I have models like following: class Task(models.Model): what_task = models.CharField(max_length=100, ) #This helps to print in admin interface def __str__(self): return u"%s" % (self.what_task) class Step(models.Model): task = models.ForeignKey(Task, related_name='steps', on_delete=models.CASCADE, ) what_step = models.CharField(max_length=50, blank=True, ) #This helps to print in admin interface def __str__(self): return u"%s" % (self.what_step) I have serializers: class StepSerializer(serializers.ModelSerializer): class Meta: model = Step fields = '__all__' class TaskSerializer(serializers.ModelSerializer): steps = StepSerializer(many=True) class Meta: model = Task fields = '__all__' def create(self, validated_data): steps_data = validated_data.pop('steps') task = Task.objects.create(**validated_data) for step_data in steps_data: Step.objects.create(task=task, **step_data) return task and my views: @api_view(['GET', 'POST']) def task_list(request): """ List all tasks, or create a new task. """ if request.method == 'GET': tasks = Task.objects.all() serializer = TaskSerializer(tasks, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = TaskSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) I am expecting that when I create a Task, I also create it's Steps in a single request. My request JSON sent from frontend looks like following: {what_task: "Sample task three", steps:[{task: 0, what_step: "Test Step"}]} This throws me {"steps":[{"task":["This field is required."]}]} error. What am I doing wrong? Am I sending wrong JSON? P.S.: As I do not … -
Django saving models in different databases
I am new to Django. I have two apps created in my project: python3 manage.py startapp app1 python3 manage.py startapp app1 I am using Mysql as DB and I want that each app should use different schemas. I try to follow the steps described here: Sharing (mysql) database between apps Django with Database routers So in settings.py I defined 2 MySql schemas and keep default schema and add the add the DATABASE_ROUTERS. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1', 'app2', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'mydb1':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'APP1DB', 'USER': 'user1', 'PASSWORD': '****', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', }, 'mydb2':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'APP2DB', 'USER': 'user1', 'PASSWORD': '****', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', }, } DATABASE_ROUTERS = ['app1.dbRouter.App1DBRouter', 'app2.dbRouter.App2DBRouter'] Additional files: app1/models1.py from django.db import models # Create your models here. class Model1(models.Model): name = models.CharField(max_length=100) app2/models2.py from django.db import models # Create your models here. class Model2(models.Model): name = models.CharField(max_length=100) And files: app1/dbRouter.py class App1DBRouter(object): def db_for_read(self,model, **hints): if model._meta.app_label == 'app1': return 'mydb1' return None def db_for_write(self,model, … -
is it possible to decrease the line of codes below
i'm trying to do filter based on queryparams. if fridge == 'true' and toilet == 'true' and side_window == 'true': queryset = queryset.filter(toilet=True, fridge=True, sun_side_window=True) elif fridge == 'true' and toilet == 'true': queryset = queryset.filter(toilet=True, fridge=True) elif fridge == 'true' and side_window == 'true': queryset = queryset.filter(sun_side_window=side_window.capitalize(), fridge=fridge.capitalize()) elif toilet == 'true' and side_window == 'true': queryset = queryset.filter(sun_side_window=side_window.capitalize(), toilet=toilet.capitalize()) elif fridge == 'true': queryset = queryset.filter(fridge=fridge.capitalize()) elif toilet == 'true': queryset = queryset.filter(toilet=toilet.capitalize()) elif side_window == 'true': queryset = queryset.filter(sun_side_window=True) -
Django, Some part of form should change based on TypedChoiceField list selection
I am new to django I have a requirement where in based on the TypedChoiceField list selection some part of the form should be changed. Meaning for a particular selection I need some fields to be displayed on the webpage and for other selection I need some other fields to be displayed on the webpage. Please help me. If there is already a similar page existing, please point me to that page, it will help me a lot. -
Dajngo :ImportError: cannot import name Celery
Good morning It is the first time I use celery, I went through this Using celery with Django but when I run th code it gives me the following error : from celery import Celery ImportError: cannot import name Celery What is wrong ? Thank you -
django-restframework serialize relations as dictionaries rather then arrays
I'm trying to serialize foreign keys as dictionaries instead of arrays. Right now the json looks the following: { "slug": "en", "children": [{ "slug": "pants", "children": [{ "slug": "products/:level1", "children": [{ "slug": ":level2/:level3", "children": [] }] }, { "slug": ":productSlug", "children": [] } ] }, { "slug": "pullovers", "children": [] } ] } But I'd like it to use the slugs as keys: { "en": { "children": { "pants": { "children": { "products/:level1": { "children": { ":level2/:level3": { "children": {} } } } }, ":productSlug": { "children": {} } ] } } } Is it possible to do that directly in the serializer or do I have to convert it in an additional step? -
Django Translation Issue: makemessages command not working to and detecting new {% blocktrans %} tags
I have recently taken over a django project which contains a locale folder. Since then I have added many new {% blocktrans %} tags to the html files. However when I use the command: python manage.py makemessages -l vi to detect new tags, I get an error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/Brigadier90/Projects/RoyalExc/myvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/Brigadier90/Projects/RoyalExc/myvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/Brigadier90/Projects/RoyalExc/myvenv/lib/python3.6/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/Users/Brigadier90/Projects/RoyalExc/myvenv/lib/python3.6/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/Users/Brigadier90/Projects/RoyalExc/myvenv/lib/python3.6/site-packages/django/core/management/commands/makemessages.py", line 361, in handle potfiles = self.build_potfiles() File "/Users/Brigadier90/Projects/RoyalExc/myvenv/lib/python3.6/site-packages/django/core/management/commands/makemessages.py", line 393, in build_potfiles self.process_files(file_list) File "/Users/Brigadier90/Projects/RoyalExc/myvenv/lib/python3.6/site-packages/django/core/management/commands/makemessages.py", line 488, in process_files self.process_locale_dir(locale_dir, files) File "/Users/Brigadier90/Projects/RoyalExc/myvenv/lib/python3.6/site-packages/django/core/management/commands/makemessages.py", line 580, in process_locale_dir write_pot_file(potfile, msgs) File "/Users/Brigadier90/Projects/RoyalExc/myvenv/lib/python3.6/site-packages/django/core/management/commands/makemessages.py", line 191, in write_pot_file with io.open(potfile, 'a', encoding='utf-8') as fp: FileNotFoundError: [Errno 2] No such file or directory: 'locale/django.pot' (myvenv) Brigadier90s-MacBook-Pro:royalexc Brigadier90$ python manage.py makemessages -l vi Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/Brigadier90/Projects/RoyalExc/myvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/Brigadier90/Projects/RoyalExc/myvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/Brigadier90/Projects/RoyalExc/myvenv/lib/python3.6/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/Users/Brigadier90/Projects/RoyalExc/myvenv/lib/python3.6/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/Users/Brigadier90/Projects/RoyalExc/myvenv/lib/python3.6/site-packages/django/core/management/commands/makemessages.py", line 361, … -
djagno filter regex not working while python re works
I am trying to do iregex match in django for the regular expression reg_string = (\w|\d|\b|\s)+h(\w|\d|\b|\s)+(\w|\d|\b|\s)+anto(\w|\d|\b|\s)+ self.queryset.filter(name__iregex=r"%s"%(reg_string,)) by using the word "The Canton" for name but its not returning any value but while using it in python re.search its working print (re.search(r'(\w|\d|\b|\s)+h(\w|\d|\b|\s)+(\w|\d|\b|\s)+anto(\w|\d|\b|\s)+', 'The Canton', re.I).group() I am using Mysql 5.7, any one know how to fix this -
How to pass path for static files to js file in django
I have Django project where formset use javascript. I have js file where I have to pass path to static file - icon, to show icon for uploaded image before update on backend side. Here is my code: if(name.substring(name.lastIndexOf(".")+1) == 'mp4'){ self.$image.attr('src', 'https://upload.wikimedia.org/wikipedia/commons/2/2f/Google_2015_logo.svg' ); How I can pass here STATIC_FILE variable? Please for any hint. Thanks. -
Django: reuse app in different django versions
I'm trying to reuse an app on 2 different django versions and I'm receiving a lot of ImportError exceptions due to the different django versions. I basically need to retrieve some info from external app, is there any nice way to do so or I would need to create an API for it? -
Django TemplateDoesNotExist at /x/ base.html
django 1.11.3 I have a template does not exist error, to my knowledge I have my template directories setup properly. fleetdb is an app I have in my project with the following directory structure: + fleetdb +templates +fleetdb -index.html -base.html (other html pages) Everything was working find until I tried {% extends 'base.html' %} inside my index like so: {% extends 'base.html' %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'fleetdb/lists.css' %}" /> {% if vehicles_list %} <ul> {% for vehicle in vehicles_list %} <li><a href="{% url 'fleetdb:detail' vehicle.id %}">{{ vehicle.unit }} {{ vehicle.make }} {{ vehicle.vmodel }} {{vehicle.color}}</a></li> </ul> {% endfor %} {% else %} <p>No Vehicles are available.</p> {% endif %} In my settings.py I have a print(TEMPLATES) statement, and it all seems to be looking in the right areas but not finding base.html. Trace at pastebin: https://pastebin.com/raw/MQDAip64 Side Question: How can I inherit templates from another app, would it be like the url tags where {% url 'fleetdb:detail' } ? -
Need assistance with pyqt logout
I have problem with PyQt5 application and don't know how to solve it. In my tray qt application I have my user logout action button which is connected with logout function. Logout function from tray.py should activate through response my logout function on server app in views.py. In views.py I have that logout function that receive back httpResponse("User is logged out"). My question is: "How to make aware my desktop pyqt app when user press that logout button? Because I recieve response.status_code = 200 it only means that i recieve just a page, and not that user state (if user is login or logout)". Everything seems to be ok, but dont know how to proceed execution of code in tray.py/logout() desktop app - tray.py import json import sys, os, requests, uuid from Crypto import Random from Crypto.PublicKey import RSA from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QMenu from PyQt5.QtWidgets import QSystemTrayIcon from login import LoginForm from settings import HTTP_PROTOCOL from settings import SERVER_URL from timestamp.form import TimestampForm class SystemTrayIcon(QSystemTrayIcon): def __init__(self): QSystemTrayIcon.__init__(self) self.setIcon(QIcon('icons/icon-placeholder_128x128_red.png')) self.http_client = requests.Session() self.base_url = '{}://{}'.format(HTTP_PROTOCOL, SERVER_URL) self.set_desktop_timezone() # Keeping reference to LoginForm object so that window wouldn't close self.uuid = self.create_uuid('TTASM') self.create_private_key() try: requests.get(self.base_url) self.server_accessible = … -
django.db.utils.IntegrityError: UNIQUE constraint failed
Hi m new in django framework and I am trying to solve this problem from 2 day I am getting this error after python manage.py migrate command. I cant understand what the problem is? models.py from django.db import models from django.utils import timezone class BlogPost(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=100,unique=True) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True,null=True) def publish(self): self.published_date=timezone.now() self.save() def __str__(self): return self.title error File "/home/letsperf/.conda/envs/MyDjangoEnv/lib/python3.5/site-packages /django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/letsperf/.conda/envs/MyDjangoEnv/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/letsperf/.conda/envs/MyDjangoEnv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 515, in alter_field old_db_params, new_db_params, strict) File "/home/letsperf/.conda/envs/MyDjangoEnv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 262, in _alter_field self._remake_table(model, alter_field=(old_field, new_field)) File "/home/letsperf/.conda/envs/MyDjangoEnv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 206, in _remake_table self.quote_name(model._meta.db_table), File "/home/letsperf/.conda/envs/MyDjangoEnv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/home/letsperf/.conda/envs/MyDjangoEnv/lib/python3.5/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/letsperf/.conda/envs/MyDjangoEnv/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/letsperf/.conda/envs/MyDjangoEnv/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/letsperf/.conda/envs/MyDjangoEnv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/letsperf/.conda/envs/MyDjangoEnv/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/letsperf/.conda/envs/MyDjangoEnv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: social_blogpost.title please help I am confused !! -
Filter django query by unicode characters 🐲 or 💎 etc
I have a model: class Trophy(models.Model): server = models.CharField(max_length=191, blank=True) title = models.CharField(max_length=191, blank=True) note = models.TextField(blank=True) badge = models.CharField(max_length=191) badge - is a field for unicode characters like 🐲 or 💎 or 🔝 or ☔️ or 💯 etc... I have three objects in database: Dragon (badge=🐲) Antiaircrafter (badge=☔️) Diamond player (badge=💎) I have not problem to get trophy with badge ☔️: trophy = Trophy.objects.get(badge=u"☔️") But I can't get 🐲 or 💎: trophy = Trophy.objects.get(badge=u"🐲") MultipleObjectsReturned: get() returned more than one Trophy -- it returned 2! And one more thing: I can't see 🐲 and 💎 in MySQL Workbench (only "?") untill run: SET NAMES utf8mb4; Any idea how to work with utf8mb4 in django queries? -
Django Website copy an file (by path) to clipboard on Linux Ubuntu Server
I have a project that is supposed to be a simple website, where a textbox and a button is. With textbox you enter a path, where a file is stored and by clicking on the button it will be automatically re-copied to a fixed path. I have a Ubuntu Linux OS with the framework django. I hope you can help me Thanks