Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django using an Integerfield for sorting
I have a model which has an IntegerField. this field may change after creation of object. I wanna use it for the "trend" part in my project, like those objects with the larger number must shown at top. so what is the best way (efficient) to do this. my current idea is: class Map(models.Model): rank = models.IntegerField() and later use it like this: sorted_list = Map.objects.order_by("-rank")[:50] is this a good idea even if there are many requests for the trend page? -
Users gets an Qr code with link to django webpage with login required
My problem: A user gets an email with qrcode, the qrcode links to a website. But when the user is not logged in he cant reach the linked site (because of the login requirement). When the the user is logged in there is no problem, after scanning the qr he gets to the site. How can i make it user friendly when the user is NOT logged in. User gets qrcode, scans it and gets the login page of django. After logging in i want him to direct to the qr link directly. Is that possible ? Normally i post code, hower in this case i dont have any because the login proces is the standard one of django, and the qr link is just a decoded http link. -
I have difficulties saving the form data after form submission django
I have a form where user can create a team. But, somehow the form data never saved on the db after submission. The form page just refresh and return the form with the filled data. This happen to any form that I created for the project. I feel too confused as I tried every possible way I can think of, but to no avail. Any help could be appreciated. The model #model class Team(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True, blank=True) logo = models.ImageField(default='team.png', upload_to='teams_pic/') bg_img = models.ImageField(default='team_bg.png', upload_to='teams_pic/') cups = models.IntegerField(default=0) coach = models.ForeignKey(Profile, related_name="coach", on_delete=models.CASCADE) birth = models.IntegerField(blank=True) country = CountryField() state = models.CharField(max_length=100, choices=STATE_CHOICES) lga = models.CharField(max_length=100, choices=LGA_CHOICES) town = models.CharField(max_length=200, blank=True) creator = models.ForeignKey(Profile, related_name="creator", on_delete=models.CASCADE) fb = models.URLField(max_length=500, blank=True) tweet = models.URLField(max_length=500, blank=True) insta = models.URLField(max_length=500, blank=True) players = models.ManyToManyField(Profile, related_name='players', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) objects = TeamManager() def __str__(self): return str(self.name) class Meta: ordering = ('-created',) def get_absolute_url(self): return reverse('sport:team-detail-view', kwargs={'slug': self.slug}) __initial_name = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__initial_name = self.name def save(self, *args, **kwargs): ex = False to_slug = self.slug if self.name != self.__initial_name or self.slug == "": if self.name: to_slug = slugify(str(self.name)) ex = Team.objects.filter(slug=to_slug).exists() while … -
Why is Django not finding static files on S3?
I followed this tutorial in order to make Django use S3 when loading static files https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ When I try to upload new media files through my webapp they get uploaded directly on S3. However, when I try to load static files in my html templates and I inspect the links, those are still linked to my local drive. Why is Django not looking at S3 for static files in my case? settings.py: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME= "eu-central-1" AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3-website.{AWS_S3_REGION_NAME}.amazonaws.com' STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # STATICFILES_STORAGE = 'custom_storages.StaticStorage' MEDIAFILES_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' AWS_LOCATION = 'static' AWS_S3_FILE_OVERWRITE = False AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_DEFAULT_ACL = 'public-read' navbar.html: {% load static %} ... <img src="{% static '/images/logo1.png' %}" > When I reload and inspect my webpage I still see <img src="/static/images/logo1.png"> instead of a link to AWS. -
Django nested serialization is not serializing on read
I know this issue is pretty popular but can't figure this out. class SpaceTypeSerializer(serializers.ModelSerializer): class Meta: model = SpaceType fields = ['id', 'company_id', 'label', 'value', 'active'] class SpaceSerializer(serializers.ModelSerializer): class Meta: model = Space # space_type = serializers.PrimaryKeyRelatedField( # queryset=SpaceType.objects.all()) space_type = SpaceTypeSerializer(read_only=True) fields = ['id', 'location_id', 'name', 'description', 'active', 'space_type', 'group_reservations_active', 'seats'] I'm getting just the id for the space_type field. I tried the commented out part and get the exact same result. class Space(Model): location = ForeignKey( Location, on_delete=DO_NOTHING, blank=False, null=False, related_name='spaces' ) name = CharField(max_length=255) description = TextField(null=True) active = BooleanField(default=True) space_type = ForeignKey( SpaceType, on_delete=DO_NOTHING, blank=True, null=True, related_name='spaces' ) Here's my model. Not sure what else to try but I want my space_type to have the entire space type object serialized. Here's my query: def get(self, request, pk, format=None): space = Space.objects.select_related('space_type').get(pk=pk) serializer = SpaceSerializer(space) return Response(serializer.data) Not sure if i need the select_related in there but putting it in for verification purposes. -
IntegrityError at /profile NOT NULL constraint failed: tutorapp_profile.user_id
I am making a app for finding tutors where tutors need to log in and post their jobs in the web application. While developing the profile section for tutors, i am unable to add a feature of updating or uploading a new profile bio and profile picture. I'm new to django Here is my model of Profile in models.py class Profile(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE) image= models.ImageField(default = 'default.jpg',upload_to='profile_pics') bio=models.CharField(default = 'no bio',max_length=350) def __str__ (self): return f'{self.user.username} Profile' and its model form class UpdateProfile(forms.ModelForm): class Meta: model = Profile fields =['image','bio',] def clean(self): super(UpdateProfile, self).clean() return self.cleaned_data view of profile views.py def profile(request): if request.method == 'POST': p_form = UpdateProfile(request.POST, request.FILES) if p_form.is_valid(): p_form.save() return redirect('profile') else: p_form = UpdateProfile() context = { 'p_form': p_form } return render(request,'profile.html',context) urls.py urlpatterns = [ path('', views.index, name='index'), path('home', views.index, name='home'), path('signup', views.signup, name='signup'), path('postskill', views.postskill, name='postskill'), path('profile', views.profile, name='profile'), ] template of profile.html <img class="rounded-circle account-img" src="{{user.profile.image.url}}" height="100" width="100"> <h5> First Name: {{user.first_name}} </h5> <h5> Last Name: {{user.last_name}} </h5> <h5> Username: {{user.username}} </h5> <h5> Email: {{user.email}} </h5> <p> Bio: {{user.profile.bio}} </p> <button class="btn btn-primary" onClick="myFunction()"> UpdateProfile</button> <div id ="hide"> {% csrf_token %} <form method = "POST" enctype="multipart/form-data"> {% csrf_token %} {{ p_form|crispy … -
Django Multiple File Upload in UpdateView - not getting file information using request.FILES.getlist
I'm trying to get multiple file uploads working in my Django app. forms.py: from django.forms import ClearableFileInput class CountForm(forms.ModelForm): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) class Meta(): model = Count ... views.py: class count_modal(UpdateView): model = Count form_class = CountForm template_name = 'count_modal.html' pk_url_kwarg = 'count_id' def get_form_kwargs(self): kwargs = super(count_modal, self).get_form_kwargs() return kwargs def form_valid(self, form): obj = form.save() print(self.request.FILES.getlist('file_field')) ... My template is a generic form using enctype='multipart/form-data'. When I try to print out the file upload, it always comes up with an empty list. I'm planning to upload this to a different model, but for now I'm just trying to get the files in my view. -
Unable to resolve ModuleNotFoundError when deploying a Django App on Heroku
I keep getting the following error in my logs when I try to deploy my app on Heroku: 2021-03-16T19:03:43.053580+00:00 heroku[web.1]: Starting process with command `gunicorn todo.wsgi:application` 2021-03-16T19:03:46.709810+00:00 app[web.1]: [2021-03-16 19:03:46 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-03-16T19:03:46.711200+00:00 app[web.1]: [2021-03-16 19:03:46 +0000] [4] [INFO] Listening at: http://0.0.0.0:14087 (4) 2021-03-16T19:03:46.714536+00:00 app[web.1]: [2021-03-16 19:03:46 +0000] [4] [INFO] Using worker: sync 2021-03-16T19:03:46.720381+00:00 app[web.1]: [2021-03-16 19:03:46 +0000] [9] [INFO] Booting worker with pid: 9 2021-03-16T19:03:46.726148+00:00 app[web.1]: [2021-03-16 19:03:46 +0000] [9] [ERROR] Exception in worker process 2021-03-16T19:03:46.726159+00:00 app[web.1]: Traceback (most recent call last): 2021-03-16T19:03:46.726161+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2021-03-16T19:03:46.726163+00:00 app[web.1]: worker.init_process() 2021-03-16T19:03:46.726164+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process 2021-03-16T19:03:46.726164+00:00 app[web.1]: self.load_wsgi() 2021-03-16T19:03:46.726164+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2021-03-16T19:03:46.726165+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-03-16T19:03:46.726166+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-03-16T19:03:46.726167+00:00 app[web.1]: self.callable = self.load() 2021-03-16T19:03:46.726167+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2021-03-16T19:03:46.726167+00:00 app[web.1]: return self.load_wsgiapp() 2021-03-16T19:03:46.726168+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2021-03-16T19:03:46.726168+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-03-16T19:03:46.726169+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app 2021-03-16T19:03:46.726169+00:00 app[web.1]: mod = importlib.import_module(module) 2021-03-16T19:03:46.726170+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2021-03-16T19:03:46.726170+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-03-16T19:03:46.726170+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import 2021-03-16T19:03:46.726171+00:00 app[web.1]: File "<frozen importlib._bootstrap>", … -
Django Project ||Create a Signup module. . The user will get registered once the admin will approve it
Create a Signup module. Users will be required to register themself in the application. The user will get registered once the admin will approve it. -
Django celery[redis] is not working ! plz help me :(
I use DRF because Build API Server, When Clients register my app, I send register email to client, My Settings Window 10 Django 3.1.7 Python 3.8.7 pip install celery[redis] Here is my Code Tree Photo here Here is My Code celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.prod') app = Celery('config') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') __init__.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) task.py from django.core.mail import EmailMessage from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode from django.utils.encoding import force_bytes from django.contrib.auth import get_user_model from celery import shared_task from .tokens import account_activation_token User = get_user_model() @shared_task def task_send_email(user_pk, validated_data): user = User.objects.get(pk=user_pk) message = render_to_string('accounts/account_activate_email.html', { 'user': user, 'domain' : 'localhost:8000', 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user) }) mail_subject = 'Hello' to_email = validated_data['email'] email = EmailMessage(mail_subject, message, to=[to_email]) email.send() serializers.py def create(self, validated_data): user = User.objects.create(**validated_data) user.set_password(validated_data['password']) user.save() # Celery - Send Eamil task_send_email.delay(user.pk, validated_data) # Here!! Not Working T_T EmailSendHistory.objects.create( email_address = user.email, ) return user I try to redis-server celery -A config worker -l info python manage.py runserver I'm looking forward to sending an e-mail when I sign up for membership. However, … -
Django relation "users_driverregistration" does not exist
I changed django models ande deployed new version to the server. In admin page I see an error relation "users_driverregistration" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "users_driverregistration" I tried to update database via python3 manage.py makemigrations python3 manage.py migrate But received error File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/usr/local/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 112, in database_forwards field, File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 447, in add_field self.execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 137, in execute cursor.execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/usr/local/lib/python3.7/site-packages/sentry_sdk/integrations/django/__init__.py", line 467, in execute return real_execute(self, sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, … -
How does postgreSQL structure Django Array Fields in database
How does PostgreSQL structure an ArrayField like: class House(models.Model): people_ids = ArrayField(models.IntegerField(), default=list, blank=True) in database? Does it generate an auxiliary table with the numbers as Ids and then another table with the Id pairs? Like: House Id Name 1 MyHouse People Id 1 2 House_People House_Id Person_Id 1 1 1 2 So as to have, for example, people 1 and 2 in house "MyHouse"? -
django auto login after UserCreationForm
I'm using one function to sign up and sign in user. The sign-in is working smoothly, however, when the user is registered it doesn't automatically login into his dashboard. Any suggestions? Thank you. form: class SignUpForm(UserCreationForm): class Meta: model = User fields = ('email','username','password1','password2',) labels = { 'email' : 'Email address', } .view: def index(request): # SIGN UP form = SignUpForm() login_form = CustomAuthForm() if request.method == "POST": if request.POST.get('submit') == 'sign_up': form = SignUpForm(request.POST) if form.is_valid(): auth.login(request) form.save(); messages.success(request, "Successfully registered.") return redirect("dashboard") elif request.POST.get('submit') == 'sign_in': #Log in login_form = CustomAuthForm(data = request.POST) if login_form.is_valid(): username = login_form.cleaned_data.get('username') password = login_form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.success(request, "Successfully logged in.") return redirect('dashboard') else: messages.success(request, "Error credentials.") else: messages.success(request, "Error.") return render(request, 'index.html', context={'form':form,'login_form':login_form}) -
Django Image is not added to media folder
So the thing is that in production code with media files is not working (image of model is not added there). If you need some details please write! Thank you for your help ) project configuration <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For … -
What are the methods for working with a self-referential model in a Django view?
I'm creating a virtual library in Django 3.1.5 and would like to show users books based on subjects that the books and users have in common. To make this a bit more powerful I plan on using a self-referential subject model. This will allow me to do a lot of things like suggest or show related books to users (e.g. I can show a user who's related to the subject Programming books that are relevant to Python, Django and Flask even though the user isn't related to those subjects directly), or create a dynamic library filter. Here are the subject fields that I have in my model: class SubjectType(models.Model): name = models.CharField(max_length=35) def __str__(self): return self.name class Subject(models.Model): name = models.CharField(max_length=255) subject_type = models.ForeignKey(SubjectType, on_delete=models.PROTECT) children = models.ManyToManyField("self", blank=True, related_name="parents", symmetrical=False) def __str__(self): return self.name My problem is that I'm fairly new to all of this, and while I've come across quite a bit of information regarding setting up self-referential models, I'm having a bit of trouble finding the right combination of QuerySet and view methods for efficiently querying such a model. And I would appreciate it if anyone could point me in the right direction. E.g.: How might I … -
When a registered user tries to add a product in cart it says Internal Server Error: /update_item/
When a guest user adds a products it works fine but when a registered user tries to add product in the cart it gives a error. Internal Server Error: /update_item/ Traceback (most recent call last): File "C:\Users\varuni\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\varuni\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\varuni\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: updateItem() missing 1 required positional argument: 'customer' Here is my updateItem in views.py: def updateItem(request, customer): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action: ',action) print('productId: ',productId) product = Product.objects.get(id = productId) order, created = Order.objects.get_or_create(customer = request.user.customer, complete= False) orderItem, created = OrderItem.objects.get_or_create(order= order, product= product) if action=='add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove' : orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('item added', safe=False) this is my store.html where the action of add to cart button is defined: {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> {% for prod in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{prod.imageURL}}"> <div class="box-element product"> <h6><strong>{{prod.name}}</strong></h6> <hr> <button data-product={{prod.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> <a class="btn btn-outline-success" href="#">View</a> <h4 … -
Django - customized ModelAdmin to show ManyToMany filtered view (vetical or horizontal) by related fields filters
I have a Model with a field: class SampleModel(models.Model): questions = models.ManyToManyField('questions.Question') 'Question' objects do have some simple foreign keys like Department or Organisation (with their corresponding 'name' fields). Could somebody point me a direction how to achieve the following: i'd like to have in Admin of "SampleModel" a way to filter these questions list by their related fields (department, organisation). I've seen some examples that should work for simple foreign keys, but nothing works for ManyToMany. Is there eventually any addon with similar funcionality? -
Psycopg2 installation error on mac: command 'clang' failed with status 1
I can't install psycopg2 on my m1 Mac. I tried to reinstall openssl with brew. I tried a lot of thing but nothing changed. The error log is super long so I couldn't understand what is wrong. I am facing up with this error when I try to pip install psycopg2 Waiting for your help. Here is the full error log: https://wtools.io/paste-code/b4jG -
Geodjango | 'DatabaseOperations' object has no attribute 'geo_db_type'
I am building a BlogApp . AND I am stuck on an Error. What i am trying to do I am making a Location Based BlogApp and I am using PointField in models. The Problem 'DatabaseOperations' object has no attribute 'geo_db_type' This error is keep showing when i migrate. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '---------', 'HOST': 'localhost', 'PORT': '', } } What have i tried I also tried chaning 'django.db.backends.postgresql_psycopg2' to 'django.contrib.gis.db.backends.postgis'. BUT it is showing django.db.utils.OperationalError: could not open extension control file "C:/Files/PostgreSQL/13/share/extension/postgis.control": No such file or directory I also tried many answers but nothing worked for me. I have installed pip install psycopg2. -
% being appended to existing % in django template
I am developing a django based web application. I use django templates in html. There is a form containing textbox where i enter a value with % symbol But i notice that the post request converts the text box value to this format below txtBillingAccName=Billing+Account+25%25 Due to this the values get saved in the database like this: I need to use % symbol for most of the Billing Account Names. Can anyone please help me,how to solve this?. Thanks -
No route found for path in Django-channels
Using django channels im trying to connect to a websocket but it can't find it. I tried to see if its because of routing.py or consumer.py and i can't find the answer. I get the warning that no route was found for path 'tribechat/1/'. git error message: Traceback (most recent call last): File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\security\websocket.py", line 37, in __call__ return await self.application(scope, send, receive) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\sessions.py", line 254, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\auth.py", line 181, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\routing.py", line 168, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'tribe_chat/1/'. Console error message: WebSocket connection to 'ws://127.0.0.1:8000/tribe_chat/1/' failed: routing.py: from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.urls import path, re_path from tribe_chat.consumers import TribeChatConsumer application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ re_path(r'ws/tribe_chat/(?P<room_id>\w+)/$', TribeChatConsumer.as_asgi()), ]) ) ), }) consumers.py: from channels.generic.websocket import … -
Django, get value from url after "#"
I have a callback endpoint in my Django app And on this callback endpoint comes such request http://127.0.0.1:8000/callback/#state=cc444d19-bd8c-4b4c-8011-1054fd0e8e73&session_state=8776a4ca-033b-469e-8a50-81f90c81c5ef&code=7ade58cf-d6ed-4c20-8d8c-33453c37c44e.8776a4ca-033b-469e-8a50-81f90c81c5ef.913199c3-a793-4f5a-ac36-b4c105a08000 How can I get values that comes after "#"? -
Can't upload files larger than 2mb from Angular to Django rest framework
I want to be able to upload audio files of any size from an Angular website to Django backend. At the moment i am able to upload small files up to ~2mb without any problems, however, when uploading files larger than 2mb the Django function that handles the file upload doesn't fire, and no errors occur in Angular frontend. Angular uploadFile() { this.subscription = this.ApiService.uploadfile(this.fileToUpload,this.myControl.value).subscribe(data => { this.UtilsService.openSnackBar('Successfully added wavs',this.myControl.value) // do something, if upload success alert("success") }, error => { //console.log(error); alert("error") }); this.dialogRef.close(); } Upload function of ApiService, sends some parameters along with file(s) uploadfile(file,inst_label):Observable<any>{ const formData: FormData = new FormData(); for(let i = 0; i < file.length; i++){ if(i==0){ formData.append(inst_label,file[i],file[i].name) } else{ formData.append(i.toString(),file[i],file[i].name) } } return this.http.post(this.baseurl + '/upload_files', formData); } On my settings.py i have set: FILE_UPLOAD_MAX_MEMORY_SIZE = 5000000000 # 50 MB DATA_UPLOAD_MAX_MEMORY_SIZE = 5000000000 # 50 MB FILE_UPLOAD_PERMISSIONS = 0o644 Lastly my function upload_files in views.py prints something when files are less than 2mb, if the files are >2mb nothing happens. Hope i was clear enough, i'm running out of ideas on what to do besides cut those large files to smaller ones before uploading. -
Setting Default Image Dynamically Based On Model Choice - Django
Say I have a class: imageModel(models.Model): O1 = 'Option1' O2 = 'Option2' CHOICES = ( (O1, 'Option1'), (O2, 'Option2'), ) options = models.CharField(max_length=50, choices=CHOICES) image = models.ImageField() How would I dynamically set the default for the image field based on the option choice? I tried something like: imageModel(models.Model): O1 = 'Option1' O2 = 'Option2' CHOICES = ( (O1, 'Option1'), (O2, 'Option2'), ) options = models.CharField(max_length=50, choices=CHOICES) image = models.ImageField() def get_default_image(self): super().save() img = Image.open(self.company_logo.path) if self.options == "Option1": img.default = "/static/img/option1img.jpg" elif self.options == "Option2": img.default = "/static/img/option2img.jpg" img.save(self.image.path) But that didn't work. -
Send api request every x minutes and update context with status
I am trying to make a website, where user can start a task on a button click, which will send an api request every x seconds/minutes. Api request gets a list of offers as a response and the task will check if the api request is the same as before. If it is then then i want to show status on my page as: "No offers were found, still searching" and if the api response is different the status changes to: "I found an offer" I wanted to make that process in the background and without need to refresh the page by user. I want the context["status"] to be automatically updated when new offer is found. I tried to achieve this with threading but the page keep on loading as a task is working. Every idea is appreciated. Thanks!