Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django foreign key name on select
I'm working with 2 models each one in a different Django application: App products class Product(models.Model): name = models.CharField(max_length=256) price = models.FloatField() warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) def __unicode__(self): return self.name App warehouses class Warehouse(models.Model): name = models.CharField(max_length=256) def __unicode__(self): return self.name The probles is that in the admin site, when I want to create a product and I need to select a warehouse, in the select list I only see: Warehouse object Warehouse object Warehouse object What I have to do to see warehouse name? -
How To Upload Image From Admin Side In Pycharm (Django)
In Models.py, from django.db import models class Question(models.Model): question_text = models.CharField(max_length= 100) pub_date = models.DateTimeField('Date Is Published') image = models.ImageField(upload_to="Question_Image", blank=True) def __str__(self): return self.question_text class Choice(models.Model): choice_text = models.CharField(max_length= 200) votes = models.IntegerField(default= 0) question = models.ForeignKey(Question, on_delete= models.CASCADE) def __str__(self): return self.choice_text In settings.py, i added MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mysite/media') In mysite/urls.py, from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls', namespace= "polls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In index.html, {% extends 'polls/base.html' %} {% block main_content %} {% if latest_questions %} <ul> {% for question in latest_questions %} <li><a href={% url 'polls:detail' question.id %}> <b>{{question.question_text}}</b> <img src="{{question.question_text.image.url}}"> </a> </li> {% endfor %} </ul> {% else %} <p> You have no questions. Please add some.</p> {% endif %} {% endblock %} but there seems to be no uploading of image which was what i wanted to add to poll app created from 'my first django app' videos on youtube. Please help. -
google cloud sotrage download file with encoded path included
I am using Google Cloud Storage API to manage my files. and when I download a file from link created. it downloads path together like this. movie%2F316029%2Fko%2FThe.Passion.Of.the.Christ.2004.DVDRip.XviD.AC3.CD2-CiPA.smi instend The.Passion.Of.the.Christ.2004.DVDRip.XviD.AC3.CD2-CiPA.smi is there have a way that fixes or turn off encoding path problem? I am using python3.5.2 Django 2.0 with Google Cloud Library. -
How to set User in request.user in Django
How i can set my own user in request.user or request.session.user my own models: class User(Document): id = fields.IntField(primary_key=True) username = fields.StringField(required=True) email = fields.EmailField() .... @property def is_authenticated(self): return False I set this in my view user = User.objects.get(email=email) request.session.user = user but didn't work. -
Is it ok to use the anaconda distribution for web development?
I started learning Python working on projects involving data and following tutorials advising to install the anaconda bundle, to take advantage of the other libraries coming with it. So did I and I got confortable with it, I liked the way it manages environments. During the last months, I have been teaching myself web development with django, flask, continuing to use the anaconda python. But most of the time I install the dependencies I need with pip install though (inside the conda environment). I've never seen any tutorials or podcasts mentioning the conda environment as an option for developing web apps so I start to get worried. Is it for a good reason? Everywhere its the combination of pip and virtualenv that prevail. And virtualenv isn't compatible with anaconda that has its own env management system. My newbie question is: Will I run into problems later (dependencies management in production or deployment maybe?) using the anaconda distribution to develop my web apps? -
Django Email Confirmation activation view not working
I am trying to set up an email confirmation for my django application. This is the activation URL: url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', activate, name='activate'), and this is the activate view: def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = get_user_model().objects.get(pk=uid) except (TypeError, ValueError, OverflowError, get_user_model().DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.email_confirmed = True user.save() login(request, user) return redirect('profile') else: return render(request, 'email/invalid_token.html') This is the error I am getting: TypeError at /activate/MzQ/4se-cb054dd0a60fb9f85110/ activate() got an unexpected keyword argument 'uidb64' Any help would be appreciated. -
How to re-sort search results in-place without having to re-send a request in django?
Here is the scenario: I have a search page, with some form elements providing multiple filter conditions (something like 'advanced search'), and probably a nested ListView to display the search results in-place. What I would like to achieve: Whenever the user changes some filter conditions, the result list below responds in-place (taking another request for this could be accepted); When the user changes the sorting option, the results change their ordering immediately, without sending another request, either synchronous or by ajax. From the server side it would be as simple as changing the order_by attribute of a QuerySet, but I would like it in a front-end way. So I wonder if it is possible to achieve that. It seems to me that the filtered QuerySet could be somehow kept at the client side. Is it possible by pure Django using some mechanism like session? Or will it have to take some front-end frameworks such as AngularJS or Vue.js? Or is it not even possible (If so, is there any approach taking the minimal extra network payload?) -
Why does Django server crash in PyCharm professional?
I am working in PyCharm professional version and I am not able to run Django server from PyCharm, though I can start it from cmd. After starting the server from cmd, everything works fine, I can reach my urls and get a response. When I am trying to do the same from Pycharm, first I get a windows error ("Python has stopped working. A problem caused the program to stop working correctly. Please close the program.) When I click "Close the program", it does not close, and I can see the following in error in PyCharm: Process finished with exit code -1073741819 (0xC0000005) I am using the following versions: Python version: 3.6.1 Django version: 1.9.13 I have already tried Tools | Run manage.py Task | runserver , which gives the same result. I have found a way to make this error disappear in PyCharm: When I go to Run | Edit Configurations | and check "No reload", then the server starts normally and I can access it through the browser. Does anyone have a hint on why this is happening? What is the purpose of "No reload"? Thank you for the answer! -
no changes detected when running makemigrations
After dropping every single relation in my database, and deleting everything inside workoutcal/migrations, I tried to run python manage.py makemigrations. This is what happened: (workout) Sahands-MBP:workout sahandzarrinkoub$ python manage.py makemigrations No changes detected How is this possible? The database is empty. There is nothing inside the migrations folder. Are there other things I should delete? -
Different behaviour of Django's django.utils.crypto.salted_hmac depending on uwsgi run manually or via service
Experiencing hard to understand for me behaviour. I feed salted_hmac function with predefined arguments - key_salt, value and without providing secret_key. When I run this via django command, I get some key inside salted_hmac function: key = hashlib.sha1(key_salt + secret).digest(). Same key I get, when running this from a django view run on runserver or from a the same django view while being run on uWSGI, which has been launched directly from terminal. On the other hand, when I run uWSGI via a service - the key in salted_hmac function differs. The only difference between those runs is a way it's run, I use exactly the same .ini file with uWSGI configuration. My guess would be that secret keys differ between running this function from terminal / from service, but when I print secret_key inside salted_hmac function - it's the same key... Moreover if I hardcode secret_key param when calling salted_hmac function - I get the same key generated in salted_hmac, regardless of it's run directly from terminal or from a view on uWSGI run from a service... -
after Model and many to many fields saved signal django
i have models like class Genre(models.Model): name = models.CharField(max_length=50) class Cast(models.Model): name = models.CharField(max_length=120, null=False, blank=False) class movie: name = models.CharField(max_length=120, null=False, blank=False) genre = models.ManyToManyField(Genre) cast = models.ManyToManyField(Cast, null=True, blank=True) i want to send notification to clients after a movie saved so i used post_save signal and because of my m2m relationships it didn't work and after that i used m2m_changed and now everytime i make a change on movie genres or movie cast they will be notified! i want them to be notified just for the first time the movie submits and i need the genres too! i mean the problem with the post_save signal was, it happens before genre and cast objects submit so i didn't have access to them -
Upload Percentage of AWS S3 file in django
I am uploading an whole folder using the following code: views.py: s3 = session.resource('s3') bucket = s3.Bucket('sudo-study-name') for subdir, dirs, files in os.walk(path): for file in files: full_path = os.path.join(subdir, file) with open(full_path, 'rb') as data: full_path = full_path.replace('\\','/') bucket.put_object(Key=full_path[len(path) + 1:], Body=data) print(full_path) Is it possible to know the amount of upload that has happened and show it in an progress bar on my html templates in Django project? Please note: This upload happens after a post. -
Django: Custom Metaclass Inheriting From And Extending `ModelBase`
I am trying to do some metaclass hocus-pocus. I want my own Metaclass to inherit from ModelBase and then I want to add additional logic by extending its __new__ method. However I think there is something strange happening with the MRO/inheritance order. Here is the basic situation: from django.db.models import Model, ModelBase class CustomMetaclass(ModelBase): def __new__(cls, name, bases, attrs): # As I am trying to extend `ModelBase`, I was expecting this # call to `super` to give me the return value from here: # https://github.com/django/django/blob/master/django/db/models/base.py#L300 # And that I would be able to access everyhing in `_meta` with # `clsobj._meta`. But actually this object is # `MyAbstractModel` and has no `_meta` property so I'm pretty # sure `__new__` isn't being called on `ModelBase` at all at # this point. clsobj = super().__new__(cls, name, bases, attrs) # Now, I want to have access to the _meta property setup by # ModelBase so I can dispatch on the data in there. For # example, let's do something with the field definitions. for field in clsobj._meta.get_fields(): do_stuff_with_fields() class MyAbstractModel(metaclass=CustomMetaclass): """This model is abstract because I only want the custom metaclass logic to apply to those models of my choosing and I don't want … -
Serve static HTML in Django
I’m pretty new to Django so forgive me if this is something I shouldn’t even consider, but I’d like my app to be able to link to a large number of static HTML pages (enough that creating URL paths to each one would be unreasonable) and there would constantly be more being uploaded (by me via FTP). I’ve got this working on the the development server by adding the path to those HTML files to my STATICFILES_DIRS [] but that doesn’t seem to work when I push my code to production. I tried setting up a STATIC_ROOT and running collectstatic but that didn’t help, and I’m also worried that even if I got that working, I would have to run collectstatic each time I uploaded new files. So my question is, is this even reasonable? Should I just avoid hosting these static HTML files alongside my project and leave them where they are now, on a separate server under a separate domain? The only reason I wanted to host them together initially is because along with the static HTML files, there is an SQL LITE database that my Django app displays data from (this is the whole purpose of my … -
You are trying to add a non-nullable field... when makemigrations
Here's what's happened: I created the following models: class Workout(models.Model): datetime = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.CASCADE) lifts = fields.LiftsField() cardio = JSONField() def __str__(self): return str(self.datetime)+" "+self.user.email __repr__ = __str__ class Activity(models.Model): name = models.CharField(max_length = 100) def __str__(self): return self.name __repr__ = __str__ class CardioActivity(Activity): pass class LiftActivity(Activity): pass I ran makemigrations and migrate workoutcal/migrations/0002_activity_cardioactivity_liftactivity_workout.py - Create model Activity - Create model Workout - Create model CardioActivity - Create model LiftActivity 0002_activity_cardioactivity_liftactivity_workout.py class Migration(migrations.Migration): dependencies = [ ('workoutcal', '0001_initial'), ] operations = [ migrations.CreateModel( name='Activity', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='Workout', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('datetime', models.DateTimeField()), ('lifts', workoutcal.fields.LiftsField()), ('cardio', django.contrib.postgres.fields.jsonb.JSONField()), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='CardioActivity', fields=[ ('activity_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='workoutcal.Activity')), ], bases=('workoutcal.activity',), ), migrations.CreateModel( name='LiftActivity', fields=[ ('activity_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='workoutcal.Activity')), ], bases=('workoutcal.activity',), ), ] Then I turned the Activity class into a meta class: class Activity(models.Model): name = models.CharField(max_length = 100) def __str__(self): return self.name __repr__ = __str__ class Meta: abstract = True And tried to makemigrations again: (workout) Sahands-MBP:workout sahandzarrinkoub$ python manage.py makemigrations You are trying to add a non-nullable field 'id' to cardioactivity without a default; we can't do … -
Django 1.11 static files not loading
<link href="{% static 'vendor/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css"> <link href= "{% static 'css/grayscale.min.css' %}" rel="stylesheet"> Setting.py STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(os.path.abspath(file)) STATIC_ROOT = os.path.join(PROJECT_DIR,'static') TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) There are static files in my directory, I have tried every possible solution. -
How to prevent abstract model class from being included in migrations
I've made two very simple models with the help of an abstract model: class Activity(models.Model): name = models.CharField(max_length = 100) def __str__(self): return self.name __repr__ = __str__ class CardioActivity(Activity): pass class LiftActivity(Activity): pass The Activity model is just an abstract model that is not intended to be used for anything, only to save me writing the same stuff twice. But when I makemigrations, it creates a database table for it: (workout) Sahands-MBP:workout sahandzarrinkoub$ python manage.py makemigrations Migrations for 'workoutcal': workoutcal/migrations/0002_activity_cardioactivity_liftactivity_workout.py - Create model Activity ### HERE - Create model Workout - Create model CardioActivity - Create model LiftActivity It seems suboptimal to create a table that is never going to be used by me. Is there a standard way of preventing this from happening? -
Will Firebase be a good database for a Django server to serve a Website and an Android application?
Not a lot is out there for integrating Firebase with a Django server. Will it be a good database to serve a Website and a mobile application? -
Custom Errors in Fields Django
i have a custom signup app from views: def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): userObj = form.cleaned_data username = userObj['username'] email = userObj['email'] password1 = userObj['password1'] password2 = userObj['password2'] if password1 != password2: return HttpResponse('password not match') elif User.objects.filter(email=email).exists(): return HttpResponse('email must be unique') elif User.objects.filter(username=username).exists(): return HttpResponse('username exists') else: user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activation' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Letter is sent') else: form = SignupForm() return render(request, 'signup.html', {'form': form}) This is the only way I made test for unique email working (models didn't work, dont know why). How can i make custom errors which i can put to my html using template tags {% if %}? Thanks! -
django image upload to path is not displaying
I have an application where I upload images and the images are uploaded to a specific directory but after uploading which works fine if I attenp to click on the image url I get an error which says The current URL, media/gallery/2017/12/28/230-256.png, didn't match any of these and also the image is not displaying in the browser html below is my model and view despite having my media path defined in the settings Models.py class Gallery(models.Model): name = models.CharField(max_length=400, db_index=True) image = models.ImageField(upload_to='gallery/%Y/%m/%d', blank=True) class Meta: ordering = ('name',) def __str__(self): return self.image.url Views.py def index(request): gallery = Gallery.objects.all() context = { 'gallery': gallery, } template = 'gallery.html' return render(request, template, context) html {% if gallery.image %} <div><a href="{{ gallery.image.url }}" title="{{gallery.name}}"><img src="{{ gallery.image.url }}"></a></div> {% endif %} -
handling contct form in django
I have an application whereby a user can contact me by filling out a form and in the form the user just has to fill in his details and his email and subject. the code throws no error but I could not receive the mail after setting up everything but the contact details gets stored in the database as I want it to be stored. below is my code. Models.py class Contact(models.Model): name = models.CharField(max_length=100) message = models.TextField() sender = models.EmailField() phone = models.CharField(max_length=10) cc_myself = models.BooleanField(blank=True) time = models.DateTimeField(auto_now_add=True, db_index=True) def __str__(self): return 'Message for {}'.format(self.sender) Forms.py class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['name', 'sender', 'phone', 'message', 'cc_myself'] Views.py def contact(request): if request.method == 'POST': contact_form = ContactForm(request.POST) if contact_form.is_valid(): name = contact_form.cleaned_data['name'] message = contact_form.cleaned_data['message'] sender = contact_form.cleaned_data['sender'] phone = contact_form.cleaned_data['phone'] cc_myself = contact_form.cleaned_data['cc_myself'] recipients = ['xxxx@gmail.com'] if cc_myself: recipients.append(sender) send_mail(name, message, sender, recipients) contact_form.save() messages.success(request, 'Message sent successfully') return redirect('contact:contact') else: messages.error(request, 'Error sending your Message') else: contact_form = ContactForm(request.POST) context = { "contact_form": contact_form, } template = 'contact.html' return render(request, template, context) gmail server EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'xxx@gmail.com' EMAIL_HOST_PASSWORD = 'xxxx' EMAIL_PORT = '587' EMAIL_USE_TLS = True -
Hi, I do not know how to pass url to ajax success. Help please
This my template fragment for comments/ {% for comment in comments %} <div class="comment-wrapper"> <a href="{% url 'comment:update_comment' slug=product.slug id=comment.id %}" class="comment-edit-img"> <img src="{% static 'media/work_images/icons-edit.png' %}" alt=""> </a> <a href="{% url 'comment:delete_comment' comment.pk %}" class="comment-del-img"> <img src="{% static 'media/work_images/icons-delete.png' %}" alt=""> </a> <p class="comment-text">{{comment.comment_text}}</p> {% if comment.update_date != comment.posted_date %} <span class="comment-author"> {% trans 'Posted' %}: {{comment.author}} </span> <span class="comment-date"> {% blocktrans trimmed with update=comment.update_date %} {{update}} {% endblocktrans %} </span> {% else %} <span class="comment-author"> {% trans 'Updated by' %}: {{comment.author}} </span> <span class="comment-date"> {% blocktrans trimmed with posted=comment.posted_date %} {{posted}} {% endblocktrans %} </span> {% endif %} </div> {% endfor %}enter code here My ajax code / $('#add-comment').click(function (e) { e.preventDefault(); var form = $('#add-comment-form'); $.post(form.attr('action'), form.serialize()).done(function(data) { $('#comment-box').prepend( "<div class='comment-wrapper'>"+ "<a href='???' class='comment-edit-img'>up</a>"+ "<a href='???' class='comment-del-img'>x</a>"+ "<p class='comment-text'>"+data.text+"</p>"+ "<span class='comment-author'>"+data.author+"</span>"+ "<span class='comment-date'>"+data.date+"</span>"+ "</div>" ); }) }); How can I pass the url of the address for tag the same as in the template? Or maybe there is a more correct solution to ajax? Thank you. -
Django rest framework reflect true REST API for function based view
I have three models: A 'User' will have a 'Wishlist' and a 'Wishlist' will have many 'Books'. To perform CRUD operations on Wishlist, I am writing my URLs and corresponding views. Right now I have one url: url(r'^wishlist/$', wishlist), and a function: # Get specific user's wishlist @api_view(['GET', 'POST', 'PUT', 'DELETE']) def wishlist(request): """ List all the books in wishlist of a specific user/Update/add/delete """ if request.method == 'GET': books = Book.objects.filter(wishlist__user=request.user) serializer = BookSerializer(books, many=True) return Response(serializer.data) elif request.method == 'POST': ... elif request.method == 'PUT': ... elif request.method == 'DELETE': ... My question is- having such one function with one url and all four methods is a correct way to build true REST API, or should I separate them? Considering for example, for PUT and DELETE methods, I perhaps also could send wishlist_id in the url and handle accordingly. In current code snippet, I will have to filter against request.user -
How to apply contains to list?
I want to search for filtered objects. Below is the filtered object. questions = models.Question.objects.filter(creator=user, tags__name__in=hashtags) and I tried the following command. But it does not work. questions = models.Question.objects.filter(tags__name__contains=hashtags) I think, __contains does not seem to work on the list p.s. hashtags is a list -
Mail traffic between MailDev container and Django container delivers Errno 111] Connection refused
Mail traffic between MailDev container and Django container delivers [Errno 111] Connection refused Email traffic to console backend works, so the function should be correct. send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False ) After I switched to SMTP backend and started MailDev in Container, I got: [Errno 111] Connection refused in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' in Shell: sudo docker run -p 1080:80 -p 1025:25 --name maildev djfarrelly/maildev My Docker Containers are: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a46040dd1259 djfarrelly/maildev "bin/maildev --web..." 11 seconds ago Up 9 seconds 0.0.0.0:1025->25/tcp, 0.0.0.0:1080->80/tcp maildev 4fed036f92d4 exposee "/usr/src/start.sh" 42 minutes ago Up 42 minutes 0.0.0.0:8000->8000/tcp exposee 2c2cf7ce19e9 winauth "gunicorn -b 0.0.0..." 43 minutes ago Up 43 minutes 127.0.0.1:9876->9876/tcp winauth afe4a449aa01 postgres "docker-entrypoint..." 44 minutes ago Up 44 minutes 127.0.0.1:5432->5432/tcp postgres My Settings in settings.py are: EMAIL_HOST = CONFIG.get('EMAIL_HOST', '127.0.0.1') EMAIL_PORT = CONFIG.get('EMAIL_PORT', 1025) EMAIL_USE_TLS = CONFIG.get('EMAIL_USE_TLS', False) EMAIL_USE_SSL = CONFIG.get('EMAIL_USE_SSL', False) My Conigurations in config.json are: "EMAIL_HOST": "127.0.0.1", "EMAIL_PORT": 1025, "EMAIL_USE_TLS": false, "EMAIL_USE_SSL": false