Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to query database after the server has started?
I am trying to Query my database after the server has started, all of the tutorials on youtube write the code inside the server and run it. I don't want this, on the official tutorial they execute the commands inside a shell. How do I do the same? -
Converting to different timezones
I want to show the user Datetime based on their timezone, I want to post the timezone selected by the user and get the converted times, I have multiple Datetime objects, so need to convert them all. for example I have this date in UTC 2018-08-24 18:00:00+00:00 and I have a function that converts it to the user timezone, how can we go about running that method and returning the serialized data back to the user, class TimeSlots(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) time_slots = models.DateTimeField() #utc time here class SlotsSerializer(serializers.ModelSerializer): class Meta: model = TimeSlots fields = '__all__' -
Forbidden You don't have permission to access / on this server. on Django, Apache, Centos7
I'm using Centos 7. I create a django project under /home/WEFORUM/admshapersdev/stargate/ and create a wsgi file in /home/WEFORUM/admshapersdev/stargate/stargate The Django.conf Alias /static /home/WEFORUM/admshapersdev/stargate/landingpage/static <Directory /home/WEFORUM/admshapersdev/stargate/landingpage/static> Require all granted </Directory> <Directory /home/WEFORUM/admshapersdev/stargate/stargate> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess stargate python-path=/home/WEFORUM/admshapersdev/stargate:/home/WEFORUM/admshapersdev/stargate/stargateenv/lib/python3.6/site-packages WSGIProcessGroup stargate WSGIScriptAlias / /home/WEFORUM/admshapersdev/stargate/stargate/wsgi.py The structure and rights of the project folder: drwxr-xr-x. 6 admshapersdev apache 4096 Aug 17 22:47 landingpage/ -rwxr-xr-x. 1 admshapersdev apache 806 Aug 17 21:42 manage.py* -rw-r--r--. 1 admshapersdev apache 464 Aug 17 22:42 requirements.txt drwxr-xr-x. 4 admshapersdev apache 4096 Aug 18 01:08 stargate/ drwxr-xr-x. 5 admshapersdev apache 77 Aug 17 21:41 stargateenv/ drwxr-xr-x. 2 admshapersdev apache 6 Aug 17 21:52 static/ But each time I try to reach my page, I am having this error in apache log: [core:error] [pid 22477] (13)Permission denied: [client 192.168.140.179:63696] AH00035: access to /favicon.ico denied (filesystem path '/home/WEFORUM/admshapersdev/stargate') because search permissions are missing on a component of the path, referer: http://stargate0.weforum.local/admin Does anyone know how to handle this? thank you! -
Multiple Django FusionCharts on same page
I am trying to do the same as in this post Multiple FusionCharts on Same page with Django and as far as I can see I am using the same approach as in the answer but it is not working. I have also tried putting the charts in a table as in the answer but only get chart1 again. I also can't get chart2 or chart3 to appear on it's own, or get multiple copies of chart1 to appear. The code posted below gives chart1 but blank spaces (reserved space but no chart) for chart2 and chart3. Using Django 2.0.4, Python 3.6.3, SQLite built in to Django and the Django dev server. If anyone can spot what I am doing wrong I'd be very grateful. views.py (extract) def charts(request): '''Various Temperature Charts''' #### TEMPERATURES TODAY CHART ##### CHART1 # DATA SERIES lastdayevent = Event.objects.filter(reading='AMB', location = 'Hall').order_by('-date')[0] # get event from latest day querydate = lastdayevent.date # Use last day with data rather than today. Allows testing with old database files. qsH= Event.objects.filter( reading ='AMB', location = 'Hall', date = querydate).order_by('-time') qsM= Event.objects.filter( reading ='AMB', location = 'Bed_Mstr',date = querydate).order_by('-time') qsE= Event.objects.filter( reading ='EXT_TEMP', location = 'Bed_Mstr',date = querydate).order_by('-time') datalist_hall β¦ -
Django filter find the smallest number group by other column
I have a database structure like as below: id listing sequence 1 1 0 2 1 1 3 1 2 4 2 1 5 3 1 6 3 2 7 4 0 8 4 1 I want to get each group of listing whose sequence is the smallest, the example result is as below: {listing:1, sequence:0}, {listing:2, sequence:1}, {listing:3, sequence:1}, {listing:4, sequence:0} PS: some sequence is start from 0, some is start from 1, or even more. -
How to merge same code block in Django?
I have the same code block in 4 of my functions,is any way I can merge the same code block? Here is the same code block: def function_name(): ...some code... hot_news_48h = h_mostViewed(48, News, '-pv') hot_news_1w = w_mostViewed(1, News, '-pv') ...some code... return render(request, "template_name.html", { ...some code... 'hot_news_48h': hot_news_48h, 'hot_news_1w': hot_news_1w, ...some code... }) Here is function1: def newsDetailView(request, news_pk): news = get_object_or_404(News, id=news_pk) tags = news.tag.annotate(news_count=Count('news')) News.objects.filter(id=news_pk).update(pv=F('pv') + 1) hot_news_48h = h_mostViewed(48, News, '-pv') hot_news_1w = w_mostViewed(1, News, '-pv') relative_news = News.objects.filter(tag__id__in=news.tag.all()).exclude(id=news_pk)[:6] return render(request, "news_detail.html", { 'news': news, 'tags': tags, 'hot_news_48h': hot_news_48h, 'hot_news_1w': hot_news_1w, 'relative_news': relative_news }) Here is function2: def tagNewsList(request, tag_pk): tag = get_object_or_404(Tag, pk=tag_pk) news_list = News.objects.filter(tag=tag) hot_news_48h = h_mostViewed(48, News, '-pv') hot_news_1w = w_mostViewed(1, News, '-pv') return render(request, "tags_list.html", { 'news_list': news_list, 'tag': tag, 'hot_news_48h': hot_news_48h, 'hot_news_1w': hot_news_1w, }) Any friend know how to merge them?Thanks so much! -
Serializing single instance in Django
I have a simple "Driver" Django model with fields "id", "phone", and "address". I added a serializer and a request handler to return the last driver from the database as shown below. The serializer returns empty data when i pass a single instance driver object. However, it returns the last driver as a list if i pass the same object as a list and set many = True. Any ideas how can i get the serializer working with instance parameter instead of wrapping it in a list? def get_last_driver(request): last_driver_object = Driver.objects.last() # This always returns empty data last_driver_data = DriverSerializer(last_driver_object).data # This returns serialized list containing one object last_driver_data = DriverSerializer([last_driver_object], many=True).data class DriverSerializer(serializers.ModelSerializer): class Meta: model = Driver fields = ("id", "phone", "address") return JsonResponse({"last_driver": last_driver_data}) -
Errors when I try to migrate in Django2
I have a problem (at least I think). I am new in all this, so I apologize If I ask something stupid. I have some site, which is working normally. When I try to make migrations ( python manage.py makemigrations), everything passed ok, I got the message of how many models new I have, etc. But, when I run after that migrate, I got the following output: Operations to perform: Apply all migrations: admin, auth, comments, contenttypes, news, sessions Running migrations: Applying comments.0003_auto_20180816_2158...Traceback (most recent call last): File "../venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File ".../venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File ".../venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File ".../venv/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File ".../venv/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File ".../venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File ".../venv/lib/python3.6/site- packages/django/core/management/commands/migrate.py", line 203, in handle fake_initial=fake_initial, File ".../venv/lib/python3.6/site- packages/django/db/backends/base/schema.py", line 531, in _alter_field fk_names = self._constraint_names(model, [old_field.column], foreign_key=True) File ".../venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line β¦ -
can't connect to database through django
I'm trying to connect to a database on another server in my django app, but I'm getting the error (in my apache error log): django.db.utils.OperationalError: could not create SSL context: library has no ciphers I can use manage.py shell and connect to this database: >>> import psycopg2 >>> conn = psycopg2.connect("dbname=mobilesurvey user=django password=xxx host=dugong-api-rmove.rsginc.com port=5432") What can I do to get this working through django? -
Getting the Value from ExtractQuarter
I have a django model. When the form to populate this model is completed, I want my save function to use the new ExtractQuarter database function on one of the fields input by the user. Based on the value produced by ExtractQuarter, I want to populate another field which is hidden from the form's user. However, I cannot figure out how to actually get the value from ExtractQuarter. The save function is: def save(self, *args, **kwargs): q = ExtractQuarter(self.fiscal_year_end).values.get() if q >= 3: y = ExtractYear(self.fiscal_year_end).Value() else: y = ExtractYear(self.fiscal_year_end).Value()-1 self.fiscal_year = y super(ModelName, self).save(*args, **kwargs) This gives me: TypeError: '>=' not supported between instances of 'ExtractQuarter' and 'int' Thanks for the help. -
How to configure django-haystack to work with dynamically created Solr cores?
We configure django-haystack to work with Solr and one predefined core, just like in official documentation. And it's work just fine. But now due to the huge amount of data we create one Solr core per month. The problem is that every core has a unique name. So we need to set every new core in django settings and it's not an option for the prod. Can any one help: How to set django haystack to work with dynamically created Solr cores, without changing djnago settings? (Django 1.11 / Solr 5.5 / django-haystack 2.8.1) -
How to use AWS S3 to serve my media file?
I am using Django on Amazon EC2 free tier instance. When a user uploads an image in my application it saves in EC2 but I want to save it in S3 bucket. What steps should I take? -
Django model_set for a list of elements
I have the following code: class Skill(models.Model): name = models.CharField(max_length=60) class Competency(models.Model): skill = models.ForeignKey(Skill, null=True, on_delete=CASCADE) class Employee(AbstractUser): competencies = models.ManyToManyField(Competency, blank=True, related_name='employees') From a specific skill I would like to get a queryset of employees that have competencies with that skill. From that skill I was able to get a list of related competencies with: competencies = skill.competency_set.all() How can I do the same to create a queryset of employees given that "competencies" contains many elements? -
My AbstractBaseUser changes 'email' to username in admin panel when i update any field
I have a problem with my User Model. The deal is that when I update any field or fields in the admin panel, my email field gets the same data as at the username field. I have no idea how to solve this problem. So, I really rely on your help. Here are all my files that may be important: models.py class User(AbstractBaseUser): email = models.EmailField( verbose_name = 'email address', max_length=255, unique=True ) real_name = models.CharField(max_length=20, blank=True) username = models.CharField(max_length=40, unique=True, verbose_name='username') active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) grade = models.ForeignKey(GradeUser, on_delete=models.CASCADE, blank=True, null=True) country = models.ForeignKey(Country, on_delete=models.CASCADE, blank=True, null=True) reputation = models.IntegerField(default=0) image = models.ImageField(upload_to='accounts/media', blank=True) about_me = models.TextField(blank=True) USERNAME_FIELD= 'email' REQUIRED_FIELDS = ['username'] my forms.py class UserAdminCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('email', 'username') def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): user = super(UserAdminCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) user.active = False if commit: user.save() return user class UserAdminChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = User fields = ('email', 'username', 'password', 'active', 'admin') def clean_password(self): return self.initial["password"] -
Django, url and forms: what is the point in sending parameters in url?
A question I have been asking myself for a long time: what is the advantage to send parameters in Django urls instead of using forms, except when you want to share some url with someone? For instance, to me, path('stuff/<int:expected_value>', views.my_stuff) will be equivalent to <form method='post' action="{% url 'do_stuff' %}" id='{{ stuff.pk }}'> {% csrf_token %} <input type="hidden" name="some_value" value="{{ object.some_value }}"> <button type="submit">Send</button> </form> urls would always look clean that way, much more simple for the one coding as for the user checking it in the address bar (in my very own opinion of course). Maybe I just lack some obious knowledge, so please enlighten me! π -
Django + nginx, only homepage works
I don't understand this behavior coming from django running on gunicorn with static file hosting and port forwarding from nginx. project directory tree: . βββ Dockerfile βββ myproj β βββ __init__.py β βββ settings.py β βββ urls.py β βββ wsgi.py βββ pages β βββ __init__.py β βββ apps.py β βββ static β β βββ pages β β βββ index.css β βββ templates β β βββ pages β β β βββ index.html β βββ urls.py β βββ views.py pages/urls.py: urlpatterns = [ path('', views.index, name='home'), path('static-home/', views.index, name='static-home'), ] myproj/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('pages/', include('pages.urls')), path('', include('pages.urls')), ] If I python manage.py runserver then everything works as expected at these URIs http://127.0.0.1:8000/ http://127.0.0.1:8000/static-home/ http://127.0.0.1:8000/pages/ http://127.0.0.1:8000/pages/static-home/ If I dockerize using gunicorn + nginx ( as described in this blog post: https://blog.skindc.co.uk/dockerise-django-and-static-files-with-nginx/ ) Then I see a different behavior good: http://<docker-machine-ip>/ nginx 404: http://<docker-machine-ip>/static-home/ good: http://<docker-machine-ip>/pages/ good: http://<docker-machine-ip>/pages/static-home/ I will add any other info if requested, but in the interest of keeping the post succinct all my docker files, docker compose, nginx.conf, et cetera are the same as that shown in the tutorial linked above. Why is it that I can add all urls from pages at <docker-machine-ip>/pages/, but I can β¦ -
Automatically get name of the column with for loop in django template
I would like to automatically retrieve the name of the column with a for loop. If I know the name of the columns I can write the template in this way: <ul> {% for co in team %} <li>{{ co.name }}</li> <li>{{ co.team}}</li> <li>{{ co.sport}}</li> {% endfor %} </ul> But in my present case, I do not know the names of the columns of my table. How can I display them? Thank you -
Add a values to django manytomanyfield with using another database
I have 2 models class A(models.Model): name = models.CharField(max_length=255, verbose_name='Name') city = models.ManyToManyField('City') class City(models.Model): name = models.CharField(max_length=255, verbose_name='Name') I get objects from another database with 'using'. When i added values to ManyToManyField it's writing to 'default' database. city = City.objects.using('AN_DB').get(name=city_name) a = A.objects.using('AN_DB').get(name=a_name) a.city.add(city) How i can add values to 'AN_DB' ? -
Value Error for Foregin key field
I am trying to insert data but am getting ValueError while inserting due to ForeignKey. class Test(models.Model): test_name = models.CharField(max_length=20, unique=True) test_code = models.SlugField(max_length=10, name='Code',unique=True) referance_value = models.CharField(name='Referance', max_length=20) def __str__(self): return self.test_name class TestTaken(models.Model): app_code = models.CharField(max_length=20,unique=True) user_name = models.CharField(name='Username',max_length=20) test_names = models.ForeignKey(Test, on_delete=models.CASCADE) result_value = models.CharField(name='ResultValue',max_length=20) def __str__(self): return self.app_code Below is my View.py def alltestdata(request): if request.method == 'POST': app_code = request.POST.getlist('app_code') test_name = request.POST.getlist('name') test_list = request.POST.getlist('test_list') for i, j , k in zip(app_code, test_name, test_list): book = TestTaken(app_code=i, ResultValue=j, test_names=k, Username=request.user.username) book.save() return redirect('lab:Dashboard') Am geting following error ValueError: Cannot assign "'eeeee'": "TestTaken.test_names" must be a "Test" instance. -
Django Web app like onlinejudge with docker containers to execute and compile users code
I am building a web application like hacker rank , so the poit is , when the user typed and press the compile button , the code should need to be executed in the container . With all the testcases that are needed for the program . So give me an idea of how to do it . Also how to use celery with combination of monitoring with testcases . My Dockerfile is , FROM chug/ubuntu14.04x64 ADD hello.py ./pythondir/ ADD hello.c ./cdir/ RUN apt-get install -y gcc RUN apt-get install -y g++ CMD [ "python", "pythondir/hello.py" ] CMD [ "gcc","cdir/hello.c"] CMD [ "cdir/a.out" ] Hope you understand the question . Also when i tried to use this , i need to build the docker container again and again . So it takes sometime , which i dont want . What is the effective way of using Dockerfile -
How to render data to a {% included a.html %} template in Django
I have a rank.html which is a publicly sharing template for many other templates through {% include rank.html %} method. This template will display the 48 hours hot news base on the click number. Here is the view.py: def rank(self, request): hot_news_48h = h_mostViewed(48, News, '-pv') return render(request, "rank.html", { 'hot_news_48h': hot_news_48h,}) h_mostViewed(48, News, '-pv') is a function,that can fetch most viewed(clicked) post within 48 hours.It works. Here is the rank.html: <ul> {% for hot_view in hot_news_48h %} <li> <a href="{% url 'news:news_detail' hot_view.pk %}" > <img src="{{ MEDIA_URL }}{{ hot_view.image }}" > </a> <a href="{% url 'news:news_detail' hot_view.pk %}"> <h6>{{ hot_view.title }}</h6> </a> </div> </li> {% endfor %} </ul> Here is the url.py: path('hot_news', views.rank, name="hot_news") The problem is,I can't get the data. **But if I give up {% include rank.html %} method and insert the rank.html's code directly inside each template which need this function, I can get the data. Take new_detail.html template as an example:** Here is the view.py: def newsDetailView(request, news_pk): news = get_object_or_404(News, id=news_pk) all_comments = NewsComments.objects.filter(news=news) news.comment_nums = all_comments.count() news.save() News.objects.filter(id=news_pk).update(pv=F('pv') + 1) hot_news_48h = h_mostViewed(48, News, '-pv') relative_news = News.objects.filter(tag__id__in=news.tag.all()).exclude(id=news_pk)[:6] return render(request, "news_detail.html", { 'news': news, 'all_comments': all_comments, 'hot_news_48h': hot_news_48h, 'relative_news': relative_news }) β¦ -
using model forms to save data in different databases
Ok the problem is that I have a model in which a field is unique.I am inputting that field value from user in post body and wanted to save that via model form in a database that is also specified in post body # models.py class Type(models.Model): name = models.CharField(max_length=100, unique=True) created_at = models.DateTimeField(auto_now_add=True, editable=True) def __str__(self): return self.name #forms.py class TypeCreateForm(forms.ModelForm): class Meta: model = Type fields = "__all__" # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "default", 'USER': 'root', 'PASSWORD': 'abcd1234', 'HOST': '0.0.0.0', "PORT": "3306" }, 'database1': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "database1", 'USER': 'root', 'PASSWORD': 'abcd1234', 'HOST': '0.0.0.0', "PORT": "3306" }, } #views.py def index(request): db_name=request.POST["db_name"] ob = TypeCreateForm(request.POST) for a in ob: if a.errors: print(a.errors.as_text()) ob=ob.save(commit=False) ob.save(using=db_name) I searched several similar question of saving into another database other than default.Some suggested commit=False will work along with save with using keyword argument. In some answer they suggested to do modification in queryset of the field. But I dont think that worked for me because in my model there is a unique constraint as well so when I will print the errors before saving it will show unique constraint failed if that type is stored in default β¦ -
Django user.has_perm return false
I got some strange issue when user.has_perm always return true, even when permission is for sure in table. Maybe someone got like this before? Seams like issue only in last versions Test show issue is below: import django import datetime django.setup() from django.contrib.auth.models import User u=User.objects.get(pk=177) print("version %s" % str(django.VERSION)) print("1: %s" %str(u.has_perm('not_show_tos'))) from django.contrib.auth.models import Permission permissions = Permission.objects.filter(user=u) sorted_list_of_permissions = sorted(list(permissions)) print("2:%s " % str("not_show_tos" in sorted_list_of_permissions)); for i in sorted_list_of_permissions: print( str(i.codename)) print("%s" %str(u.has_perm(i.codename))) print("\n") p=Permission.objects.get(codename='not_show_tos'); print("4 %s " % str(p)) print("5 %s " % str(p in sorted_list_of_permissions)) print("6 %s " % str(u.has_perm(p))) Test result python3 /tmp/test.py signals init done. version (2, 0, 6, 'final', 0) 1: False 2:False not_show_tos False 4 sessions | session | Not Show Tos Page 5 True 6 False -
Django: No output when running `manage.py run_huey`
For my Django project I've created three settings files (base.py, development.py and production.py) instead of the normal settings.py. They are in the folder /settings. Unfortunately, it seems like this change has broken the little task queue Huey (https://github.com/coleifer/huey). Previously, when I ran manage.py run_huey I got this output immediately: [2018-08-17 17:47:25,040] INFO:huey.consumer:MainThread:Huey consumer started with 1 thread, PID 2389 [2018-08-17 17:47:25,041] INFO:huey.consumer:MainThread:Scheduler runs every 1 second(s). [2018-08-17 17:47:25,041] INFO:huey.consumer:MainThread:Periodic tasks are enabled. [2018-08-17 17:47:25,041] INFO:huey.consumer:MainThread:UTC is enabled. ... Now, I get no output at all, even when set to verbose. I am not sure what could cause this change, so I am asking here in hope someone has any idea. Here is the diff that changed the behaviour: https://dpaste.de/4GUy -
Virtual environments pip has two paths. How to remove one path ?
I created virtual environment with Pycharm and Anaconda but the problem is that pip has two paths. where pip : C:\Users\Tuta\Anaconda3\envs\test_haystack\Scripts\pip.exe C:\Python\Scripts\pip.exe How can I remove C:\Python\Scripts\pip.exe this path ? And leave Anaconda path.