Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the currently logged in user (from auth) and display his name on the post
How can I get the Username and save it to auhtor model in discussion and then display it in template. i tried a few things but it doesn't work. Any help is appreciated. thanks models class Discussion(models.Model): author=models.CharField(max_length=15,null=True) title=models.CharField(max_length=50) argument=models.CharField(max_length=350) slug=models.SlugField(max_length=31,unique=True) created_on=models.DateField(auto_now=True) def get_absolute_url(self): return reverse('discussion_detail',kwargs={'slug':self.slug}) def __str__(self): return self.title Form class DiscussionForm(forms.ModelForm): class Meta: model=Discussion fields=['title','argument','slug'] Views: class NewDiscussionView(LoginRequiredMixin,View): template_name='Discussion/new_discussion.html' form_class= DiscussionForm def get(self,request): return render(request,self.template_name,{'form': self.form_class()}) def post(self,request): bound_form = self.form_class(request.POST,instance=request.user) if bound_form.is_valid(): new_discussion=bound_form.save() return render(request,'Discussion/discussion.html',{'discussion':Discussion.objects.all()}) else: return render(request,self.template_name,{'form': bound_form}) -
How to look up with foreing keys?
I'm starting with Django and I want to get the movies that have a better rating score and I don't know how to find a way using my model state. Now there are my classes: class Movie(models.Model): movieId = models.IntegerField(unique=True) title = models.TextField(max_length=100) anno = models.IntegerField() imdbId = models.IntegerField(unique=True) tmdbId = models.IntegerField(unique=True) def __str__(self): return self.title class Rating(models.Model): rating = models.IntegerField() timestamp = models.IntegerField() user = models.ForeignKey(User, on_delete = models.CASCADE) movie = models.ForeignKey(Movie, on_delete = models.CASCADE) def __str__(self): return str(self.user)+"--"+str(self.rating) -
Building my django project with Centos7 + virtualenv + apache2
It goes nothing wrong when I run ./manage.py runserver 0.0.0.0:8000. But I came across weird errors when launching them with virtualenv and apache2. And there seems to be nothing wrong in the error_log. enter image description here It has confused me for a long time. I would be highly appreciated if I can get your help! -
I have an "empty path didn't match any of these" error after apllying the django toturial, is the problem in my computer siitting
I have an "empty path didn't match any of these" error after apllying the django toturial , is the problem in my computer siitting ? page not found mysit urls polls urls views sitting -
How to write view to update model image in django?
Now I extends the django User model with profile model. I want add update user's profile function. Because I make the num field as the unique field, So in my update view function, the update form's is_valid was always False, and I also cannot update the photo png? Those are my codes. What should I do to solve this problem? Models: class Profile(models.model): user = models.OneToOneField(User,on_delete=models.CASCADE) num =models.CharField('identity',max_length=254,unique=True) photo = models.ImageField('image',upload_to = 'images/licences') forms: class ProfileForm(forms.ModelForm): class Meta: model= Profile fields = ['num','photo'] views: def modify_view(request): user = request.user if request.method=="POST": form = ProfileForm(request.POST,request.files) if form.is_valid() user_profile = Profile.objects.get(user=user) user_profile.image = form.clean_data['image'] user_profile.save() else: form = ProfileForm() return render(request,"profile.html",{form:form}) -
Emulate file upload from a form from code
This is probably trivial but I am unable to find a solution. Here are my models.py and forms.py models.py class FileModel(models.Model): file = models.FileField(blank=False, upload_to='/xyz/') forms.py class FileModelForm(forms.ModelForm): class Meta: model = FileModel Now I want to create an instance of this model (using the form) from the shell. Assume my file is currently located in media/test_files/x.txt These are the things that I have already tried : ins = FileModelForm(data={'file':'/test_files/x.txt'}) ins = FileModelForm(data={'file':'/media/test_files/x.txt'} ins = FileModelForm(data={'file':os.path.join(settigs.MEDIA_ROOT,'test_files/x.txt') f = open(os.path.join(settings.MEDIA_ROOT, 'test_files','x.txt') ins = FileModelForm(data={'file':f} In all these above cases, ins.is_valid() returns False How do I do this? -
How to add if function in django html template
I want to add one if function in html template of my django project. If the variables datas is null, it will show the text "The results is null", if the variables datas is not empty, it will show the table for the data in datas. Here's what I write, but it keeps show that "Invalid block tag on line 13: 'if(isEmpty($('#datas')))', expected 'endblock'. Did you forget to register or load this tag?" How could I deal with it? {% if(isEmpty($('#datas'))) %} <h3>The results is null.</h3> {% else %} <table style="table-layout:fixed;"> <tr>...</tr> <tr> {% for i in datas %} <td>{{ i.1 }}</td> </tr> {% endfor %} </table> {% endif %} -
Django: When to use UUID?
I know this question is the one someone already asked but I really don't understand when I should use UUID. I just started to try to bulid REST API in Django. And I've read we should use UUID but I don't understand how to use it. For example, I currently use id to refer to a specific object in api views as I write in usual views.py. Is it what I should not do? If so, how users can refer to a object using UUID? When is it used? @api_view(['GET', 'PUT', 'DELETE']) def specific_entry(request, pk, format=None): entry = get_object_or_404(Entry, id=pk) ... -
restframework-jwt not working with manual model class
I have only beginner level idea about django restframework-jwt. When i try to authenticate with my custom model class it showing "non_field_errors": [ "Unable to log in with provided credentials." ] But I can generate token with "auth_user" table data model.py contain users class & user_manager settings.py INSTALLED_APPS = [ 'rest_framework', 'rest_framework_jwt', 'rest_framework.authtoken', ] AUTH_USER_MODEL = '**app_name**.Users' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } JWT_AUTH = { 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3000), 'JWT_AUTH_HEADER_PREFIX': 'Bearer', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', } -
Can't connect to localhost using mysql
I am new to Django and mysql and I am trying to configure my django application's backend to mysql. I am using XAMPP for my local mysql database and anaconda as my pkg manager. Also using a conda virtualenv. When I go to run python3 manage.py migrate, I get this error: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (61)") My database is setup as the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'exampleproject', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '', } } I changed 'HOST' to 'localhost' but then get this error: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)") Any help is appreciated! -
Why doesn't jinja re-render my template after a successful Ajax POST operation
I am told that the success of AJAX function is responsible for doing everything after sending the data, including updating the page to show any data sent by the backend in response to the post. When I printed the success: function(res){ console.log(res) } I am able to see my newly generated HTML in the console log where the HTML DIV is populated where I had the Jinja FOR loop. <div id="RIGHTCONTAINER" class="list-group" style="height:625px; overflow-y: scroll"> {% for model in model_list %} <a href="#" data-set="{{ model_list|length }}" class="list-group-item py-0 list-group-item-action">{{ model }}</a> {% endfor %} </div> I am surprised that console.log is able to see the returned data, render generated html, but it is now up to me somehow to display that in the browser if when I am using ajax. I was however able to print my content using ajax BELOW METHOD but this is NOT not ideal for me, (because I have additional functions I need to call for operations upon list-group-items inside my RIGHTCONTAINER, which will become multiple nested ajax requests inside my ajax success function, and I found myself worked into a corner). $.ajax({ type:'POST', url:"home/view_results/onclick/", data:{ selected_item:item_index, // Sending users selection csrfmiddlewaretoken:"{{ csrf_token }}" }, dataType:"text … -
Java ZonedDateTime.toInstance() behavior
I'm seeing a discrepancy whereby this: ZonedDateTime.now(ZoneId.of("America/New_York")).minusDays(30) returns (correctly): 2018-11-07T22:44:11.242576-05:00[America/New_York] whereas conversion to an instant: ZonedDateTime.now(ZoneId.of("America/New_York")).minusDays(30).toInstant() seems to mess up the result by adding an extra day to it: 2018-11-08T03:58:01.724728Z I need an instant conversion to use the result in the following code as Date: Date.from(t.toInstant()) An equivalent Python code (Django) works correctly: datetime.datetime.now(TZ)+datetime.timedelta(days=-num_days) evaluating to: datetime: 2018-11-07 20:13:55.063888-05:00 -
Django: Video can play in Chrome, but not Safari
I have an issue about Video in Django. This is my URL: https://api.feedtrue.com/vd/39/21_39_37957721_276811923114866_7425040007062093824_n.mp4 When I open this URL by Google Chrome browser, it works normally, but when I use Safari browse, this video doesn't load and I don't know the reason. This is the screen of Safari browser, which doesn't load this video. I read about byte-range and apply this package: Django Ranged Response but it doesn't work too. Please give me advice about this issue. Thanks in advance! -
Django: Check if a foreign key field has been loaded
I have two django models class ValidName: name = models.TextField() class MetaSyntacticName(ValidNames): name = models.ForeignKey(ValidName) usages = models.IntegerField() If I have an instance of MetaSyntacticName, can I find out if the ValidName instance it's name references has been loaded from the database without a database query? -
Django Tutorial: 'detail' is not a valid view function or pattern name
I am using Windows XP, Python 3.4 and Django 2.0.2 I am new to Django and am trying to follow the instructions in https://docs.djangoproject.com/en/2.0/intro/tutorial04/ the Django tutorial. The most likely mistake that I made is that I did not cut and paste code in the right places. It would be helpful to me (and possibly others) if the writers of the tutorial had a reference to the complete list of the py and html files at each stage (not just part of the code). I have the following error: http://127.0.0.1:8000/polls/ ` NoReverseMatch at /polls/ Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Django Version: 2.0.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. Exception Location: C:\programs\python34\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 632 Python Executable: C:\programs\python34\python.exe Python Version: 3.4.3 Python Path: ['Y:\mysite\mysite', 'C:\WINDOWS\system32\python34.zip', 'C:\programs\python34\DLLs', 'C:\programs\python34\lib', 'C:\programs\python34', 'C:\programs\python34\lib\site-packages'] Server time: Thu, 6 Dec 2018 15:35:56 -0600 Error during template rendering In template Y:\mysite\mysite\polls\templates\polls\index.html, error at line 4 Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. 1 {% if latest_question_list %} 2 <ul> … -
Django: Combine two Field Inputs to Generate URL to navgate to another Django Template
In my Django project there is an index model which renders an index.html view, in which I have a form: <input type="text" list="option"> <label >Type or Select Query</label> <datalist id="option"> <option value= "Option 1"> <option value= "Options 2"> </datalist> <div class="input-field"> <select> <option value="view_function1">Text 1</option> <option value="view_function2">Text 2</option> </select> </div> What I want to do is take the text input / option selection in the text field and merge it with the option selected in the drop down field to form something like this: /view_fucntion2/Option 1 or /view_function1/query These urls would serve the various models in a template defined in views.py. The query + drop down merge will execute on a button submit. I understand I may be able to achieve this with Jquery, but my grasp of that is limited. What should I do? -
How does django UpdateView find a html form? (name convention)
I am following a django tutorial and everything is working, but I don't understand how this class, in views.py, find the album_form.html if I didn't pass any parameters of the path/name. class AlbumCreate(CreateView): model = Album fields = ['artist' , 'album_title' , 'genre' , 'album_logo'] The html name is album_form.html and works fine, but if I change to somethingelse_form.html it doesn't work anymore. From where django identifies that it have to use 'album' instead of 'somethingelse'? What is the name convention? Its not from urls.py, because mine is this: url(r'album/add/$', views.AlbumCreate.as_view(), name='album-add') -
How to transfrom static path to web url in Django?
I think my problem is more or less a simple question, but I'm not still accustomed to using webpack and so on, So your advice will be helpful to me. (I'm using Django on backend and React on frontend) Hierarchy of folder Cebula4 - back - settings.py - manage.py - front - static - bundles - MainPage.js (webpacked) Settings.py ... STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static'), ] STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles') ... Static URL : C:\Users\1Sun\Cebula4\front\static\bundles\MainPage.js How I can transform this Static URL to local web_url like http://127.0.0.1:8000/static/bundles...? -
Django Unit Testing in Visual Studio 2017 or 2019:
Django needs setup code so unit tests on models that need a database will work. Standard Django unit test do that silently in the background but not with Visual Studio. I have not found a good way to provide setup code that will work for starting test runs from both the Visual Studio Test Explorer and with django manage.py test. Visual Studio Test Explorer does not call setUpModule/tearDownModule nor tearDownClass. The following code works from within VS, but I find it ugly, AND it doesn't work with nose/django-nose: import os import django import unittest from django.test.utils import setup_test_environment, teardown_test_environment from django.test.utils import setup_databases, teardown_databases try: os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.test" setup_test_environment() print("Called setup_test_environment()") django.setup() old_config=setup_databases(1,False) except: old_config=None def tearDownModule(): try: global old_config if old_config: teardown_test_environment() print("Called teardown_test_environment()") teardown_databases(old_config,1,False) except: pass from unittest import TestCase # This needs to be called after django.setup from konsenser.models import Poll class PollTest(TestCase): @classmethod def setUpClass(cls): print("Setting up class") return super().setUpClass() @classmethod def tearDownClass(cls): print("Tearing down class") return super().setUpClass() def setUp(self): Poll.objects.create(name='Test Poll', description='for testing') def test_content(self): poll=Poll.objects.get(id=1) name=f'{poll.name}' description=f'{poll.description}' self.assertDictEqual({'name':name,'description':description }, {'name':'Test Poll','description':'for testing'}) if __name__ == '__main__': unittest.main() When run by VS Test Explorer, the output is Called setup_test_environment() Creating test database for alias 'default'... … -
how to publish HIT on external http website using mturk?
Actually I create a website using Django in python3.7 and publish my HITs on that website. Now I am trying to publish those HITs to the crowd using mturk. I found some documents, but it seems that the ExternalQuestion of mturk only support the https website. (while my website is http) I am sure there are some solutions, but I need more time to find out them..Dose anybody has any ideas about how to publish HITs on http website with mturk? Any idea will be much appreciated! -
django not starting server
hai i am new to django when i start my project it returns me a error Traceback (most recent call last): File "/home/kid/PycharmProjects/test/myproject/manage.py", line 8, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/kid/PycharmProjects/test/myproject/manage.py", line 14, in ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
Problems with redirect URI on production domain (django allauth)
I got stacked with django allauth redirect callback (I am begginer in web development and faced troubles with first deployment in production). Long story short: I use django allauth for loggining on the web site through social network instead of regular process of signing up. While development everything was good, I configured social application in vk.com and configured Social Application in django admin. Redirect URI looks like: http://127.0.0.1:8000/accounts/vk/login/callback/ and in development (when server was running on 127.0.0.1:8000) everything was ok and authentication was successful. However, after deploying django server on VPS hosting I faced problems. I associated domain with hosting ip: django server is running on http://188.158.73.151:9000 but is accessible both https://example.com and http://184.154.83.121:9000. But, authentication is successful only from ip:port (http://184.154.83.121:9000) and fails if I try the same from https://example.com (raise error: Social Network Login Failure An error occurred while attempting to login via your social network account.) I noticed that redirect URI for both cases are http://184.154.83.121:9000/accounts/vk/login/callback/ and if I manually change it to https://example.com/accounts/vk/login/callback/ authentication will be successful. However, I don't have any idea how to handle it. What should I do to get redirect with my production domain? Please help, I scrutinized dozens of google pages … -
One to Many options doesn't appear in Model Form Django
I am very new to Django and struggling to figure wrong what am I missing in Django Model Form. I want to display a drop-down with predefined values in the form but for some reason, the options never appear. Following is the code from models.py LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) class Status (models.Model): class Meta: db_table = 'Status' status = models.CharField( max_length=1, choices=LOAN_STATUS, blank=True, default='m', ) class Property(models.Model): def __str__(self): return self.propertyTitle propertyID = models.AutoField(primary_key=True) status = models.ForeignKey(Status, on_delete=models.SET_NULL, null=True)` Following is the code from ModelForm class CreateAdvertisementForm(ModelForm): class Meta: model = Property exclude = ['propertyID'] Following is the code from my Template {% block body %} <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form>{% endblock %} Please help me understand what is going wrong. -
How do I send email, to my user's email? (Help Django)
How do I send email to my user's email? Hi, I want to send email to my user, using his email, informing that the user has been updated, I tried something like this in the forms: forms.py @transaction.atomic def update_student(request): try: student = request.user.student except Student.DoesNotExist: student = Student(user=request.user) if request.method == 'POST': form = StudentUpdateForm(request.POST, instance=student) if form.is_valid(): form.save subject = 'Usuario atualizado' from_email = settings.EMAIL_HOST_USER to_email = [student.email] update_message = 'Usuario ativado com sucesso' send_mail(subject,from_email=from_email,recipient_list=to_email,message=update_message,fail_silently=False) return redirect('student_list') else: form = StudentUpdateForm(instance=student) return render('student_list') No problem, but the email is not sent, so I used send_email in students / views.py and the email was sent correctly, however with emails in a 'static' way in the fields "from" and "to" students/views.py class StudentUpdate(UpdateView): model = Usuario form_class = StudentUpdateForm context_object_name = 'student_update' template_name = 'students/student_update.html' success_url = reverse_lazy('student_list') send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) How to use the user's email instead of stating "static" emails using strings? -
how to get celerybeat cron tasks to run in docker container for django app?
I'm trying to run celery beat tasks in my django/nuxt app I have separate frontend and back end directories and I'm using docker-compose to build and run my app. (pycharm professional-mac-oS seria I can run my tasks perfect without using docker containers locally but when I try to containerize to run, both celery and celery-beat wont stay running. I find the documentation is very poor online and even on celery's or dockers official documentation there's no mention of running celery & beat with docker Can anyone tell me if my configuration is wrong or what I need to do in order for my app to accept the cronjobs in my settings.py? I build my containers with docker-compose up-d and run my app with docker-compose exec django bash Can anyone point me in the right direction? settings.py import os from configurations import Configuration, values from datetime import timedelta #print(os.environ) class Base(Configuration): DEBUG = values.BooleanValue(False) SECRET_KEY = '2pj=b#ywty7ojkv_gd#!$!vzywakop1azlxiqxrl^r50i(nf-^' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATABASES = values.DatabaseURLValue() ALLOWED_HOSTS = [] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "rest_framework.authtoken", "django_celery_results" , "django_celery_beat" , "corsheaders", "djoser", "accounts", "posts", "comments", "events", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF …