Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
query ManyToManyfield for requested user
I have two models, a user model and a sport model. These two models have a m2m relationship as a user can do multiple sports and a sport can be played by more than one user. I want to get a query set of a user's sports, so only the sports a specific user does shows up for that user. I have created a context_processors.py file so that the information is available on all pages of the site. The problem is that I don't know how to query the database to get this information. These are my models: class Sport(models.Model): name = models.CharField(max_length=100, null=False) class User(AbstractUser): ... sports = models.ManyToManyField(Sport) Right now, I get all the sports available, like this def test(request): sports = Sport.objects.all() return { 'x': sports } I just want to get the sports the requested user is assigned to in the sports variable. -
Internal server [closed]
I m having the this issues after deploying an app on DigitalOcean. I Set Up a wagatail app with Postgres, Nginx, and Gunicorn on Ubuntu 20. And after the the configurations, here is what I get when I send a message from the contact app. Internal server error Sorry, there seems to be an error. Please try again soon. I have sentry running and telling me the errors like this: 1- ConnectionRefusedError /{var} New Issue Unhandled [Errno 111] Connection refused 2 - Invalid HTTP_HOST header: '${ip}:${port}'. The domain name -
python name '_mysql' is not defined
I build a virtual environment with python 3.7.10, by installing mysql and mysqlclient It is mysql 8.0.28, mysqlclient 2.1.0. When running python manage.py migrate It comes out like this: (test) ➜ backend git:(main) python manage.py migrate Traceback (most recent call last): File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 0x0002): symbol not found in flat namespace '_mysql_affected_rows' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/db/models/base.py", line … -
Why is django adding two slashes at the end of my urls?
I'm new to django and I'm trying to develop my first website. I've searched for similar questions but I couldn't find any (or maybe I've only searched the wrong query). What I'm here to asking is why django is adding a final slash into my url? and why is it doing this just in few occasions? I'd want to explain you better what it's happening to me. This is my urls.py (a portion) urlpatterns = [ path('admin/', admin.site.urls), path('', home, name='home'), path('new/', new, name="new"), path('attachements/<str:pk>/<str:var>/', attachements, name="attachements"), path('new_2_4/<str:pk>/<str:var>/', new_2_4, name="new_2_4"), path('new_4e2/<str:pk>/<str:var>//', new_4e2, name="new_4e2"), # others ] In my template.html I've created tag which allows me to go from a page to others, for example: <ul class="nav nav-tabs"> <li class="nav-item" style="background-color:powderblue;"> <a class="nav-link" href="{% url 'attachements' att.id var%}">Allegati</a> </li> <li class="nav-item" style="background-color:powderblue;"> <a class="nav-link" href="{% url 'new_2_4' att.id var %}">4</a> </li> <li class="nav-item" style="background-color:powderblue;"> <a class="nav-link" href="{% url 'new_4e2' att.id var %}">4.2</a> </li> </ul> <div style="position:relative; left:20px;"> <a class="btn-sm btn-info" href="{% url 'new_2_4' att.id var %}">&#x2190;</a> <a class="btn-sm btn-info" href="{% url 'new_4e3' att.id var %}">&#x2192;</a> </div> When I first have designed the whole thing, my url for 'new_4e2' didn't have two final slashes: I've had to add one final manually because … -
Ajax requires Basic authentication again
I have project with django and nginx and nginx has the basic authentication Accessing top page / the basic authentication works well. server { listen 80; server_name dockerhost; charset utf-8; location /static { alias /static; } location / { auth_basic "Restricted"; auth_basic_user_file /etc/nginx/.htpasswd; proxy_pass http://admindjango:8011/; include /etc/nginx/uwsgi_params; } } but in template, I use ajax to local api /api/myobj/{$obj_id} $.ajax({ url:`/api/myobj/${obj_id}/` It requires the authentication again and pop up appears. I wonder /api/myobj/ is under / Why it requires authentication again?? And even I put the id/pass correctly, it is not accepted. I tried like this ,but it also in vain. $.ajax({ url:`/api/myobj/${obj_id}/`, username: "myauthid", password: "myauthpass", -
Saving and displaying multiple checkboxes to Django ModelMultipleChoiceField
I am a beginner on django 2.2 and I can't correctly send multiple choices in the database. In my field table the days are stored like this: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] My form : CHOICESDAY = (("Monday", "Monday"), ("Tuesday", "Tuesday"), ("Wednesday", "Wednesday"), ("Thursday", "Thursday"), ("Friday", "Friday"), ("Saturday", "Saturday"), ("Sunday", "Sunday") ) class FgtScheduleForm(forms.ModelForm): days = forms.MultipleChoiceField(required=True, choices=CHOICESDAY, widget=forms.CheckboxSelectMultiple( attrs={'class': 'checkbox-inline'})) class Meta: model = FgtSchedule fields = ('name','days') widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control form-form ' 'shadow-none td-margin-bottom-5'}), } fields = ('name', 'days') My model class FgtSchedule(models.Model): days = models.CharField(max_length=100, blank=True) My view : def fg_schedule_list(request): list_fg_sch = FgtSchedule.objects.all() return render(request, 'appli/policy/fg_schedule.html', {'list_fg_sch': list_fg_sch}) My template {% for fg_sch_list in list_fg_sch %} <tr> <td>{{ fg_sch_list.id }}</td> <td>{{ fg_sch_list.name }}</td> <td>{{ fg_sch_list.days|replace_days }}</td> </tr> {% endfor %} My custom tags : @register.filter def replace_days(value): CHOICESDAY = {"Monday": "Monday", "Tuesday": "Tuesday", "Wednesday": "Wednesday", "Thursday": "Thursday", "Friday": "Friday", "Saturday": "Saturday", "Sunday": "Sunday"} return CHOICESDAY[value] The problem is when I want to display later all the days I have KeyError at "['1', '2']" -
is there a way to find duplicated value that has both the same address and pickup date in two different table?
I am currently working on a delivery app. Basically, what I am trying to achieve here is to have a counter that display out any potential duplicated jobs that the customer might have accidently double entered. The criteria to be considered as a duplicated job is as such: Has to have same delivery_address and same pickup_date. This is my postgresql tables: class Order(models.Model): id_order = models.AutoField(primary_key=True) class OrderDelivery(models.Model): order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) delivery_address = models.TextField() class OrderPickup(models.Model): order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) pickup_date = models.DateField(blank=True, null=True) This is what I have came up with so far: def dashboard_duplicated_job(orders, month): # This function finds for jobs that has # (1) exact pickup_date # (2) exact delivery address # and mark it as duplicated job. # Find current month, if not take current year now = timezone.localtime(timezone.now()) month = "12" if month and int(month) == 0 else month if month == 12 or month == '12': now = timezone.localtime(timezone.now()) last_month = now.today() + relativedelta(months=-1) start_date = last_month.replace(day=1).strftime('%Y-%m-%d') year = last_month.replace(day=1).strftime('%Y') month = last_month.replace(day=1).strftime('%m') last_day = calendar.monthrange(int(year), int(month))[1] string_start = str(year) + "-" + str(month) + "-01" string_end = str(year) + "-" + str(month) + "-" + str(last_day) start_date = … -
Update Boolean field and Integer fields from Django view
Can someone please point me in the right direction here. I have a quiz app where I want to implement some user progress objects. I have a QuizResult model which foreignkeys to user, quiz and lesson. What I want is to be able to update a couple of fields: score (integer field) and complete (boolean field) from my views.py function. when I try to update these fields from my frontend I get a no errors, but the object shows complete and score fields as null. Here is my model: class QuizResult(models.Model): student = models.ForeignKey(User, related_name="results", on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, related_name="results", on_delete=models.CASCADE) lesson = models.ForeignKey(Lesson, null=True, blank=True, related_name="results", on_delete=models.CASCADE) score = models.IntegerField(blank=True, null=True) complete = models.BooleanField(default=False) and my view.py function: @api_view(['POST']) def post_progress(request, pk): data = request.data score = data.get('score') complete = data.get('complete') quiz = Quiz.objects.get(pk=pk) user_progress = QuizResult.objects.create(quiz=quiz, score=score, complete=complete, student=request.user) serializer = QuizResultSerializer(user_progress, data=data) return Response(serializer.data) -
How to have multiple Auth models in django
I have an application where I've two models both models have same fields client buyer I'm using separate models because client can also signs up as a buyer using the same email and vice versa. I don't want to use single model for both client and buyer with some checks like is_buyer/is_client. How do I achieve something like class Client(AbstractUser): email = Field() password = Field() class Buyer(AbstractUser): email = Field() password = Field() AUTH_USER_MODEL=app.Client AUTH_USER_MODEL=app.Buyer Also I'm using simpleJWT library, so I can generate jwt when the client or buyer logins in. -
Compress an image to less than 1MB (one) and than allow users to download the image using Python in Django project
I'm working on a Django project. All I need is to take a image as an input from user than I have to compress it in less than 1MB or specific size without losing too much quality. Then allow users to download the image -
Run Tasks on Celery with Django Error: raised unexpected: ConnectionRefusedError(111, 'ECONNREFUSED')
I just run Redis on my VPS with no problem: -------------- celery@s1550.sureserver.com v5.2.3 (dawn-chorus) --- ***** ----- -- ******* ---- Linux-5.15.19-sure2-x86_64-with-debian-10.11 2022-03-08 17:22:46 *** --- * --- ** ---------- [config] ** ---------- .> app: web_edtl:0x7c2374cc52e8 ** ---------- .> transport: redis+socket:///home/$USER/private/redis/redis.sock ** ---------- .> results: socket:///home/hamutuk/private/redis/redis.sock *** --- * --- .> concurrency: 2 (eventlet) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . imagekit.cachefiles.backends._generate_file [2022-03-08 17:22:46,248: INFO/MainProcess] Connected to redis+socket:///home/$USER/private/redis/redis.sock [2022-03-08 17:22:46,252: INFO/MainProcess] mingle: searching for neighbors [2022-03-08 17:22:47,267: INFO/MainProcess] mingle: all alone [2022-03-08 17:22:47,284: INFO/MainProcess] pidbox: Connected to redis+socket:///home/$USER/private/redis/redis.sock. [2022-03-08 17:22:47,292: WARNING/MainProcess] /home/$USER/private/project/project_env/lib/python3.7/site-packages/celery/fixups/django.py:204: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! leak, never use this setting in production environments!''') [2022-03-08 17:22:47,293: INFO/MainProcess] celery@s1550.sureserver.com ready. But web i run some task to Send Email i got a Error : raised unexpected: ConnectionRefusedError(111, 'ECONNREFUSED') This is log off error: [2022-03-08 17:04:44,527: ERROR/MainProcess] Task appname.tasks.task_name[892f4462-2745-4bb7-9866-985cd3407c86] raised unexpected: ConnectionRefusedError(111, 'ECONNREFUSED') Any Ideia how to Fix it? Thank You -
Running a command from a command line tool from another app in django
I am building a Webapp using Django and want to generate some comments from a command-line tool present in the same directory as the web app. What are the different methods to call this tool from the web app and run commands in the terminal and extract output from it and display it in a web app? -
How I can show selectbox from models in my form?
How I can show selectbox from models in my form. Output for below code does not show options for selectbox. #models.py class Reg(models.Model): options = ( ('one', 'option1'), ('two', 'option2'), ) types = models.CharField(max_length=30, choices=options,null=True) company = models.CharField(max_length=50,null=True) #form.py from django import forms from .models import Reg class Regform(forms.ModelForm): class Meta: model = Reg fields = ['types','company'] types = forms.CharField( widget=forms.Select( attrs={'class': 'form-control'} ), label="Type", ) -
Is there a way to require a signature or authorization when POSTing JSON data to a Django database with Python?
Say I have a Django database in an API storing a bunch of JSON data. I have a scraper webscraping a site and posting the info at specific endpoints. It runs swimmingly but, if I were to share my API, I worry that there may be a malicious actor or some troll that might want to POST fraudulent data to the database. So the question is, is there a key or or some functionality that authorizes the poster to upload to the database? How would I implement this? Thank you in advance! -
Error "string indices must be integers" when querying
I am just learning how to write programs and applications in python. I'm writing a serializer for a Recipe app. But I am getting an error. Please help me understand and write correctly. Here is the serializer: class AddRecipeIngredientsSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(queryset=Ingredient.objects.all()) amount = serializers.IntegerField() class Meta: model = RecipeIngredient fields = ('id', 'amount') class AddRecipeSerializer(serializers.ModelSerializer): image = Base64ImageField() author = CustomUserSerializer(read_only=True) ingredients = AddRecipeIngredientsSerializer(many=True) tags = serializers.PrimaryKeyRelatedField( queryset=Tag.objects.all(), many=True ) cooking_time = serializers.IntegerField() class Meta: model = Recipe fields = ('id', 'tags', 'author', 'ingredients', 'name', 'image', 'text', 'cooking_time') def validate_ingredients(self, data): ingredients = data[0] if not ingredients['id']: raise ValidationError('Не выбрано ни одного ингредиента!') ingredients_ids = [ingredient['id'] for ingredient in ingredients] if len(ingredients) != len(set(ingredients_ids)): raise serializers.ValidationError('Вы не можете добавить один ' 'ингредиент дважды') for ingredient in ingredients['amount']: print(ingredients) print(ingredient) if int(ingredient) <= 0: raise ValidationError('Количество должно быть положительным!') pk = int(ingredient['id']) if pk < 0: raise ValidationError('id элемента не может быть ' 'отрицательным') return data def validate_tags(self, data): if not data: raise ValidationError('Необходимо отметить хотя бы один тег') if len(data) != len(set(data)): raise ValidationError('Один тег указан дважды') return data def validate_cooking_time(self, data): if data <= 0: raise ValidationError('Время готовки должно быть положительным' 'числом, не менее 1 минуты!') return data … -
Dynamic carousel in django using bootstrap carousel
I am working on project where I need dynamic carousel in my html.problem is I making carousel which have maximum of 5 slide but what I am getting only 4 slides and i cannot even nav buuton to last slide using buttons and also prev button is not working when i at the second last slide. I used bootstrap carousel . Views.py class HomeView(View): def get(self,request): return render(request,'MainSite/home.html',{'carousel_item' : carousel_item}) home.html <div style = "padding : 10px 10px 10px 10px;margin-top : 20px;"> <div id="carouselExampleCaptions" class="carousel slide mx-3" data-bs-ride="carousel"> <div class="carousel-indicators"> {%for item in carousel_item %} {% if forloop.first %} <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> {% else %} <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button> {% endif %} {% endfor %} </div> <div class="carousel-inner"> {%for item in carousel_item %} {% if forloop.first %} <div class="carousel-item active"> <img src="{{item.title_image}}" class="d-block w-100" height = "350px" > <div class="carousel-caption d-none d-md-block"> <h5>{{item.title}}</h5> <p>{{item.subtitle}}</p> </div> </div> {% else %} <div class="carousel-item"> <img src="{{item.title_image}}" class="d-block w-100" height = "350px" > <div class="carousel-caption d-none d-md-block"> <h5>{{item.title}}</h5> <p>{{item.subtitle}}.</p> </div> </div> {% endif %} {% endfor %} </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> … -
how to deal with model property in django view
I am trying to do an ecommerce app ,where in i have to add coupon code in the checkout page. I had a model property to check for the coupon code validity.Here is my code model: class CoupenCode(models.Model): code=models.CharField(max_length=100) startdate=models.DateField() enddate=models.DateField() discount=models.IntegerField() disc_type=models.CharField(max_length=20,choices=( ('Amount','Amount'), ('Percentage','Percentage'))) usercount=models.PositiveIntegerField() min_amount=models.PositiveIntegerField() @property def is_expired(self): if datetime.now().date() > self.enddate or datetime.now().date() < self.startdate : return False return True class Meta: db_table = 'CoupenCode' ordering = ['-id'] def __str__(self): return self.code views: def fncoupon(request): if request.method=="POST": coupon=request.POST.get('promo') couponcode=CoupenCode.objects.filter(code=coupon) validity=couponcode.is_expired() if validity == True : if couponcode.disc_type == "Amount": discount=couponcode.discount + 'Rs' else: discount=couponcode.discount + '%' print(discount) return JsonResponse({'discount':discount}) else: message="This coupon code is not valid" print(message) return JsonResponse({'message':message}) the problem is i cant check for the coupon code validity using this property in views.it gives me an error 'QuerySet' object has no attribute 'is_expired' Can anyone please suggest me how i could solve this.. -
Django Rest Framework: How to generate sequence numbers
In my projects, there is a unique random number that is auto-generated through a function, but the scenario is I want a sequential number for each entry. def generate_unique_key(length): return ''.join(random.choice(string.digits) for _ in range(length)) def get_unique_key(): while User.objects.filter(learner_number=unique_id).exists(): unique_id = ("NO" + generate_unique_key(length=3)).upper() return unique_id how to change the above functions to generate sequential numbers for each entry? Like userA: NO001 userB: NO002 -
I am not able to make migrations to the following file?
My models.py code is this ` from django.db import models class Flight(models.Model): origin = models.CharField(max_length=64), destination = models.CharField(max_length=64), duration = models.IntegerField(), -
Cannot submit Django Wizard form when form is passed with arguments
I'm creating an app containing 3 multiple choice questions. The second multiple choice options are dependent on the response to the first question. To accomplish this, I added a "choices" argument to the second form and called that argument in the wizard's get_form function. While everything appears to work normally, the problem occurs when trying to submit the form on the last step. The done() function is never called and neither is the clean() function in forms.py. The page just gets refreshed without any errors appearing and the existing selected options get wiped. From testing, I've concluded that removing the custom init from forms.py and the get_form from views.py fixes the issue--but obviously defeats the purpose of this. I've been trying for a very long time to solve this issue but just can't seem to, any help is greatly apperciated! views.py class FormWizardView(SessionWizardView): form_list = [FormReflectionOne, FormReflectionTwo] template_name = 'reflection/form.html' def done(self, form_list, **kwargs): form_data = [form.cleaned_data for form in form_list] # Save form_data to Reflection Model return redirect('dashboard') def get_form(self, step=None, data=None, files=None): if step is None: step = self.steps.current if step == '1': firststep_data = self.get_cleaned_data_for_step('0') choices_list = AdjectiveChoice.objects.filter(feeling=firststep_data['feeling']) choices = [(x.order, x.adjective) for x in choices_list] form … -
Recover data deleted by diskpart
After accidentally deleting all data on my disk using "clean" on diskpart, my HDD is now empty. I've searched and used some recovery data apps, one of them is EaseUS. After scanning hours, it shows up exactly all data I lost but requiring fee to recover. I want to know that how all the data is still remained and found by the app while the disk show in my computer is empty and is there any reliable and safe ways to recover all data that do not require money? p/s: Sorry for bad english, I hope you guys understand and help me with this problem. -
How To Create Live Location Tracker in Django? [closed]
I have Used folium To create map but two pointer mark draw that was straight line and so i am getting straight line but i am not able to get the road location. SO please help me in fixing that. -
Running into a booting worker issue with Django application when deploying to heroku
I'm deploying a website using Heroku, Django and gunicorn and can't seem to get it to deploy. 2022-03-08T04:04:56.739100+00:00 heroku[web.1]: State changed from crashed to starting 2022-03-08T04:05:02.664299+00:00 heroku[web.1]: Starting process with command `gunicorn commerce.wsgi` 2022-03-08T04:05:03.931009+00:00 heroku[web.1]: State changed from starting to up 2022-03-08T04:05:03.885712+00:00 app[web.1]: [2022-03-08 04:05:03 +0000] [4] [INFO] Starting gunicorn 20.1.0 2022-03-08T04:05:03.886103+00:00 app[web.1]: [2022-03-08 04:05:03 +0000] [4] [INFO] Listening at: http://0.0.0.0:6623 (4) 2022-03-08T04:05:03.886136+00:00 app[web.1]: [2022-03-08 04:05:03 +0000] [4] [INFO] Using worker: sync 2022-03-08T04:05:03.889017+00:00 app[web.1]: [2022-03-08 04:05:03 +0000] [9] [INFO] Booting worker with pid: 9 2022-03-08T04:05:03.932911+00:00 app[web.1]: [2022-03-08 04:05:03 +0000] [10] [INFO] Booting worker with pid: 10 2022-03-08T04:05:04.307248+00:00 app[web.1]: [2022-03-08 04:05:04 +0000] [10] [ERROR] Exception in worker process 2022-03-08T04:05:04.307278+00:00 app[web.1]: Traceback (most recent call last): 2022-03-08T04:05:04.307279+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute 2022-03-08T04:05:04.307280+00:00 app[web.1]: return self.cursor.execute(sql, params) 2022-03-08T04:05:04.307280+00:00 app[web.1]: psycopg2.errors.UndefinedTable: relation "auctions_category" does not exist 2022-03-08T04:05:04.307280+00:00 app[web.1]: LINE 1: ...category"."name", "auctions_category"."name" FROM "auctions_... -
I have django application and nginx
I have django application and nginx, from browser, it access to the file /static. such as http://example.com/static/file.png However my application has files under /staticroot. http://example.com/staticroot/file.png it shows the image. So, I set on nginx. location /static { alias /staticroot; } However it doesn't appear My environment is Debug mode. My settings py is like this, STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(config("PROJ_PATH"), 'staticroot') How can I fix this? -
NotSupportedError : Calling QuerySet.exclude() after union() is not supported
I am getting the above error when I was trying to exclude some datasets from the result.. votes = VoteResponse.objects.filter(project=self) others = OtherResponse.objects.filter(project=self) vote_responses = votes.filter(date__year=self.date.year, date__quarter=self.date_quarter) return vote_responses.union(others) and I am trying to exclude the comments with null... projectSnapshot.comments = projectSnapshotResponses.exclude(comments='').order_by('-date')[:10].values_list('comments', flat=True) Could anyone please help me with this... Thanks