Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to configure Geonode's geoserver on my ubuntu server using nginx
I have configured geonode and it is working fine on my local machine. I have proceeded to move it to an ubuntu server and I am using Nginx and gunicorn. I am having a challenge in starting my GeoServer on this URL 'geonode1.local.com/geoserver where I get the error below in my error.log: 2020/11/10 07:36:38 [error] 825#825: *7 "/usr/share/nginx/html/geoserver/web/index.html" is not found (2: No such file or directory), client: 197.232.113.55, server: geonode1.local.com, request: "GET /geoserver/web/ HTTP/1.1", host: "geonode1.local.com" my question: How do I get GeoServer to start on this URL? Do I need to install tomcat9 on my server? /etc/nginx/sites-available/geonode server { listen 80; server_name geonode1.local.com; location = /favicon.ico { access_log off; log_not_found off; } location ^~ /static/ { alias /home/user/Geosites/geonode/static/; } location ^~ /uploaded/ { alias /home/user/Geosites/geonode/uploaded/; } location /geoserver/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } # gunicorn wsgi proxy location / { proxy_pass http://unix:/run/gunicorn.sock; proxy_pass_header Server; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Scheme $scheme; proxy_connect_timeout 20; proxy_read_timeout 20; } location ^~ /static/admin/ { alias /home/user/Geosites/geosite_env/lib/python3.6/site-packages/django/contrib/admin/static/admin/ } } -
default integer value for non-primary field in django with postgresql
I have a non-primary key integer field in my Django model and I use Postgresql for database. class TestModel(models.Model) pid = models.IntegerField(blank=True) some_field = models.CharField() I want my pid field to have default values, that appear in database, I set the serial type for the pid field on the DB side alter column pid type serial not null; but when I create some record without without specifying value for pid, Django gives an error "null value in column "pid" violates not-null constraint", although it works fine when inserting data via SQL directly into database. I found this Django and PostgreSQL sequence for primary key autoincrement, but it's not working for me -
How to query ManyToManyField linked with a Foreign Key and that Foreign Key is linked with another Foreign Key?
I have created a TimeTable model that is linked to the Period Model via ManyToManyField and the Period Model is linked to the PeriodData via a Foreign Key. The models are working fine but I have very little idea of how to query the data. Here is the TimeTableModel - TimeTable Model class TimeTable(models.Model): class_id = models.OneToOneField(Classes, on_delete=models.CASCADE) monday = models.ManyToManyField('Period', related_name='monday', blank=True) tuesday = models.ManyToManyField('Period', related_name='tuesday', blank=True) wednesday = models.ManyToManyField('Period', related_name='wednesday', blank=True) thursday = models.ManyToManyField('Period', related_name='thursday', blank=True) friday = models.ManyToManyField('Period', related_name='friday', blank=True) saturday = models.ManyToManyField('Period', related_name='saturday', blank=True) Period Model class Period(models.Model): period_id = models.CharField(unique=True, max_length=50) class_id = models.ForeignKey(Classes, on_delete=models.CASCADE) period1 = models.ForeignKey('PeriodData', related_name='period1', blank=True, null=True, on_delete=models.CASCADE) period2 = models.ForeignKey('PeriodData', related_name='period2', blank=True, null=True, on_delete=models.CASCADE) period3 = models.ForeignKey('PeriodData', related_name='period3', blank=True, null=True, on_delete=models.CASCADE) period4 = models.ForeignKey('PeriodData', related_name='period4', blank=True, null=True, on_delete=models.CASCADE) period5 = models.ForeignKey('PeriodData', related_name='period5', blank=True, null=True, on_delete=models.CASCADE) PeriodData Model class PeriodData(models.Model): period_data_id = models.CharField(unique=True, max_length=50) class_id = models.ForeignKey(Classes, on_delete=models.CASCADE) subject_id = models.ForeignKey(Subject, null=True, on_delete=models.SET_NULL) teacher = models.ForeignKey(Teacher, null=True, on_delete=models.SET_NULL) start_time = models.TimeField() end_time = models.TimeField() Let's say that there is a class1 and on monday it has maths as its period1 and bio as its period2 and so on. And there's another class2 and on monday it has physics as its period1 … -
django digitalocean deploy cannot serve static files
[![enter image description here][1]][1]I try to deploy my app on digitalocean, when i configure the ngnix server, everything works except all the css and js file are not being served. I have done collectstatic, and my /etc/nginx/sites-available looks like this server { listen 80; server_name my ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/djangodeploy/portfolio-blog; } location /media/ { root /home/djangodeploy/portfolio-blog; } location / { include proxy_params; proxy_pass http://unix:/home/djangodeploy/portfolio-blog/mysite.sock; } } and my file structure looks like this [1]: https://i.stack.imgur.com/sg34k.png -
Convert datetime.date to django compatible date
I am reading data from an excel file and the date is being read in the following format: 'Date': datetime.date(2020, 2, 3) #yyyy-mm-dd whereas the Django allows the following date format: date: "2020-02-03T06:06:39.548Z" How can I convert the datetime.date to the compatible date format ? -
Unit Testing in Python Djnago
I am using Django==3.0.3 djangorestframework==3.11.0 python ==3.6.8 I want to write unit testing for API and no need to use any database(no need of mock database) that mean I want to mock the database call and write unit test cases how can i write which property is used for this Showing my api @api_view(['POST']) @permission_classes([IsAuthenticated]) def employee_entry(request): try: login = User.objects.get(pk=request.user.id) validationmsg = '' emp_data = request.data if not emp_data: validationmsg = validation["FDP15"] elif emp_data["EmployeeName"] is None or emp_data["EmployeeName"] == '': validationmsg = validation["FDP1"] elif emp_data["EmployeeCode"] is None or emp_data["EmployeeCode"] == '': validationmsg = validation["FDP2"] elif Employee.objects.filter(EmployeeCode=emp_data["EmployeeCode"]).count() > 0: validationmsg = validation["FDP3"] if validationmsg != '': return Response({msg: validationmsg}, status=status.HTTP_400_BAD_REQUEST) employee = Employee( EmployeeName=emp_data["EmployeeName"], EmployeeCode=emp_data["EmployeeCode"], Security=emp_data["Security"], CreatedDate=date.today(), CreatedUser=login, ) employee.save() if emp_data["Security"] == 1: device = Device.objects.filter(~Q(DeviceStatus=static_values["const0"])) employee.Device.set(device) elif emp_data["Security"] == 0: device = Device.objects.filter(~Q(DeviceStatus=static_values["const0"]), DefaultAccess=True) employee.Device.set(device) return Response({"EmployeeId": employee.EmployeeId}, status=status.HTTP_200_OK) except(KeyError, TypeError, ValueError) as ex: logging.getLogger("error_logger").exception(repr(ex)) return Response({msg: validation["FDP21"]}, status=status.HTTP_400_BAD_REQUEST) except Exception as ex: logging.getLogger("error_logger").exception(repr(ex)) return Response({msg: validation["FDP23"]}, status=status.HTTP_400_BAD_REQUEST) -
Django form validation with FileField
I am having some trouble getting a file to post via a form using generic class-based view CreateView. Below is what i have so far. I am not quite sure how to handle the file and if request.FILES is getting the file being posted or if there is something else i need to be doing to capture the file information in the form. I have tried following the docs, however no luck in getting something working. File uploads as a blank field. views.py # Create class FileUploadCreateView(BSModalCreateView): template_name = 'fileupload/create-file.html' form_class = FileUploadModelForm success_message = 'Success: File was uploaded.' success_url = reverse_lazy('files_list') # Add required field my_user prior to posting form def form_valid(self, form): form = FileUploadModelForm(self.request.POST, self.request.FILES) self.object = form.save(commit=False) self.object.my_user = self.request.user self.object.file_status = 'ready' return super().form_valid(form) -
How to save search query result into the model with Django?
This is for revert/rollback the table. I have a query like this: query = Table.objects.all() it takes all entries in the Table. I will delete it later: Table.objects.all().delete() Now I want to save query into Table. How can I do that? -
Django failed to read static files from Azure Blog storage
Here is my application settings.py, command "python manage.py collectstatic" works fine and pushing static files to azure STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'dist', 'static'), ] STATICFILES_STORAGE ='backend.custom_azure.AzureStaticStorage' DEFAULT_FILE_STORAGE = 'backend.custom_azure.AzureMediaStorage' AZURE_ACCOUNT_NAME = os.environ['AZURE_ACCOUNT_NAME'] AZURE_ACCOUNT_KEY = os.environ['AZURE_ACCOUNT_KEY'] AZURE_CUSTOM_DOMAIN = os.environ['AZURE_CUSTOM_DOMAIN'] STATIC_LOCATION = 'static' STATIC_URL = f'http://xxxxxxxx.blob.core.windows.net/static/' AZURE_LOCATION = os.environ['AZURE_LOCATION'] AZURE_CONTAINER = os.environ['AZURE_CONTAINER'] MEDIA_LOCATION = "media" MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' While running the application server looking for the static files and fails, server looking for different path, I can see static files in Azure [10/Nov/2020 05:24:47] "GET /static/js/app.fa77985a.js HTTP/1.1" 404 77 [10/Nov/2020 05:24:47] "GET /static/css/chunk-vendors.102171f9.css HTTP/1.1" 404 77 [10/Nov/2020 05:24:47] "GET /static/css/app.0f5f9b8e.css HTTP/1.1" 404 77 [10/Nov/2020 05:24:47] "GET /static/js/chunk-vendors.56f4d0fa.js HTTP/1.1" 404 77 Following the doc available at https://medium.com/@DawlysD/django-using-azure-blob-storage-to-handle-static-media-assets-from-scratch-90cbbc7d56be -
How to get the object type and name on Django
I have this obj details on my Django context debug u'non_homepage_obj': <Organisation: text-org>, This is the context related to it 'non_homepage_obj': obj.primary_publisher, How to get the <Organisation: text-org> into string, which i can put the Organisation or the name of Organisation into use later on? I already tried str(obj.primary_publisher) but it's only get the text-org, and not passing the Organisation. Thanks -
Django Calculation inside HTML
I wanted to do something simmilar to this suing django. but somehow i it doesn't work. how do i fix it? for statik in statistik{ print(statik*total/100) } Is there any documentation regarding what I'm trying to implement to my django app? Thank you Here's the HTML : {% if statistics %} {% for statik in statistics|slice:":4" %} <div class="mb-3"> <div class="small text-gray-500">{{ statik.name }} <div class="small float-right"><b>{{ statik.voters }} of {{ total }} Voters</b></div> </div> <div class="progress" style="height: 12px;"> <div class="progress-bar bg-success" role="progressbar" style="width: {{ statik.voters * total/100 }}%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> {% endfor %} {% else %} <p>END TABLE</p> {% endif %} -
How do I query that spans multiple relationships?
Here's a simplified version of my model class: class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) class UserProfile(models.Model): user = models.OneToOneField(User, related_name = 'profile') first_name = models.CharField(max_length=120, blank=True, null=True) last_name = models.CharField(max_length=120, blank=True, null=True) following = models.ManyToManyField(User, related_name = 'followed_by', blank=True, through='FollowingRelation') class FollowingRelation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) I'd like to query all rows from BlogPost that have been created by the session user, plus all other posts created by the users that the sessionUser is following, but has a timestamp greater than or equal to the timestamp when the session user started following. -
Refused to apply style from because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled
after adding build folder(from reactjs) to my django backend folder. I am getting this error while running the surver. another similar error is : Refused to execute script , because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. i have added the path of build folder in the templates section in the setting.py file..here is the code: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] can anyone please help me fix this?? -
Django-crontab is not working on in linux ec2 instance
I'm trying to set up cron jobs in my django application on a ec2 instance(linux). Everything is working fine, I tried python3 manage.py cron add python3 manage.py cron show python3 manage.py cron remove everything works just fine But when I start the apache server, and load the page, I'm getting 500. From the error logs I found that django_crontab module was not found. But it's still there and I've installed it in the virtual environment too (I've double checked with pip3 freeze). I also tried sudo service cron start which didn't show me anything and didn't make any difference. What could be the possible issue here? -
Cannot read csv files uploaded using pandas in Djnago
I have the following view defined in my Django views:- def csv_file_upload(request): if request.method == "POST" and request.FILES['file_upload']: registry = request.POST.get('reg_select').lower() csv_file = request.FILES['file_upload'] data = pd.read_csv(csv_file, delimiter="\|\|") print(data.head()) return render(request, "csv_file_upload.html", {}) But the pd.read_csv part is giving me this error:- cannot use a string pattern on a bytes-like object The sample csv file that I have is like this: Col_A||Col_B||Col_C A0||B0||C0 A1||B1||C1 The same file I can read using pd.read_csv() without using Django and do no get this error. Why is this error being caused when using Django? -
unable to use link to the admin page in django
i am using django 3.0.8 on python 3.7 and every time use the link to the admin page. i get this: this is the cmd console after i enter the admin page. this is the web page error my urls.py file and my settings.py file i am not finding any solutions online and any help would be appreciated. P.S i am using the database django comes with. the sqlite3 one. -
How do I initialize a django form with the previous input in a class based view?
It displays a form on the top and when you submit it, it will only show some of the Offer instances that fits the filters. It works fine, but every time I submit it, the form returns to the initial value. How can I stop that? My form uses GET and the view is class-based. Also, the __init__ in the form doesn't seem to be working. views.py class Search(ListView, FormMixin): model = Offer template_name = 'search.html' paginate_by = 20 form_class = SearchForm def get_queryset(self): self.form = SearchForm(self.request.GET) if self.form.is_valid(): data = self.form.cleaned_data qs = Offer.objects.all() if data['book'] != '0': qs = qs.filter(book_id=data['book']) qs = qs.filter(worn_degree__in=data['min_worn_degree']) qs = qs.filter(note_degree__in=data['min_note_degree']) return qs else: return Offer.objects.all() search.html {% extends 'base_generic.html' %} {% block content %} <form method="get"> {% csrf_token %} <table> {{ form.as_table }} </table> <br> <input type="submit" value="검색"> </form> {% if object_list %} {% for object in object_list %} <p>{{ object.book.title }}</p> <p>{{ object.seller }}</p> {% endfor %} {% else %} <p>There are no offers.</vp> {% endif %} {% endblock %} forms.py class SearchForm(forms.Form): def __init__(self, *args, **kwargs): super(SearchForm, self).__init__(*args, **kwargs) self.book = '0' self.min_worn_degree = 'abc' self.min_note_degree = 'abc' BOOK_CHOICE = tuple([('0', '모두')] + [(book.id, book.title) for book in Book.objects.all()]) book … -
Form booleanfield does not appear in request.POST data
I tried printing out all (key,value) pairs in a request.POST to extract the form data. I notice that a BooleanField, if not checked (i.e. set to True), is not included in request.POST. This is true even if the BooleanField is set with required=True. Is it possible to force the (key,pair) to be sent? For example, in this form below, if applied field is not checked when rendered, request.POST should still include applied off? When applied is checked, request.POST includes applied on. But without being checked, applied is not part of request.POST data. class ItemModifierForm(forms.Form): applied= forms.BooleanField(label='Trait A', required=True) -
Django: prefetch related: for loop: based on how we call for loop, the number of sql call varies
In django i am trying to understand prefetch: I have two for loop scenarios after prefetch symbollist = SymbolList.objects.prefetch_related('some_related_name')[0:10] for i in range(0,symbollist.count()): print(symbollist[i].some_related_name) Now it calls sql N+1 times where as symbollist = SymbolList.objects.prefetch_related('some_related_name')[0:10] for symbol in symbollist: print(some_related_name) this will call only two sqls Why so -
Django Can I change the Receive Charset specific View?
settings.py DEFAULT_CHARSET = 'UTF-8' views.py class OrderResult(viewsets.ModelViewSet): def create(self, request, *args, **kwargs): payload = request.data <<---- some string broken *** save to database i'd like to receive data with 'euc-kr' only in the above View. Is it impossible? I can't find it. -
How to fix find and Field 'id' expected a number but got '' error
I am trying to add a like button to my posts in a Django Project. I have made a model for the likes and included a value for it. In the template the post_id should be reflected in the views but for some reason it is showing an error. So, I have followed all the steps correctly but I am getting error: ValueError at /blogs/like Field 'id' expected a number but got ''. Here is the models.py class Post(models.Model): liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') ...................................... @property def num_likes(self): return self.liked.all().count() LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10) date_liked = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.post) Here is the views.py def like_post(request): user=request.user if request.method=='POST': post_id=request.POST.get('post_id') post_obj= Post.objects.get(id=post_id)<--------------- Error highlighted in this line if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like,created=Like.objects.get_or_created(user=user,post_id=post_id) if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' like.save() return redirect('blog:post_list') Here is the template: <form action="{% url 'blog:like-post' %}" method="POST"> {% csrf_token %} <input type="hidden" name="post_id" value='{{obj.id}}'> {% if user not in obj.liked.all %} <button class="ui button positive" type="submit">Like</button> {% else %} <button class="ui button negative" type="submit">Unlike</button> {% endif %} <strong>{{ obj.like.all.count }} … -
Django - Add the same set of objects to a queryset using a ManyToMany field
I have pizzas and I have toppings. class Pizza(ModelBase): name = models.CharField(max_length=255) toppings = models.ManyToManyField('Topping', blank=True, related_name='pizzas') class Topping(ModelBase): name = models.CharField(max_length=255) Let's suppose I want to add the toppings Tomato and Cheese to every pizza in my database. At the moment I can do it with a nasty for loop: toppings = Toppings.objects.filter(Q(name='Tomato') | Q(name='Cheese')) for pizza in Pizza.objects.all(): pizza.toppings.add(*toppings) Is there a way to achieve the same thing without having to loop all the pizzas? Maybe using the through table that Django creates? I know that I can delete the toppings from all the pizzas using the following query: Pizza.toppings.through.objects.filter(topping__in=toppings).delete() but I haven't been able to add toppings to multiple pizzas without the for loop. -
Why is one text element of a table not aligning with the rest?
I'm making a game based off of a gameshow with Django, and want the users to be able to select a specific episode to play. The page in question is after the users have selected a year from the database, when they select the month from which they want to play. For some reason, no matter which year is selected, the month of March is always not aligned with the rest of the text. This occurs if March is the first, second, or third available month. I have not styled it differently from the others, and when I click inspect it randomly aligns with the rest (pictures attached). I've attached the code from episode_month.html and main.css. If anyone could help me align this month or give insight as to why it's above the others I'd appreciate it--it's been driving me crazy! episode_months.html: {% extends "game/base.html" %} {% load static %} {% block content %} <div class = "mode">Available Months</div> <div class = "mode_info">{{ year }}</div> <table class = "board"> {% for month_group in months %} <tr class = "row"> {% for month in month_group %} {% if month != "" %} <th class = "tile-months board_cat"> <a class = board_month … -
Cmd is not finding my files. I can see them in file explorer, but am unable to see them or access them in cmd
I am unable to access bookbuddy or activate my python virtualenv. The problem is not specific to this Project-BookBuddy directory. There are strange and inconsistent results in other directories as well. I recently synced with oneDrive. IDK if that has anything to do with this. -
Django + chart.js: plot with django Queryset data
I am across a problem that I cannot handle. I passing queryset data from a django view to its corresponding template and I want to use this data to plot a graph with chart.js I am trying to achieve this without using Ajax requests. However, when I try to acquire the queryset data with javascript to pass it in chart.js it renders an error. Here is what I have done in html: <div id="default_data"> <p> {{ default_items }} </p> </div> <div id="labels"> <p>{{ labels }} </p> <div class="col-lg-6"> <div id="tag3" class="card-footer small text-muted">{% trans 'ITEMS WITH HIGHEST NUMBER OF SALES (3 MONTHS)' %}</div> <div class="bar-chart block"> <canvas id="myChart3" height="90"></canvas> </div> </div> and here is what labels and default_data render: <QuerySet [58.0, 62.0, 74.0, 60.0, 16.0, 1.0, 1.0, 1.0, 1.0, 2.0]> <QuerySet ['372750', '372600', '372650', '372700', '372150', '289807', '289922', '289840', '289923', '372310']> and javascript: <script> var ctx3 = document.getElementById('myChart3').getContext('2d'); var labels = document.getElementById("labels"); var myChart3 = new Chart(ctx3, { type: 'bar', data: { labels: labels, datasets: [{ label:'références avec nombre de ventes élevé', data: default_data, label: '# of Votes', borderWidth: 1, }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); </script> I don't …