Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use phone number / sms token instead of username password in django
I'm new to django and I'm developing a website with django, but I want to have a custom flow for register/login instead of django's default, as described below: When a user want to login/register redirects to a form that only have one field "phone number" and a submit button in the next page if the phone is belongs to a registered user, user receive a token via SMS and enter it to complete login. and if the phone isn't found, redirects to a form to receive user's information such as first/last name and SMS token to complete registering user. I know I need custom forms and custom user model, but I don't know how to implement this. Do I need to subclass my custom user model from django's AbstractUser or AbstractBaseUser? Do I need to use any plugin? Should I write a custom authentication backend? what should I do, if i want to differ between staffs and customers. So staff should login with username/password and customers use system described. I browsed some topics and tutorial about django user system and official document of django, but I feel confused and can't find my way. -
Djanog statics are not loading
I'm trying to run my Django project on localhost server (with runserver command) but my css files are not loading with the error : Refused to apply style from 'http://127.0.0.1:8000/statics/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. I've setup STATIC_URL = 'static/' STATIC_ROOT= BASE_DIR / 'static' MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media' STATICFILES_DIRS = [ BASE_DIR / "statics/css/", ] in settings.py file and put my css files in BASE_DIR / statics/css/ but still I've got the error I also added these setting to the url pattern in urls.py file: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
i want to send mail to forget password in django
my views.py def ForgetPassword(request): try: if request.method=="POST": username=request.POST.get('username') if not User.objects.filter(username=username).first(): messages.success(request,'not user found with this username') return redirect('forget-password/') user_obj=User.objects.get(username=username) token=str(uuid.uuid4()) send_forget_password_mail(user_obj,token) messages.success(request,'An email is sent') return redirect('/forget-password/') except Exception as e: print(e) return render(request,'forget-password.html') helpers.py def send_forget_password_mail(email, token): subject="your forget password link" message=f'hi, click on the link to rest your password http://127.0.0.1:8000/change-password/{token}/' email_from=settings.EMAIL_HOST_USER recipient_list=[email] send_mail(subject,message, email_from, recipient_list) return True i have created a function which will send mail if anyone click on forget password but email is not sending. -
Django Email doesn't render HTML tags
I am trying to make an email notification system using Django, but there's a problem. The body of the email doesn't render html tags, and instead the body display the html tag and the message in a long line instead. Even when the message contains \n, it doesn't create a new line but the \n is not visible in the body of the email This is my email template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{subject}}</title> </head> <body> {{body}} </body> </html> This is my code to send the email from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags from django.conf import settings class SendNotification: @staticmethod def by_email(instance): subject = instance.subject to = list(instance.receivers.values_list("to", flat=True)) html_content = render_to_string("email.html", {'subject': subject, "body": instance.message}) text_content = strip_tags(html_content) try: email = EmailMultiAlternatives( subject, text_content, settings.EMAIL_HOST_USER, to, ) email.attach_alternative(html_content, 'text/html') email.send() instance.counter += 1 instance.save() instance.receivers.all().update(status=True) any idea why the html tag is not rendered properly? -
Simple Example of Multiple ManyToMany Model Relations in Django
I'm writing a workout app and have a number of models that need to link together. Specifically, I have an Exercise model that needs to track the name of each exercise as well as the primary and secondary muscle groups targeted by the exercise. I also need a muscle group model, and these all need to link together in a ManyToMany fashion, e.g. any muscle group be associated with the primary and/or secondary or multiple exercises and vice versa. How do I write the code to define the classes, as well as write a script to populate the database and test how to access various fields? Answered below as hopefully a useful super intro tutorial for others since I couldn't find something so easily online. -
Is Django_daraja currently missing some classes ? I can't get it to work
I've already installed django_daraja via pip on the environment and it's still invisible, to the project. Even on the setting file, I've included it and it's still fairing of poorly. I added all the necessary applications It's still being seen as an unsolved reference. -
How can I enter the time at 24:00 in timeFiled
I am booking a stadium at a specific time And everything is correct But when I enter the from_hour or to_hour to time(24:00) it prompts an error the erorr is (Cannot use None as a query value) class OpeningHours(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) pitche = models.ForeignKey(Pitche,on_delete=models.DO_NOTHING) made_on = models.DateField() from_hour = models.TimeField() to_hour = models.TimeField() timing = models.CharField(max_length=50,choices=timing) def clean(self): if self.from_hour == self.to_hour: raise ValidationError('Wrong Time') if self.made_on < datetime.date.today(): raise ValidationError('InVaild Date') if ( OpeningHours.objects.exclude(pk=self.pk) .filter( made_on=self.made_on, pitche_id=self.pitche_id, to_hour__gt=self.from_hour, from_hour__lt=self.to_hour, ) .exists() ): raise ValidationError( f'The booked time ({self.from_hour} to {self.to_hour}) is occupied.' ) return super().clean() -
How to Implement Two-Factor Authentication (2FA) in a Django Web Application?
I'm working on a Django web application and want to enhance security by adding Two-Factor Authentication (2FA) for user logins. I've looked into various libraries and approaches, but I'm not sure which one is the most reliable and secure for my project. Can someone provide guidance on how to implement 2FA in a Django application? What libraries or methods are recommended for this purpose? Thanks! -
Uploading multiple images no longer working after updating from django 3 to 4
I have a Django project I recently updated to version 4.2 I am experiencing an issue where a ClearableFileInput i had that allowed a user to upload multiple images no longer works throwing the error ValueError: ClearableFileInput doesn't support uploading multiple files. I have looked at the updated documentation and it seems multiple has changed to allow_multiple_selected however when i use this like 'images': forms.ClearableFileInput(attrs={'allow_multiple_selected ': True}), I am only able to upload only a single image. form: class PostImagesForm(ModelForm): class Meta: model = PostImages fields = ('images',) widgets = { 'images': forms.ClearableFileInput(attrs={'allow_multiple_selected ': True}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['images'].required = False view: @login_required def createPostView(request): postForm = PostForm() if request.method == 'POST': postForm = PostForm(request.POST, request.FILES) postImages = PostImagesForm(request.POST, request.FILES) #has to be 21 as it includes the cover img if len(request.FILES.getlist('images')) >= 21: messages.error(request, 'More than 20 image gallery images uploaded') return render(request, 'blog/post_form.html', {'postForm': postForm, 'PostImagesForm':PostImagesForm}) for image in request.FILES.getlist('images'): if image.size > settings.MAX_UPLOAD_SIZE: messages.error(request, f'Image gallery image {image} is too large 10mb max per image') return render(request, 'blog/post_form.html', {'postForm': postForm, 'PostImagesForm':PostImagesForm}) else: if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() if len(request.FILES.getlist('images')) == 0: return redirect('post-detail', PostFormID.pk , PostFormID.slug) else: for f … -
How to creating Django projeckt directory in VS-Code
enter image description hereI work with Git Bash, Python, Django in a virtual environment under VS-Code and I have such a problem. When I use the $ python -m django startproject mysite command in the djangogirls directory, two nested mysite directories are created under the djangogirls directory, see a picture. But I would need only one under the djangogirls directory. How should I do that ? everything I could think of -
Roadmap for me:provide feedback and insights please
I am 16 years old studying in college but also working on my skills.After much research i have created this roadmap for me.If you are an industry professional,please consider giving some words about this roadmap so i can have the relaxation that i am doing the right thing.Your feedback will matter a lot as you are in the tech industry so i will be highly grateful to you, this is the roadmap note that i am dedicating 1 hour daily to learning and i cannot give more due to my studies and also self learning is difficult: This is my roadmap: Basics and Intermediate Python(6 weeks) Scripting and Automation With Python (18 weeks learning from Automate the boring stuff with python's part 2 (automating tasks)) Advanced Python and Object Oriented Programming(8 weeks) Html css and basic Javascript(8 weeks) Intermediate Javscript and Reactjs(8 weeks) Sql with Postgresql and Git (8 weeks) Django Backend Development(12 weeks) How is this roadmap Provide feedback insights,do constructive criticism,whats wrong with it give some words about the syllabus do i need to adjust it like somthing before or after a thing I have completed the first phase and now i am in the second phase -
How to serve InMemoryStorage media files during Django tests
I have some Selenium-based integration tests (subclassed under django.contrib.staticfiles.testing.StaticLiveServerTestCase) for my Django app that require a functioning user-uploaded media configuration. I've been using S3 storage (django_s3_storage.storage.S3Storage from etianen/django-s3-storage) and that works just fine, but it incurs S3 costs each time I run my tests, plus the network overhead of going out to S3 is a lot during some of my media-heavy tests. The newly added (in Django 4.2) InMemoryStorage solves both of these problems (S3 costs and overhead) perfectly, but I can't get the test server to actually serve the uploaded media files. I've added: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to my urlpatterns.py, but that has no effect since Django tests are always run with DEBUG=False. But even if I force it in to my urlpatterns by inlining the relevant portion of django.conf.urls.static.static like so: import re from django.views.static import serve urlpatterns += [ re_path( r"^%s(?P<path>.*)$" % re.escape(settings.MEDIA_URL.lstrip("/")), serve, kwargs={"document_root": settings.MEDIA_ROOT}, ), ] it still doesn't work since the serve function looks like it's not storage-aware; it only works with media files on the filesystem. The result is that my media files all return 404s when my Selenium browser requests them. Is there a storage-aware equivalent to django.views.static.serve that I can … -
How do i fix this id?
i was watching a youtube tutorial about django and got an error. i was making login page and forms.py, and got an error which one the guy on youtube didnt get. its an 'invalid id reference error' in login.html, and i dont know how to fix it. code looks like this: forms.py: from django import forms from django.contrib.auth.forms import AuthenticationForm from users.models import User class UserLoginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control py-4', 'placeholder': 'Введите имя пользователя'})) password = forms.CharField(widget=forms.PasswordInput(attrs={ 'class': 'form-control py-4', 'placeholder': 'Введите пароль'})) class Meta: model = User fields = ('username', 'password') login.html: (part of the code) {% csrf_token %} <div class="form-group"> <label class="small mb-1" for="{{ form.username.id_for_label }}">Username</label> {{ form.username }} </div> <div class="form-group"> <label class="small mb-1" for="{{ form.password.id_for_label }}">Password</label> {{ form.password }} </div> <div class="form-group d-flex align-items-center justify-content-between mt-4 mb-0"> <a class="small" href="#">Forgot password?</a> <input class="btn btn-primary" type="submit" value="Registrate"> </div> error in this line: <label class="small mb-1" for="{{ form.username.id_for_label }}">Username</label> and this: <label class="small mb-1" for="{{ form.password.id_for_label }}">Password</label> please help me im too stoopid -
IntegrityError at /save-comment/
Good evening everyone I'm really stuck facing this Django problem for days thank you for helping me to unblock the problem, I created an opinion platform where the user can put the stars and give their opinion in comments, but when he wants to do it I always get an error please help me resolve the problem here is the error that appears all the time: IntegrityError at /save-comment/ (1048, "Le champ 'concours_id' ne peut être vide (null)") concours.views.save_comment .utilisateur}"``` class AvisConcours(models.Model): concours = models.ForeignKey('concours.Concours', on_delete=models.CASCADE, related_name='avis_concours') note = models.ManyToManyField('concours.Note', related_name='avis_note', blank=True,) commentaire = models.TextField(blank=True) utilisateur = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = "Avis de concours" verbose_name_plural = "Avis de concours" def __str__(self): return f"{self.concours}" + " - " + f"{self.utilisateur}" def save_comment(request): if request.method == 'POST': commentaire = request.POST.get('commentaire') concours_id = request.POST.get('concours') utilisateur = request.user notes_to_create = [] for note_type in NoteType.objects.all(): rating_value = request.POST.get(f'rating_{note_type.id}') if rating_value is not None: # Only create notes for non-empty ratings notes_to_create.append(Note(note_type=note_type, valeur=rating_value)) # Save bulk Note created_notes = Note.objects.bulk_create(notes_to_create) # Save AvisConcours and link notes avis_concours = AvisConcours.objects.create( concours_id=concours_id, commentaire=commentaire, utilisateur=utilisateur ) avis_concours.note.set(created_notes) # Use set() to set ManyToManyField directly return redirect('merci_commentaire') # return redirect('merci_commentaire') return render(request, "page_commentaire.html") <div … -
Runtime error in the GET methord and while submiting the form
I am just done the migration, then i want to store the data in the database after hit the submit button it show the error like this in the picture so gide me how to clear the error model.py from django.db import models # Create your models here. class register(models.Model): your_name = models.CharField(max_length=30) Email= models.EmailField(max_length=254) phone= models.IntegerField(max_length=13) account = models.CharField(max_length=10) message = models.CharField(max_length=300) error page Internal Server Error: /register Traceback (most recent call last): File "J:\good\test\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\utils\deprecation.py", line 136, in __call__ response = self.process_response(request, response) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\middleware\common.py", line 108, in process_response return self.response_redirect_class(self.get_full_path_with_slash(request)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\middleware\common.py", line 87, in get_full_path_with_slash raise RuntimeError( RuntimeError: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/register/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. [29/Sep/2023 20:35:21] "POST /register HTTP/1.1" 500 70661 In this view file it contain the register file. views.py from django.shortcuts import render,redirect from django.contrib.auth.models import User # Create your views here. def index(request): return render(request,"index.html") def contact(request): return render(request,"contact.html") def … -
in django in my porfolio detail the picture of portfolios are similar
in my django project in the index page in portfolio part everything is ok and the picture of each portfolio is correct but when i open a portfolio detail the picture of all portfolio in detail is a similar picture for example my firsts portfolio picture is pic3.jpg and my seconds portfolio image is pic4.jpg in the index page i havent any problem but when i open detail the first and second portfolio image is similar both of them is pic3.jpg it is my template: {% for item in porto %} <div class="col-xl-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <a style="display: inline-block; max-width: 360px; max-height: 200px; overflow: hidden;" href="{{ item.image.url }}" data-gallery="portfolio-gallery-app" class="glightbox"> <img src="{{ item.image.url }}" class="img-fluid" alt=""> </a> <div class="portfolio-info"> <h4><a href="{% url 'root:portfolio' id=item.id %}" title="More Details">{{ item.title }}</a></h4> <p>{{ item.content|truncatewords:3 }}</p> </div> </div> </div><!-- End Portfolio Item --> {% endfor %} it is urls.py: from django.urls import path from .views import * app_name = 'root' urlpatterns = [ path("",home,name="home"), path("portfolio/<int:id>",port_folio,name="portfolio"), path('category/<int:category_id>',home,name='portfilter'), ] it is views: def port_folio(request,id): cat = Category.objects.all() portos = PortFolio.objects.get(id=id) porto = PortFolio.objects.filter(status = True) context = { 'cat':cat, 'portos':portos, 'porto':porto, } return render(request,'root/portfolio-details.html',context=context) and it is my modules.py: class PortFolio(models.Model): image = models.ImageField(upload_to='port',default='default.jpg') … -
Django Admin - Proxy model loses edit/add on Foreign Key fields and no auto-complete?
Goal: I want to group some of my models inside of other apps on the Admin page. How: I created a proxy model for each of my models and defined app_label to be that of the app I want. class MyModelProxy(MyModel): class Meta: proxy = True app_label = 'auth' # specify a different app for the model to be grouped with verbose_name = MyModel._meta.verbose_name verbose_name_plural = MyModel._meta.verbose_name_plural I registered the proxy model together with the custom admin model I created for each. admin.site.register(MyModelProxy, MyModelAdmin) Issue 1: My Foreign Key fields lose the icons to edit/add another object in the view/change pages. If I register the original model with the admin model, it displays fine. (original)--> (proxy) Issue 2: If I set autocomplete_fields inside the corresponding admin models, I get an error that the original model should be registered. But I want to only register the proxy model, not both ? -
Get subscription ID with new Paypal Webhooks
I use the following endpoint for receiving the Paypal webhooks: @method_decorator(csrf_exempt, name='dispatch') class ProcessWebHookView(View): def post(self, request): if "HTTP_PAYPAL_TRANSMISSION_ID" not in request.META: return HttpResponse(status=400) auth_algo = request.META['HTTP_PAYPAL_AUTH_ALGO'] cert_url = request.META['HTTP_PAYPAL_CERT_URL'] transmission_id = request.META['HTTP_PAYPAL_TRANSMISSION_ID'] transmission_sig = request.META['HTTP_PAYPAL_TRANSMISSION_SIG'] transmission_time = request.META['HTTP_PAYPAL_TRANSMISSION_TIME'] webhook_id = settings.PAYPAL_WEBHOOK_ID event_body = request.body.decode(request.encoding or "utf-8") valid = notifications.WebhookEvent.verify( transmission_id=transmission_id, timestamp=transmission_time, webhook_id=webhook_id, event_body=event_body, cert_url=cert_url, actual_sig=transmission_sig, auth_algo=auth_algo, ) if not valid: return HttpResponse(status=400) webhook_event = json.loads(event_body) event_type = webhook_event["event_type"] print(event_type) return HttpResponse() Well in the metadata no information about the subscription id can be found. Does anyone have experience how to get this information from the request? -
Guys help me, to make a chat webapp to encrypted chat webapp in django
How hard to make a end to end encrypted chat using django and react, I mean using django channels and web socket, I already builded a chat web app, how hard to change my chat app to encrypted chat app, and also those encrypted chat needs to also be store as encrypted in Database, is any library out there?? -
Migration file errors when trying to get rid of a third party Django app
I'm working on a Django Project that currently uses the third party app Oscar. We're in the process of migrating away from Oscar, to a custom-built shop, and for this we want to get rid of a bunch of old files, models and of course the actual third party dependencies. But I am having a hard time doing this because the migration files keep throwing up errors. The situation is that we have first-party models that depend on Oscar's models. For example: from oscar.apps.catalogue.models import Product class Executable(Model): exec_hash = CharField(max_length=64, unique=True) product = ForeignKey(Product, blank=True, null=True, on_delete=CASCADE) version = CharField(max_length=32) os = CharField(max_length=32) update_url = CharField(max_length=128, blank=True) This means we have a migration file that contains the code to create this table: migrations.CreateModel( name="Executable", fields=[ ("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), ("exec_hash", models.CharField(max_length=64, unique=True)), ("version", models.CharField(max_length=32)), ("os", models.CharField(max_length=32)), ("update_url", models.CharField(blank=True, max_length=128)), ( "product", models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to="catalogue.product" ), ), ], ), The product field from this Executable needs to be removed, so I removed the field from the model and created a new migration. Now I want to remove all the Oscar apps from my INSTALLED_APPS list, but this is causing a whole lot of headaches because when I … -
libc error with UWSGI for Django, UWSGI fails on site load
I am receiving a segmentation fault error in UWSGI that seems to be related to libc.so.6 in my linux system. I have no idea where to even start with this error. The error happened after pushing code, but did not disappear after re-pushing the older code. We have 2 servers running this code, but only one is receiving this error. The error is as follows: Fri Sep 29 14:34:25 2023 - DAMN ! worker 2 (pid: 57544) died, killed by signal 11 :( trying respawn ... Fri Sep 29 14:34:25 2023 - Respawned uWSGI worker 2 (new pid: 57759) Fri Sep 29 14:34:47 2023 - !!! uWSGI process 57545 got Segmentation Fault !!! Fri Sep 29 14:34:47 2023 - !!! uWSGI process 57545 got Segmentation Fault !!! Fri Sep 29 14:34:47 2023 - !!! uWSGI process 57545 got Segmentation Fault !!! Fri Sep 29 14:34:47 2023 - !!! uWSGI process 57545 got Segmentation Fault !!! Fri Sep 29 14:34:47 2023 - *** backtrace of 57545 *** website.com(uwsgi_backtrace+0x35) [0x560449e94825] website.com(uwsgi_segfault+0x23) [0x560449e94bd3] /lib/x86_64-linux-gnu/libc.so.6(+0x33060) [0x7ffad1d63060] *** end of backtrace *** Fri Sep 29 14:34:47 2023 - *** backtrace of 57545 *** website.com(uwsgi_backtrace+0x35) [0x560449e94825] website.com(uwsgi_segfault+0x23) [0x560449e94bd3] /lib/x86_64-linux-gnu/libc.so.6(+0x33060) [0x7ffad1d63060] *** end of backtrace *** I … -
want to add validation on authenticate in django form
i created a login form is ther some thing are already validated but i can't validate is the username and pass word was correct view.py from django import forms as actualform from . import forms from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login,logout from django.core import validators def user_login(request): if request.method == 'POST': form = forms.LoginForm(request.POST.dict()) if form.is_valid(): # Handle valid form submission username=form.cleaned_data['name'] password=form.cleaned_data['password'] user=authenticate(username=username,password=password) if user is not None: login(request,user) return redirect(home) elif user is None : return render(request, "login.html", context={'form': form}) else: form = forms.LoginForm() return render(request, "login.html", context={'form': form}) def home(request): if request.user.is_authenticated: return render(request,"home.html") return redirect(user_login) def user_logout(request): if request.user.is_authenticated and request.META.get('HTTP_REFERER') is not None: logout(request) return redirect(home) login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>login</title> {% load bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} </head> <body> <div class=" w-50 container " style="border-radius: 20px; background-color: darkgrey;"> <h1 class="mt-5 pt-5 mb-0 text-center ">login</h1> <div class="h-100 d-flex align-items-center justify-content-center "> <form class="w-50 m-5 container" method="post" autocomplete="on"> {% csrf_token %} {{ form.name.label_tag }} {{ form.name }} <div class="error-message" style="color:red">{{ form.name.errors }}</div> {{ form.password.label_tag }} {{ form.password }} <div class="error-message">{{ form.password.errors }}</div> <button type="submit" class="btn btn-primary mt-1">Login</button> </form> <!-- <form class="w-50 m-5 container" … -
How to notify multiple separate cached Django read-only instances when a view has changed?
I am considering a Django stack for a site with high-frequency read (GET) events and low-frequency write (POST) events. Suppose there are a large number of read-only instances which are all serving GET events and caching various views. There are a smaller number of non-cacheing writeable instances which handle POST events. These instances are all independent and might be running on separate machines, although they access the same central database. Now suppose there is a POST event which invalidates, say, a user's e-mail address. Then various views across the various read-only instances need to invalidate their caches. Is there a standard way to implement this pattern within the Django framework, or do I need to do this myself? (Or there a much better totally different way to do this?) -
Django/Channels: AppRegistryNotReady error when deploying ASGI application on Heroku
I'm encountering an issue when deploying my Django application with Channels (ASGI) on Heroku. I've set up my ASGI configuration and routing as per the documentation, and the application works fine locally. However, when I deploy it on Heroku, I'm getting the following error: heroku log `2023-09-29T13:50:20.958856+00:00 heroku[web.1]: State changed from crashed to starting 2023-09-29T13:50:24.630050+00:00 heroku[web.1]: Starting process with command `daphne nanochat.asgi:application --port 16299 --bind 0.0.0.0 -v2` 2023-09-29T13:50:25.627718+00:00 app[web.1]: Traceback (most recent call last): 2023-09-29T13:50:25.627755+00:00 app[web.1]: File "/app/.heroku/python/bin/daphne", line 8, in <module> 2023-09-29T13:50:25.627769+00:00 app[web.1]: sys.exit(CommandLineInterface.entrypoint()) 2023-09-29T13:50:25.627785+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/daphne/cli.py", line 171, in entrypoint 2023-09-29T13:50:25.627826+00:00 app[web.1]: cls().run(sys.argv[1:]) 2023-09-29T13:50:25.627827+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/daphne/cli.py", line 233, in run 2023-09-29T13:50:25.627875+00:00 app[web.1]: application = import_by_path(args.application) 2023-09-29T13:50:25.627876+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/daphne/utils.py", line 12, in import_by_path 2023-09-29T13:50:25.627909+00:00 app[web.1]: target = importlib.import_module(module_path) 2023-09-29T13:50:25.627909+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module 2023-09-29T13:50:25.627951+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2023-09-29T13:50:25.627952+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1050, in _gcd_import 2023-09-29T13:50:25.628008+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1027, in _find_and_load 2023-09-29T13:50:25.628030+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked 2023-09-29T13:50:25.628055+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 688, in _load_unlocked 2023-09-29T13:50:25.628081+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 883, in exec_module 2023-09-29T13:50:25.628117+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed 2023-09-29T13:50:25.628142+00:00 app[web.1]: File "/app/./nanochat/asgi.py", line 16, in <module> 2023-09-29T13:50:25.628169+00:00 app[web.1]: … -
Error while reading a csv file in django rest framework
I am simply trying to read a csv file in django rest framework but its giving me this error and I can't seem to find what is the issue because I also tried reading the file in 'r' mode. Error _csv.Error: iterator should return strings, not bytes (the file should be opened in text mode) Views.py (csv reading code) csv_file = request.FILES["Bus"] data = [] with csv_file.open('r') as file: reader = csv.DictReader(file) for r in reader: print(r) I am using postman to send the csv file for testing