Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django middleware: UnboundLocalError: local variable 'background_color' referenced before assignment
I'm trying to randomise certain elements of my theme across a website I'm building. I thought it might be quite nice to experiment with defining some custom middleware to handle this. But it looks like I've gone wrong somewhere: middleware.py: class RandomThemeAppearanceMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): theme = { background_color: '#266040', contrast: '#3bbfad', color: '#ffffff', } background_colors = ['#266040', '#009a16', '#015e85', '#d6006d'] background_color = random.choice(background_colors) if background_color == '#266040': theme['contrast'] = '#3bbfad' elif background_color == '#009a16': theme['contrast'] = '#fedf21' elif background_color == '#015e85': theme['contrast'] = '#0590b3' elif background_color == '#d6006d': theme['contrast'] = '#f97fb5' else: pass theme['background_color'] = background_color request.background_color = theme['background_color'] request.contrast = theme['contrast'] request.color = theme['color'] return self.get_response(request) Django debug is telling me the following: UnboundLocalError at / local variable 'background_color' referenced before assignment Can anyone shed any light on why this is error is being thrown? -
How to set a Background image in Django template?
I am new to Django and was using it for my project until I faced a small problem which is really small but is bothering me from 2 days. How to apply a background image in the django template ? Here's my index.html :- <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel=" stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link href="https://fonts.googleapis.com/css?family=Cabin+Sketch" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Dosis:800" rel="stylesheet"> <title>Document</title> <style type="text/css"> body { background: url({% static "images/dumb2.jpg" %}); background-size: cover; } .heading { color: white; font-family: 'Sedgwick Ave Display', cursive; font-size: 10vw; letter-spacing: 20px; color: rgb(0, 255, 170); padding-top: 20px; font-family: 'Cabin Sketch', cursive; } .data-rows { padding-top: 10px; } .textfield-labels { color: white; font-weight: 600; } .textfield { border: 5px solid black; } .signup-heading { color: white; font-family: 'Dosis', sans-serif; letter-spacing: 20px; } .bored { height: 300px; width: 300px; } .font-icons { color: white; font-size: 50px; } .description { color: white; font-weight: 600; } .first-description { padding: 10px; border-radius: 20px; border: 1px solid rgb(117, 19, 19); animation-name: first-block; animation-duration: 6s; animation-iteration-count: infinite; animation-direction: alternate; } .left-column { padding: 20px; } ::-moz-placeholder { text-align: center; } ::-webkit-input-placeholder { text-align: center; } @keyframes first-block … -
Remove filter in xlsx file with pandas
I am new to pandas, and I am doing a graph visualization using plotly from an xlsx file. I have manager to do this, but the thing is that the xlsx file has a daily filter, so it accumulate the rows that have same date. But what I want, is to desactivate the daily filter, in order to show the values of hours in the days. This is how the data are in the xlsx file And here is the bit of code that am using to visualize the data : df = pd.read_excel("Hourly_daily.xlsx").sort_values('Date') df = df[(df['Date'] != str(datetime.now().date()))].tail(7) trace1 = go.Scatter( x=df['Date'], y=df['TEST'], mode='lines+markers', name='Trafics' ) trace2 = go.Scatter( x=df['Date'], y=df['%'], mode='lines+markers', name='Pourcentage', yaxis='y2' ) data = [trace1, trace2] layout = go.Layout( title='Graphe avec double axes', yaxis=dict( title='Trafic' ), yaxis2=dict( title='Pourcentage', titlefont=dict( color='rgb(148, 103, 189)' ), tickfont=dict( color='rgb(148, 103, 189)' ), overlaying='y', side='right' ) ) fig = go.Figure(data=data, layout=layout) plotly.offline.plot(fig, filename='C:/Users/elmou/Desktop/albumaster_final/test0\music/templates/music/multiple-axes-double.html', auto_open=False) -
Parse data from yaml file to dictionary and updating in Django models
I have a yaml file, which i am parsing into dictionary. as follow- def parse(self): with open("/students.yml", 'r') as stream: try: return (yaml.load(stream)) except yaml.YAMLError as exc: print(exc) After parsing this file into dictionary i am getting a large data in dictionary as like follow - { u 'A101\ab0\ab0': { 'NAME': 'RAZ', 'AGE': '17', 'ROLLNO': u 'A101\ab0\ab0', 'CLASS': 'SIX', }, u 'A102\ab0': { 'NAME': 'OM', 'AGE': '15', 'ROLLNO': u 'A102\ab0', 'CLASS': 'SEVEN', }, u 'A103\ab0': { 'NAME': 'PURI', 'AGE': '15', 'ROLLNO': u 'A103\ab0', 'CLASS': 'SEVEN', } } I have created the Djangomodel for name, age, rollno, class field. I wanted to update models with the getting response after parsing. What could be efficient way to create object and bulk update. Any help would be appreciated. -
How do I reference a model column via string?
I'm making a terminal command where the user enters two strings. One will correspond to a model and the other to a column from that model. class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( "--model", dest="model", required=True, ) def add_arguments(self, parser): parser.add_argument( "--col", dest="col", required=True, ) def handle(self, *args, **options): # Handle stuff here I know I can do from django.apps import apps and put options["model"] in apps.get_model() to get an instance of the model the user inputs, assuming it exists. But How can I reference the column the user inputs in options["col"]? -
Django - 'module' object is not callable
I'm trying to serve images from the database with django, but when I add + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to my urlpatterns i get this error: TypeError at /: module object is not callable this is the traceback: File "/home/watch/Documents/projects/herokuapp/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/watch/Documents/projects/herokuapp/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. resolver_match = resolver.resolve(request.path_info) File "/home/watch/Documents/projects/herokuapp/venv/lib/python3.6/site-packages/django/urls/resolvers.py" in resolve 494. for pattern in self.url_patterns: File "/home/watch/Documents/projects/herokuapp/venv/lib/python3.6/site-packages/django/utils/functional.py" in __get__ 36. res = instance.__dict__[self.name] = self.func(instance) File "/home/watch/Documents/projects/herokuapp/venv/lib/python3.6/site-packages/django/urls/resolvers.py" in url_patterns 536. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/watch/Documents/projects/herokuapp/venv/lib/python3.6/site-packages/django/utils/functional.py" in __get__ 36. res = instance.__dict__[self.name] = self.func(instance) File "/home/watch/Documents/projects/herokuapp/venv/lib/python3.6/site-packages/django/urls/resolvers.py" in urlconf_module 529. return import_module(self.urlconf_name) File "/usr/lib/python3.6/importlib/__init__.py" in import_module 126. return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>" in _gcd_import 994. <source code not available> File "<frozen importlib._bootstrap>" in _find_and_load 971. <source code not available> File "<frozen importlib._bootstrap>" in _find_and_load_unlocked 955. <source code not available> File "<frozen importlib._bootstrap>" in _load_unlocked 665. <source code not available> File "<frozen importlib._bootstrap_external>" in exec_module 678. <source code not available> File "<frozen importlib._bootstrap>" in _call_with_frames_removed 219. <source code not available> File "/home/watch/Documents/projects/herokuapp/mysite/mysite/urls.py" in <module> 27. ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Exception Type: TypeError at / Exception Value: 'module' object is not callable I tried using it in both the main urls.py and the app urls.py, … -
How to assign Foreign Key static in Django Post Model
I want to add static user my Foreign Key field because of guest's post, but i can't. I try to add first id like 1, "1", "id=1" but no result. Can you help me pls? Here is my model.py; class Post(models.Model): user = models.ForeignKey('auth.User', related_name='posts') title = models.CharField(max_length=120) views.py; post = form.save(commit=False) post.user = request.user if request.user == '': post.user = 1 post.save() else: post.save() return HttpResponseRedirect(post.get_absolute_url()) etc. Thanks. -
manage.py collectstatic not working in macOS 10.13.1
I'm having issues while running collectstatic in macOS. The error is OSError: [Errno 45] Operation not supported: '/home/juan' ./manage.py collectstatic Copying '/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/contrib/admin/static/admin/css/widgets.css' Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle collected = self.collect() File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 354, in copy_file self.storage.save(prefixed_path, source_file) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/core/files/storage.py", line 49, in save return self._save(name, content) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/lib/python3.6/site-packages/django/core/files/storage.py", line 236, in _save os.makedirs(directory) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/bin/../lib/python3.6/os.py", line 210, in makedirs makedirs(head, mode, exist_ok) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/bin/../lib/python3.6/os.py", line 210, in makedirs makedirs(head, mode, exist_ok) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/bin/../lib/python3.6/os.py", line 210, in makedirs makedirs(head, mode, exist_ok) File "/Users/juan/Documents/manu/dev/sw/webwatcher/venv/bin/../lib/python3.6/os.py", line 220, in makedirs mkdir(name, mode) OSError: [Errno 45] Operation not supported: '/home/juan' ---------- The same command in the same project is running fine in ubuntu -
integrate postgresql with Django on windows
I am new to Django and Postgresql. I am trying to integrate Django with the PostgreSQL database, I modified the code in settings.py file under DATABASES. and tried to make PostgreSQL my default database. DATABASES = { 'defaults': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'Test', 'USER': 'postgres', 'PASSWORD': 'test1234', 'HOST': 'localhost', 'PORT': '', } } I am using PyCharm 2017.3.2 for the Django framework. I have installed PostgreSQL and running pgAdmin 4. My database name is Test, and I have not done anything else. but when I am trying to execute python manage.py makemigrate I am getting following error: C:\Users\Ayush\PycharmProjects\Tutorial2\tutorial2>python manage.py makemigrations Traceback (most recent call last): File "C:\Python3.6\lib\site-packages\django\db\utils.py", line 167, in ensure_defaults conn = self.databases[alias] File "C:\Python3.6\lib\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python3.6\lib\site-packages\django\db\utils.py", line 154, in databases if self._databases[DEFAULT_DB_ALIAS] == {}: KeyError: 'default' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Python3.6\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Python3.6\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Python3.6\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python3.6\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Python3.6\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Python3.6\lib\importlib\__init__.py", line 126, in … -
Could not resolve URL for hyperlinked relationship using view name ( django-rest-framework )
Problem : I am getting an error like this . ImproperlyConfigured at /api/users/ Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. I read this post but it didn't work. serializers.py class UserSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='user-detail', lookup_field='profile') class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'url') class UserProfileSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') class Meta: model = UserProfile fields = "__all__" # user = serializers.ReadOnlyField(source='owner.username') def create(self, validated_data): pass def update(self, instance, validated_data): pass urls.py user_profile_list = UserProfileViewSet.as_view({ 'get': 'list', 'post': 'create' }) user_profile_detail = UserProfileViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) user_list = UserViewSet.as_view({ 'get': 'list' }) user_detail = UserViewSet.as_view({ 'get': 'retrieve' }) user_profiles_detail = UserViewSet.as_view({ 'get': 'profile' }) router = DefaultRouter() router.register(r'userprofiles', views.UserProfileViewSet) router.register(r'users', views.UserViewSet) urlpatterns = [ url(r'^', include(router.urls)) ] views.py class UserProfileViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) pagination_class = LimitTenPagination @detail_route(renderer_classes=[renderers.JSONRenderer]) def perform_create(self, serializer): serializer.save(user=self.request.user) class UserViewSet(viewsets.ReadOnlyModelViewSet): """ This viewset automatically provides `list` and `detail` actions """ queryset = User.objects.all() serializer_class … -
How to display Image from a Model in Django - Python
I'm new to Django and i'm studying it for making a University related project. I can't figure out how to fix it: the problem is that it doesn't display the images. I'm stuck with this python code: model.py class Image(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='img') created = models.DateField(auto_now_add=True) quote = models.TextField() def __str__(self): return self.title class Meta: verbose_name = _("Image") verbose_name_plural = _("Images") def __unicode__(self): return self.quote views.py def image_list(request): image_list = Image.objects.all() return render(request, 'images/image_list.html', {'image_list': image_list}) urls.py urlpatterns = [ # post views url(r'^add_image/', views.add_image, name='login'), url(r'^image_list/', views.image_list, name='image_list'), # url(r'', views.image_list, name='list'), ] project's urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^images/', include('images.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) MEDIA_ROOT = ( BASE_DIR ) MEDIA_URL = 'images/' and image_list.html: {% extends "base.html" %} {% block title %}The Image List{% endblock %} {% block content %} <h1>Here's all your image</h1> {% for image in image_list %} <h2> <h3> {{ image.title }} </h3> <img src= "{{ image.image }}" alt="img"> <p>{{ image.quote }}</p> <p class="date">{{ image.created }}</p> </h2> {% endfor %} {% endblock %} Thank you all. -
How to use WebSockets in Django to make a multiplayer game room?
I am trying to use websockets in django to make a simple "game room" type website. The error occurs after the socket is connected, all my functions in consumers.py apart from ws_connect do not work (which i tested by printing as shown in the code) and so as a consequence my listen function in script.js does not receive any data. Any help would be appreciated ... Pls answers considering the fact that this is my first encounter with websockets. Thanking you in Advance :) consumers.py - @channel_session_user_from_http def ws_connect(message): message.reply_channel.send({'accept': True}) # Initialise their session message.channel_session['rooms'] = [] print("nikhil1") def ws_receive(message): print("nikhil43") payload = json.loads(message['text']) payload['reply_channel'] = message.content['reply_channel'] Channel("chat.receive").send(payload) print("nikhil2") @channel_session_user def ws_disconnect(message): for room_id in message.channel_session.get("rooms", set()): try: room = Room.objects.get(pk=room_id) room.websocket_group.discard(message.reply_channel) except Room.DoesNotExist: pass print("nikhil3") @channel_session_user @catch_client_error def chat_join(message): room = get_room_or_error(message["room"], message.user) print("nikhil4") if NOTIFY_USERS_ON_ENTER_OR_LEAVE_ROOMS: room.send_message(None, message.user, MSG_TYPE_ENTER) room.websocket_group.add(message.reply_channel) message.channel_session['rooms'] = list(set(message.channel_session['rooms']).union([room.id])) room.size += 1 room.save() if room.size == 2: room.websocket_group.send( {"text": json.dumps({"start":"yes","title":room.title,"join":str(room.id)})} ) else: room.websocket_group.send( {"text": json.dumps({"start":"no","title":room.title,"join":str(room.id)})} ) @channel_session_user @catch_client_error def chat_leave(message): room = get_room_or_error(message["room"], message.user) if NOTIFY_USERS_ON_ENTER_OR_LEAVE_ROOMS: room.send_message(None, message.user, MSG_TYPE_LEAVE) room.websocket_group.discard(message.reply_channel) message.channel_session['rooms'] = list(set(message.channel_session['rooms']).difference([room.id])) message.reply_channel.send({ "text": json.dumps({ "leave": str(room.id), }), }) @channel_session_user @catch_client_error def chat_send(message): if int(message['room']) not in message.channel_session['rooms']: raise ClientError("ROOM_ACCESS_DENIED") print("nikhil5") room = … -
Django with Postgresql database createsuperuser no response
I've tried to use postgresql 10 database with django 2, when i ran python manage.py makemigrations python manage.py migrate the output indicates the database is doing well. but when i try to create a supseruser python manage.py createsuperuser the console actually hangs like below: root@ca80209360d2:/app# python manage.py createsuperuser Username (leave blank to use 'root'): tdy Email address: Password: Password (again): so after i entered the passwords, it doesn't print out super user created successfully as when I'm using sqlite.. I have to Ctrl+C: ^CTraceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/kombu/utils/functional.py", line 36, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/kombu/utils/functional.py", line 333, in retry_over_time return fun(*args, **kwargs) File "/usr/local/lib/python3.5/site-packages/kombu/connection.py", line 261, in connect return self.connection File "/usr/local/lib/python3.5/site-packages/kombu/connection.py", line 802, in connection self._connection = self._establish_connection() File "/usr/local/lib/python3.5/site-packages/kombu/connection.py", line 757, in _establish_connection conn = self.transport.establish_connection() File "/usr/local/lib/python3.5/site-packages/kombu/transport/pyamqp.py", line 130, in establish_connection conn.connect() File "/usr/local/lib/python3.5/site-packages/amqp/connection.py", line 282, in connect self.transport.connect() File "/usr/local/lib/python3.5/site-packages/amqp/transport.py", line 109, in connect self._connect(self.host, self.port, self.connect_timeout) File "/usr/local/lib/python3.5/site-packages/amqp/transport.py", line 150, in _connect self.sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call … -
Django: How can I list all available RSS feeds of app?
I know how to create a new RSS feed using Django. However, I'd like to provide a page with an overview over all available RSS feeds the website provides. How can I get all the RSS feeds that are available in Django? Unfortunately, I could not find any answer yet. -
Django. How to restrict "profile" page to only "friends"
I currently have a "profile" page that displays specific users information they have uploaded. Currently it does so by objects.filter(user = request.user) Im trying to figure out how I can allow a, for lack of a better description, a "friend" to view someone else's profile. Cause right now, the user who makes the request gets their own information. I believe I know how to build the ability to "friend" another user... i just dont know how to display another users info since all ive been filtering on so far is "request.user" Im obviously a noob, be merciful :) thank you. -
Android - Django Upload Image Error on Server Side
I am trying to upload a Bitmap to Django backend using HttpUrlConnection. I understand the code quality may be poor but I have tried many different ways of doing this, hence the messy code. Any help here would be greatly appreciated. On Client Side: public class ImageUpload { private Bitmap bitmap; private putImageTask put = null; private String eventId; String token; public ImageUpload(Bitmap bitmap, String eventId, String token){ this.bitmap = bitmap; this.eventId = eventId; this.token = token; put = new putImageTask(bitmap, eventId); put.execute(); } public class putImageTask extends AsyncTask<Void, Void, Boolean> { private Bitmap bitmap; private String eventId; public putImageTask(Bitmap bitmap, String eventId){ this.bitmap = bitmap; this.eventId = eventId; } @Override protected Boolean doInBackground(Void...params) { try { String url = "http://192.168.XX.XX:8000/eventphoto/"; URL object = new URL(url); HttpURLConnection c = (HttpURLConnection) object.openConnection(); c.setDoInput(true); c.setRequestMethod("PUT"); c.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); c.setRequestProperty("Accept", "application/json"); c.setRequestProperty("Authorization", "Token " + token); c.setDoOutput(true); c.connect(); OutputStream output = c.getOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 50, output); JSONObject ev = new JSONObject(); try{ ev.put("event", eventId); }catch(JSONException e){ e.printStackTrace(); } output.write(ev.toString().getBytes("utf-8")); output.close(); StringBuilder sb = new StringBuilder(); int HttpResult = c.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader( new InputStreamReader(c.getInputStream(), "utf-8")); String line = null; while ((line = br.readLine()) != null) { sb.append(line … -
Query with many tables works very long time in Django
I have some models: class TagToPublish(models.Model): tag_to_publish = models.TextField() ru_tag = models.TextField(blank=True) eng_tag = models.TextField(blank=True) def __str__(self): return self.tag_to_publish class Tag(models.Model): tag = models.TextField(unique=True) active = models.BooleanField(default=False) tag_to_publish = models.ForeignKey(TagToPublish, blank=True, null=True, on_delete=models.SET_NULL) not_to_publish = models.BooleanField(default=False) def __str__(self): return self.tag def count(self): return self.gif_set.count() class Gif(models.Model): link = models.URLField(unique=True) # link = models.ImageField() post = models.ForeignKey(Post) tagged = models.ManyToManyField(Tag) to_publish = models.BooleanField(default=False) never_publish = models.BooleanField(default=False) choices = models.IntegerField( choices=[ (1, 'To publish'), (2, 'Never Publish'), (0, 'Null') ], default=0) def image(self): return '<image src={} />'.format(self.link) image.allow_tags = True def __str__(self): return self.link def tag_to_publish(self): for tag in self.tagged.all(): tag_to_publish = tag.tag_to_publish if tag_to_publish: return tag_to_publish class Order(models.Model): order_name = models.TextField(blank=True) class InOrder(models.Model): order = models.ForeignKey(Order) gif = models.ForeignKey(Gif) place_in_order = models.IntegerField(blank=True) published = models.BooleanField(default=False) I want to get a list with unique gif_links with the tag to publish. I wrote this code: tags = TagToPublish.objects.all() tags_to_publish = Tag.objects.filter(tag_to_publish__in=tags) gif_set = Gif.objects.filter(tagged__tag_to_publish__tag__in=tags_to_publish).distinct()[:100] But it works very long time because each Gif can have many tags and different tags can have same TagToPublish. If use filter without distinct I got many duplicates. Gif has about 180 000 items. Tags have about 70 000 items. TagToPublish has about 130 items. Each Gif has … -
return html after ajax POST
I am using an ajax call to POST a form to create an object. Once the object is created in my views, I use the object instance to render a template, footemplate say. What I would like to have happen is that footemplate is inserted into my current page, i.e. the one that contains the form. Particularly I am trying to add it to a div with id='result-container'. However when I return the rendered template it actually loads the page by itself. views def object_create(request): .... return render(request, template, template_context) AJAX $('#object-create').on('submit', function(event){ event.preventDefault(); var myform = document.getElementById('object-create'); var fd = new FormData(myform ); var post_url = $(this).attr('action'); $.ajax({ url : post_url, data : fd, cache: false, processData: false, contentType: false, type : "POST", success : function(data) { $('#result-container').html(data) }, error : function() { alert("error") } }); }); How can I return the html as text only, instead of actually generating the page on its own? -
Having trouble uploading file to Google Cloud Storage from Django(Local Windows ENV
I'm currently developing a web app that will use Google Cloud Storage for User Document uploads. I've run into a roadblock, however. When I attempt to proceed with the upload I keep getting a [Errno 2] No such file or directory: 'Marty McFly-Paycheck-06_ConditionalDirectives.pdf'. This error is confusing to me because I assumed that the file would be taken directly from my form's file upload. Am I wrong in assuming this? Should I be saving then serving the files somehow? Current Code for uploading documents to Cloud Storage #Uploading Documents function def upload_documents(bucket_name,source_file_name,destination_blob_name): storage_client = storage.Client() storage_bucket = storage_client.get_bucket(bucket_name) blob = storage_bucket.blob(destination_blob_name) blob.upload_from_filename(source_file_name) print("Document Uploaded") from .forms import DocumentUpload # Create your views here. def get_upload(request): # If this is a POST request, we will process the data -- sending it to Google Cloud Storage if request.method == 'POST': #create a form instance populated with data -- (Bound to the data previously entered that might need correction) name = request.POST['name'] titleofdocument = request.POST['titleofdocument'] doc_file = request.POST['doc_file'] fullUpload = name + "-" + titleofdocument + "-" + doc_file print(titleofdocument,name,doc_file) print(fullUpload) form = DocumentUpload(request.POST) upload_documents("upload_documents",fullUpload,"SampleBlob") else: form = DocumentUpload() return render(request, 'document-upload.html',{'form':form}) Full Stack Trace in question Marty McFly-Paycheck-06_ConditionalDirectives.pdf Internal Server Error: /upload-documents/ … -
Django: access class name in class based generic views
Using django 1.11 class based generic views ListView, DetailView & CreateView: the DRY principle works well here, but still I find quite some repetitive work in writing the templates. For each model M, a m_list,html, m_detail.html and m_form.html needs to be written. If the class name of an object could accessed from within the template, a more generic template could be written to serve multiple models. There must be a way? -
How i can find 14 migrations and apply them?
enter image description hereHow i can find 14 migrations and apply them? How easy is it to solve this problem? -
How to append/delete data from JSONField in django
I have a JSONField which i has some data like this : {'key_one' : 'val_one, 'key_two' : 'val_two'} I want to add data to it as well as deleting data from it. So far i can just give it a value not appending to it. I'm using mySql database -
Django admin foreign key dynamic verbose name
I have 100s of related models which all inherit from a base abstract class and need to define the verbose name to that of the return of the unicode method in the related class. For example in the case below it should be "Nick Name" The models.py: class Student(models.Model): user = models.OneToOneField(User) first_name = models.CharField(max_length=100,blank=True) nick_name = models.CharField(max_length=100,blank=True) def __unicode__(self): return self.nick_name class Subject(models.Model): subject = models.CharField(max_length=100,blank=True) user = models.ForeignKey(Student,verbose_name="Nick Name") -
Django admin login with staff status does not show all the permissions?
I have been trying to make an app which has 2 types of users : student and teacher. I have added permissions in both the models and they worked fine. Now when I gave the teacher acoount a staff status the entire data of the student profile does not show up . Can anyone help me out here? enter image description here Thanks -
KeyError: 'image'
When I trying to save detail, I have this error: KeyError: 'image'. I can't understand, why? Error in views.py views.py: @user_passes_test(lambda u: u.is_superuser) def new_detail(request): ImageFormSet = modelformset_factory(DetailImage, form=ImageForm, extra=10) if request.method == 'POST': form = DetailForm(request.POST) formset = ImageFormSet(request.POST, request.FILES, queryset=DetailImage.objects.none()) if form.is_valid() and formset.is_valid(): detail_form = form.save() detail_form.save() for form in formset.cleaned_data: images = form['image'] # HERE IS THE PROBLEM photo = DetailImage(detail=detail_form, image=images) photo.save() return redirect('/new_detail/') else: form = DetailForm(request.POST) formset = ImageFormSet(queryset=DetailImage.objects.none()) return render(request, 'shop/new_detail.html', {'form': form,'formset': formset}) forms.py ... class ImageForm(forms.ModelForm): image = forms.ImageField() class Meta: model = DetailImage fields = ('image',) models.py ... class DetailImage(models.Model): detail = models.ForeignKey(Detail, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to='details', null = True, blank = True)