Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I exclude user
I am creating a website where different users can upload a post and also tag other users to a post. I have list of post on news feed from different users and also users have been tagged on same posts.Example: user A and user B are friends, user A uploaded a post and user B uploaded a post, user A and user B tagged user C on a post. When user A blocked user C, user A will no longer find user C as tagged user to his post, but the problem here is that user A can still find user C in user B post. How can i exclude user C from other users post who are friends to user A, so that user A can no longer see any post associated to user C. I was able to remove user C from user A post when user A blocked user C, but how do i also make user A not to see user C when user A view tags of user B. I haave been trying to figure this out for awhile but no progress.I hope my explanation is understandable. Model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) blocked_users = … -
How can I set up nginx for my django application on digitalocean?
Yes, I did research, but it confused me even more. I have an django app on digitalocean. Thanks to @jonas I figured out that I should use nginx to serve static files. I didn't knew that I had to use it, so I started without nginx. What steps must I take to serve my static files correctly with django? -
Django channels hosting
Any idea where can I host a Django app that uses channels? Its channel layer uses redis if that matters. I tried hosting it on pythonanywhere where I usually host my projects but after some research I found out that it does not support this type of app. I am thinking about trying to host it on heroku but I don't know if it will work on the free version. Any recommendation for a place where I can host my app (preferably for free)? -
Integrating Django REST Framework and Django OAuth Toolkit Authentication
I have followed through the documentation on how to integrate both the REST framework and OAuth Toolkit, but when I run a request with a token I receive: {"detail":"Authentication credentials were not provided."} Here is my REST settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'PAGE_SIZE': 20 } An example view: class GroupViewSet(viewsets.ReadOnlyModelViewSet): authentication_classes = [OAuth2Authentication] queryset = Group.objects.all() serializer_class = GroupSerializer permission_classes = [TokenHasScope] required_scopes = ['read', 'groups'] And I do have 'oauth2_provider' in my INSTALLED_APPS. I'm able to request and receive tokens without issue. It's only when I use them that I get the above error. -
Django. Price not saving when I call save() method
I have a model: class ProductSet(models.Model): """Set of some products""" price = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) set_products = models.ManyToManyField(SetProduct, related_name='set', verbose_name='Товары набора') def save(self, *args, **kwargs): """If a total price for that product set isn't defined, save it as a sum of the set products total_price """ if not self.price: super().save(*args, **kwargs) self.price = sum([set_product.total_price for set_product in self.set_products.all()]) super().save(*args, **kwargs) The first save calling for saving "set_products" many-to-many relationship. The second save expression for saving a new self.price. But that's doesn't work, a price was saved only after I double-clicked to the django admin save button. What's the reason and how I can solve it? P.S SetProduct: class SetProduct(models.Model): """Product in ProductSet""" product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Товар', related_name='product_sets') count = models.PositiveSmallIntegerField('Количество', default=1) actual_price = models.DecimalField('Актуальная цена', max_digits=7, decimal_places=2, blank=True, null=True) def save(self, *args, **kwargs): """If an actual price isn't defined, set it as the product.price_with_discount""" if not self.actual_price: self.actual_price = self.product.price_with_discount super().save(*args, **kwargs) @property def total_price(self): return self.actual_price * self.count -
Django admin history Custom view
I'm new to django & I'm trying to add a custom History view along with SimpleAdminHistory. The SimpleAdminHistory is working fine but the 2nd url that I'm adding is not working saying dragon with ID "1220/default_history" doesn't exist. Perhaps it was deleted? Without any errors. History Class In the following class I'm trying to add a class that extends SimpleHistoryAdmin (which extends model.AdminModel), and what I'm trying to do is add a new url which when accessed should hit default_history_view method. The problem is when I hit the url http://127.0.0.1:8000/admin/dragon/1220/default_history/ it's not hitting that method at all whereas http://127.0.0.1:8000/admin/dragon/1220/history/(SimpleAdminHistory method) works perfectly. class TestClass(SimpleHistoryAdmin): history_list_display = ['changed_fields'] # pylint: disable=no-self-use def changed_fields(self, obj): """Add changed fields to changed_fields column in History.""" if obj.prev_record: delta = obj.diff_against(obj.prev_record) return delta.changed_fields return None def get_urls(self): urls = super(GenericClass, self).get_urls() admin_site = self.admin_site opts = self.model._meta info = opts.app_label, opts.model_name history_urls = [ url( "^([^/]+)/default_history/$", admin_site.admin_view(self.default_history_view), name="%s_%s_history" % info, ), url( "^([^/]+)/history/([^/]+)/$", admin_site.admin_view(self.history_form_view), name="%s_%s_simple_history" % info, ) ] return urls + history_urls def default_history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." # First check if the user can see this history. print(object_id) model = self.model obj = self.get_object(request, unquote(object_id)) if obj … -
making a foreignkey not required
I have these 2 models: # core/models.py Class Certificate: user = models.Foreignkey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='certificates') name = models.Charfield() . . # users/models.py Class User(AbstractBaseUser): . . and I want to send the certificates of a user along with its other pieces of information. this is my serializer: # users/serializers.py class CertificationSerializer(serializers.ModelSerializer): """Serializer for the certificate object""" class Meta: model = Certificate class UserSerializer(serializers.ModelSerializer): """Serializer for the user object""" # TODO # videos = serializers.PrimaryKeyRelatedField( # many=True, # queryset=Tag.objects.all() # ) certificates = CertificationSerializer(many=True) class Meta: model = get_user_model() # TODO add certificates and videos fields = ('id', 'email', 'password', 'first_name', 'last_name', 'phone_number', 'credit', 'points', 'certificates') extra_kwargs = {'password': {'write_only': True, 'label': 'گذرواژه', 'min_length': 5}} read_only_fields = ('id', 'certificates',) def create(self, validated_data): """Create a new user and return it""" return get_user_model().objects.create_user(**validated_data) def update(self, instance, validated_data): """Update a user and return it""" password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user now when I want to create a new user it tells me that field certificates can not be empty, how can I make the certificates field not required? -
Keep retrying Celery task and only move on if task succeeds or max retries reached
I have a Celery task that retries on failure with exponential backoff. This task POSTs messages received by a Django application (call it "transport") to a second Django application (call it "base") for processing. These messages have to be processed in order, and so the order in which the tasks are queued must be maintained. However, when a task fails (because transport cannot connect to base for whatever reason), it is relegated to the back of the queue, which is obviously an issue. Is it possible to "block" a Celery queue, ie. to keep retrying the same task until it either succeeds or reaches the max retries threshold, and only then move to the next task in the queue? In my case I need the task at the head of the queue to keep trying that POST until it can't anymore, and under no circumstances should the order of tasks in the queue be changed, though I'm not sure if this can be done with Celery (and if so, how). I've come across this previous question which seems to describe a very similar problem, but it's not fully relevant to my use case. -
Direct assignment to the forward side of a many-to-many set is prohibited. Use foods.set() instead in django
I have this view: @login_required def addmeal(request): if request.method == 'POST': form = addMeal(user=request.user, data=request.POST) if form.is_valid(): form.save(request) return redirect('food:index') else: form = addMeal(user=request.user) return render(request,'addmeal.html',{'form':form}) and this form: class addMeal(forms.Form): name = forms.CharField( max_length=40, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'نام وعده'}) ) foods = forms.ModelMultipleChoiceField( queryset=Food.objects.none(), widget=forms.SelectMultiple(attrs={'class':'form-control'}) ) def save(self,request): data = self.cleaned_data meal = Meals(name=data['name'],user=request.user,foods=data['foods']) meal.save() def __init__(self, user=None,*args, **kwargs, ): super().__init__(*args, **kwargs) if user is not None: self.fields['foods'].queryset = Food.objects.filter(user=user) class Meta: model = Meals when i run server and fill out form and press submit django give me error(Direct assignment to the forward side of a many-to-many set is prohibited. Use foods.set() instead.). what should i do to fix it? -
insert selected multiple record in foreign-key
I have four models shop, product, customer, order. following are shop class Shop(models.Model): user = models.OneToOneField(User, null=True, related_name='shop', blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=70, null=True, default='shop', ) address = models.CharField(max_length=70, null=True) customer class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, default='customer') Phone = models.PositiveIntegerField(blank=True, null=True) product class Product(models.Model): shop = models.ForeignKey(Shop, models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, blank=True) Brand = models.CharField(max_length=200, blank=True) order class Order(models.Model): shop = models.ForeignKey(Shop, models.CASCADE, null=True) customer = models.ForeignKey(Customer, models.CASCADE, null=True) product = models.ForeignKey(Product, models.CASCADE, null=True) quantity = models.CharField(max_length=30) In order I want to insert the selected n.product but shop and customer is same that shown in the image how I can do this when user.customer login then on the home page shop will print when and they select shop after selecting the shop, product by the shop will be the print after submitting selected product with the remaining filed will print -
Update SetupProxy target dynamically
I am developing a tenant application with Django backend and React.js as a frontend framework. And using http-proxy-middleware to proxy the request to backend server. For different kind of tenants we need to update target value of createProxyMiddleware dynamically. Typically we can use const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function(app) { app.use( '/api', createProxyMiddleware({ target: 'http://t1.demo.local:8000/', changeOrigin: true, secure: false }) ); }; Here i want to update target dynamically for different tenant client. How i can achieve that. Thanks a lot for reading -
RedirectView to external site. How to append parameters?
I would like to redirect from my page to external site. This external site address is defined and never changes... And I can implement it... The challenge comes from: I have a form, which posts Q into my view function, which gives final string of parameters to pass into the pattern of url supposedly attached to the main address of this external web site after the ? mark... I just cannot find the information how to pass and attach this string to a given url. Somehow it's difficult for me, please don't judge too harsh. Parameter is only one, it is a string, which formed in view function. I use RedirectView in urls.py: path('do_request/found/', RedirectView.as_view(url='https://docs.djangoproject.com/'), name='found_objects'), In views.py (there are probably some mistakes, but it's just for the purpose of the question): class UserFoundRequestView(TemplateView): model=ForQuery template_name='found_objects.html' def get_results(self, request): our_queries = ForQuery.objects.all() query=self.request.GET.get("q") if query: our_object=ForQuery.objects.filter(query_id__iexact=query) for x in our_queries: if x.query_id == our_object.query_id: name = x.dep_station #context = { # 'name' : name, #} return name def get_string(request): base_url = 'https://stackoverflow.com/' query_name = get_results() query_string = urlencode(query_name) url = '{}?{}'.format(base_url, query_string) return redirect(url) Thank you for the help! -
Self Signed Certificate Not Working - Invalid Certificate
I am following a Django book and trying to do social authentication. I've installed PythonSocial, Edited the hosts file and added 127.0.0.1 mysite.com. Also, I've installed django-extensions, werkzeug, pyOpenSSL adn added django-etensions to installed apps. When I tried to enter the site it is showing an insecure connection and I've added the certificate been shown first to the Trusted Root Certificates. When I click the certification and go to the certification path it is showing certification staus is ok but at the start when I click the red caution icon sort of it shows certificate is invalid. Please Help -
'attempt to write a readonly database' meanwhile everything is 777?
I've set my database and it's parent folders to 777 for diagnosing. within /: drwxr-xr-x. 21 root root 4096 Jun 21 15:36 var within /var: drwxr-xr-x. 5 apache apache 49 Jun 21 15:42 www within /var/www: drwxrwxrwx. 7 apache apache 131 Jun 21 18:18 project within /var/www/project: -rwxrwxrwx. 1 apache apache 143360 Jun 21 18:18 db.sqlite3 But I'm still getting errors when apache tries to write to the database. Any idea? I'm obviously going to remove 777 once I figure out what's going on but I'm out of ideas for now. -
How can i serve static files in django without apache or ngingx
I have a folder static: static -->css ----> main.css -->images ----> image.png Settings.py: STATICFILES_DIRS=[ os.path.join(BASE_DIR, "static"), ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static_cdn") I ran collectstatic Now I have in static_cdn: images, css and admin(never saw this last one before). When I run my server, it still doesn't use static files. How can I serve my static files to my server without using apache or nginx or that kind of stuff? Thx for your help and stay healthy! -
How to change file browser button to image button by useing forms design in Django
I can create the following form: I'm thinking when I click on the image like this: -
Wagtail page editor is oversized
Something is causing the Wagtail page editor to go oversized. This is happening regardless of browser (chrome, safari, firefox). Not for all pages, just an occasional one. But once this happens to a page, it always happens for that page. Edit a page and reload the edit page (save draft, leave page editor and come back). As page components are loading, everything looks fine. However, at the end of the page load the editor portion grows in size. The object-layout div is the correct size: But the object-layout_big-part div is way too big: Any ideas on what could be causing things to grow in width like this? -
Django : Saving two different forms at the same time results two entries in the database
Here is my models.py file. class Individual(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) title = models.CharField(max_length=10, blank=True) first_name = models.CharField(max_length=255, blank=True) middle_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) phone_no = models.CharField(max_length=255, blank=True) payment = models.CharField(max_length=255, blank=True) def __str__(self): return self.user Here is my forms.py class UserRegisForm(ModelForm): email = forms.EmailField() password = forms.CharField() class Meta: model = CustomUser fields = ['email','password'] class IndividualForm(ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Title'})) first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'First Name'})) middle_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Middle Name'})) last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Last Name'})) phone_no = forms.CharField() payment = forms.CharField() class Meta: model = Individual fields = ['title','first_name','middle_name','last_name','phone_no','payment'] Here is my views.py @csrf_exempt def register(request): next = request.GET.get('next') if request.method == 'POST': form = IndividualForm(request.POST) form1 = UserRegisForm(request.POST) if form.is_valid() and form1.is_valid(): user = form1.save(commit=False) password = form1.cleaned_data.get('password') user.set_password(password) user.save() form.save() login(request, user) if next: return redirect(next) return redirect('existing_module_master') else: return redirect('/register', messages.error(request, 'Form is not valid', 'alert-danger')) else: form = IndividualForm() form1 = UserRegisForm() return render(request, "register.html", {'form':form, 'form1':form1}) And here is my register.html file, <html> <body> <form method="post"> {{form.as_p}} {{form1.as_p}} <input type="submit" formmethod="post"> </form> </body> </html> Gives me the following output.. that is, It insert the data in CustomUser first then it keep it blank in Individual. Then it insert again the value in the Individual … -
Django+Celery Module not found error with app installed from git
I'm have a project split on 2 separate apps and both have another shared app as reusable one(i store my models there and install it from git link. So when i run celery worker locally all is working perfect, but if i use docker(with celery in separate image) i got this error Error: celery_api | Unable to load celery application. celery_api | The module common was not found. In some reason celery gets improper configuration from django. celery docker config celery_api: image: celery_api container_name: celery_api restart: unless-stopped build: . command: celery worker -A djookyapi --loglevel=info env_file: - ./.dev.env volumes: - .:/usr/src/app working_dir: /usr/src/app networks: - dev celery file in the root of project folder(near settings.py file) __future__ import absolute_import, unicode_literals import os import sys from celery import Celery from django.conf import settings BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproj.settings') os.environ.setdefault('DJANGO_CONFIGURATION', 'Local') import configurations configurations.setup() app = Celery('myproj', ) # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings') # Load task modules from all registered Django … -
Use mounted Azure Blob Storage Container in Azure App Service
I was able to mount azure blob storage on my local machine (Ubuntu 18.04) using blobfuse, just as documented here. To use it in an Azure App Service I found this, describing an option to mount Azure Storage using the Azure Portal interface. This does it for me... But how can I access the mounted storage from within my Django app? Is the mounted Storage accessible as directory via the filesystem? -
if (cart[idstr] != undefined) got error in this line
I have an error in != undefined and inneerhtml if (cart[idstr] != undefined) name = document.getElementById('name' + idstr).innerHTML; -
Non-UTF-8 code starting with '\x90' - django
After installing the django package successfully for particular project in pycharm, while I am trying to startproject from pycharm terminal, it's giving below error: (venv) C:\Users\user123\PycharmProjects\>django-admin startproject mysite File "C:\Users\user123\PycharmProjects\project_name\venv\Scripts\django-admin.exe", line 1 SyntaxError: Non-UTF-8 code starting with '\x90' in file C:\Users\user123\PycharmProjects\1project_name\venv\Scripts\django-admin.exe on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details Do I need to make any changes in the installed package file to make it work? Please help.. -
Multiple Django servers to manage "collectstatic" to s3
I have two ec2 instances with Django and both of them set up Boto3, Django Storage, and Django Compressor packages to manage static files to upload to S3 bucket with some compressed files. Here I have a question. Do I need to execute collectstatic command at each server to upload static files and compressed files So that there are overwritten static files and two different compressed files created from different servers? Is this proper way of uploading static and compressed files from multiple servers? Or is there a better practice for this? -
How To Create A List Of Querysets
My Users take Classes (many-many) and classes have teachers (many-many). Im looping through a Users Classes and getting all the Teachers. I then store the Teachers Queryset in a variable. In my template I loop through my Classes and print the Class name, then within each Class I loop through and print the Teachers names. My problem is that the variable Im using to hold the Teachers is overridden every time my for loop loops. How can I store a list of Querysets which can be iterated in my template, printing the appropriate Teachers for each Class (this is my second problem, figuring out how to print the correct Teachers to match the Class)? users_classes = request.user.student.classes.all() for class in users_classes: teachers = class.teachers.all() {% for class in user.student.classes.all %} <h3 class="account-heading">{{ class.name }}</h2> {% for teacher in context.teachers %} <tr> <td>{{ teacher.name }}</td> </tr> {% endfor %} {% endfor %} Thank you. -
Unable to import 'django.urls'
Help please! am new to django please i have installed django in virtual environment i created on my desktop. but whenever i create a django project and open up the folder in vs code in the url.py file and the wsgi.py files there is a red underline in the import statements. and when i hover over it it says unable to import the package name this is from the wsgi.py file. it says unable to import django.core.wsgi i have not written any code so there are no errors yet but vscode shows a red underline on the from import statements from django.core.wsgi import get_wsgi_application also in the urls.py file it does the same thing from django.contrib import admin from django.urls import path i have tried uninstalling and installing django again but it didn't work. it still does the samething ps. i have not written any code in the django project prior to this but no doubt this will surely give me an error