Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
django imagefield display image and have browse button for the form
In my django app, I have been able to include image for an imagefield form, however there is no browse button to upload a new image. How do I include this browse button to upload a new image ? Currently it looks like this: https://imgur.com/a/Qu4JE And here is my form code: class PictureWidget(forms.widgets.Widget): def render(self, name, value, attrs=None): html = Template("""<img src="$link" height=50 width=50 />""") logging.debug("value %s" % value.url) return mark_safe(html.substitute(link=value.url)) class EmployeeFaceImageUploadForm(forms.ModelForm): face_image = forms.ImageField(widget=PictureWidget) class Meta: model = Employee fields = ("face_image",) -
Django - How to pass value after submit when editing form?
I'm trying to pass a data to my form when it's being edited I have the following code: form = senalesEipForm(request.POST or None, instance=eip,prefix='form') new_data_2 = None form2 = reglasForm(request.POST or None, instance=regla,prefix='form3') form3 = patronInicioForm(request.POST or None,initial={'minutos':minuto_inicio,'hora':hora_inicio,'dia_mes':dia_mes_inicio,'mes':mes_inicio,'semana':semana_inicio}, prefix="form3") form4 = patronFinalForm(request.POST or None,initial={'minutos':minuto_fin,'hora':hora_fin,'dia_mes':dia_mes_fin,'mes':mes_fin,'semana':semana_fin}, prefix="form4") print form2 if form.is_valid() and form2.is_valid() and form3.is_valid() and form4.is_valid(): nuevo_minuto_inicio = form3.cleaned_data['minutos'] nuevo_hora_inicio = form3.cleaned_data['hora'] nuevo_dia_mes_inicio = form3.cleaned_data['dia_mes'] nuevo_mes_inicio = form3.cleaned_data['mes'] nuevo_semana_inicio = form3.cleaned_data['semana'] new_data_1 = '0' + '' + nuevo_minuto_inicio + '' + nuevo_hora_inicio + '' + nuevo_dia_mes_inicio + '' + nuevo_mes_inicio + '' + nuevo_semana_inicio nuevo_minuto_fin = form4.cleaned_data['minutos'] nuevo_hora_fin = form4.cleaned_data['hora'] nuevo_dia_mes_fin = form4.cleaned_data['dia_mes'] nuevo_mes_fin = form4.cleaned_data['mes'] nuevo_semana_fin = form4.cleaned_data['semana'] new_data_2 = '0' + '' + nuevo_minuto_fin + '' + nuevo_hora_fin + '' + nuevo_dia_mes_fin + '' + nuevo_mes_fin + '' + nuevo_semana_fin form.save(commit=False) form2.save(commit=False) pfin = new_data_2 print pfin form2.save() form.save() In this case, basically what I want is get the data from form3 and form4 and pass it to form2, I tried with initial but it's not working when I use instance I tried with JavaScript but not working.... What can I do to solve this? for example, what's in pfin I need it in form3.properties properties is a field … -
django rest framework hyperlinkrelatedfield for one table using its primary key
I have a table called 'users' and 'location'. Users table has a foreign key that relates to location table. I have a users serializer to get the JSON. What would I do to get the hyperlinks for the users table using its primary key? In django rest framework documentation, I couldn't find a solution. I tried using hyperlinkrelatedfield. But still I couldn't achieve this. Can someone help me in finding the solution? I need the URL like 127.0.0.1:8000/users{userid}. It should give the JSON of the user whose userid is specified in the URL -
split data and save values using django rest framework
I have models- class Web2Types(models.Model): name = models.CharField(max_length=200, unique=True) status = models.IntegerField(default=0) class Web2Domains(models.Model): domain = models.CharField(max_length=255, unique=True) web2type = models.ForeignKey(Web2Types) Now I have a string containing commas, I want that string first split by comma then all values of that list will save into Web2Domains model. I tried some methods in serializer.py but got confused. -
Javascript arrays and updating <ul><li></li></ul> elements with a loop?
I'm struggling with this one a little. I'm a junior python developer by trade and I have been asked to build a website. Naturally I said yes and chose Django. Regardless, I'm having a little issue building a calendar widget. I'm using AJAX to pass the request back to the view, and update certain elements based on whether the user is requesting the previous/next month of days. function getPreviousMonth( event ) { $.ajax({ type: "GET", dataType: "json", url: "{% url 'events' %}", data: { 'month': previousMonth, 'year': previousYear } }) .done(function(response) { console.log(response); nextMonth = response.next_month; nextYear = response.next_year; previousMonth = response.previous_month; previousYear = response.previous_year; currentMonth = response.current_month; currentYear = response.current_year; $('#currentMonth').text(currentMonth); $('#currentYear').text(currentYear); }); }; This all seems to be working well. In the response object I have an array of lists (I think, certainly correct me if I am wrong). On the template side I am using Django to setup the calendar from an array of days arrays: {% for week in weeks %} <ul class="days"> {% for day in week %} {% if day == 0 %} <li></li> {% else %} <li>{{ day }}</li> {% endif %} {% endfor %} </ul> {% endfor %} All looks nice (and …