Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django ManyToMany field - access fields of through table
Say I have the following model: class User(Model): username = CharField(...) class Project(Model): project_name = CharField(...) workers = ManyToManyField(User, through="ProjectAssignment") class ProjectAssignment(Model): user = ForeignKey(User) project = ForeignKey(Project) role = CharField(...) # name of the role a user has on a project How a query that gets the users who have role Developer on a project named XY looks like? I could not find an example in Django documentation. -
Django rest view retrieve chained objects
I have models with following relationships: A 'User' can have a 'Wishlist' and a 'Wishlist' will have many 'Book's. I want to retrieve all the books in a specific user's wishlist. I am writing my view like following: # Get specific user's wishlist @api_view(['GET', 'POST', 'PUT', 'DELETE']) def wishlist(request): """ List all the boosk in wishlist of a specific user """ if request.method == 'GET': books = Wishlist.objects.filter(request.user) serializer = BookSerializer(books, many=True) return Response(serializer.data) How can I write logic inside my filter? Or could there be a better approach (e.g. not serializing books instead wishlist)? -
django charge users based on how many counties they want to access
I'm building a web app, basically I currently have 3 models , 1- State: which represents all US states 2- County: which represents all counties with foreign key of state 3- Home: which represents all homes with foreign key of County the app will show homes, but users needs to subscribe for certain counties (the counties prices can vary) the goal is : when users subscribe to certain counties they can see the related "Homes" to these counties I'm not sure how should I represent these relations between users, subscriptions and how to connect it to County model I have. and how to make a view for the user to add new counties. Thank you. -
Why a for cycle in a django template add space at the end of my elements? (taggit)
My template.html: {% for x in post.tags.all %} <a href="{% url 'blog:post_list_by_tag' x.slug %}"> {{ x.name }} </a> {% if not forloop.last %}, {% endif %} {% endfor %} I haven't space at the end of the lines and I haven't space in the name (in database) but the output is: tag1 , tag2 , tag3 with a space between name and comma and a space at the end. Even with one tag there's a space at the end. I use taggit, maybe the problem is there. Also the links underline even the white spaces when after there's the comma (so not at the end). If I write {{ x.name }}</a> the spaces are there but the links underline only the tags, not the spaces. In myview print(post.tags) => AttributeError: '_TaggableManager' object has no attribute 'name' print(post.tags.all) => <bound method BaseManager.all of <taggit.managers._TaggableManager object at 0x03EFEA70>> -
Model formset with abstract model and foreign key
Is it possible to create a formset with two models, one of which is abstract? A simplified case of what I have is: #models.py class ProductRelationship(models.Model): ... product = models.ForeignKey('Product',verbose_name="Product") Status= models.CharField() class Meta: abstract=true class Product(models.Model): ... #forms.py ProductRelationshipFormSet = inlineformset_factory( models.Product, models.ProductRelationship, fk_name='product', fields=('Status','product',)) However this returns ValueError: fk_name 'product' is not a ForeignKey to 'rdb_valet.Product'. If I use the child models, it works without any issue. Currently my workaround is therefore to just redefine the formset for each child class, but I want to know if it's possible to do it using the abstract parent class. Thanks! -
Database driven framework with dashboard
Do you know some good alternative to KeystoneJS and Django ? I'm developing app based on KeystoneJS, but keystone has much limitations, I can't overwrite look of dashboard, I can't create custom role. I can't create nested schema of UI. I made research and I can't find framework which follows my requirements. -
Django - parse object from fk
I have a model called Friendship: class FriendShip(models.Model): from_friend = models.ForeignKey(User, on_delete=models.CASCADE, related_name='friend_set') to_friend = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_friend_set') def another_person(self, this): if self.from_friend == this: return self.to_friend elif self.to_friend == this: return self.from_friend else: return None also in my user model, I about to create a friend list: def __str__(self): if self.anonymous: return "anonymous user" else: return self.username def get_friend_list(self): friend_list = [] for friendship in FriendShip.objects.all(): friend_list.append(friendship.another_person(self)) return friend_list I print the list out and get the result : How can I get the object but not the key? (the str in my User model only returns username)