Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why do I get conflicts while creating new Django app
tn_gram_backend is the main Django project folder. I created a new folder staging and inside that I am trying to create another Django app called ddc but it is throwing me the following error as show in the below image. Please suggest how to fix this. 'ddc' conflicts with the name of an existing python module and cannot be used as an app name -
Internal server error running Django on Heroku accessing from browser
I think this is a simple fix, but I've deployed quite a few Django apps to Heroku and I still can't figure out what's going on. Accessing https://dundjeon-finder.herokuapp.com/ gives me a 500 error when using the browser/curl, but if I shell into the app using heroku run ./manage.py shell I can render the views no problem. My logs aren't telling me anything (just that the response is 500), and Sentry isn't receiving an error (it has previously when the database env variable was set badly), so I'm assuming it's something to do with the way the request works. The repo is public, any help would be much appreciated! The settings file is here. -
Virtual environment for Django in ubuntu 20.04
After installing Django, I install virtual environment by using the command - pip3 install virtualenvwrapper-win.Also run sudo pip3 install virtualenv Added the following to the end of the .bashrc file export WORKON_HOME=~/virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python source ~/.local/bin/virtualenvwrapper.sh then source ~/.bashrc gets successfully executed. But when I run this command - mkvirtualenv test to create virtual environment, I am getting this- created virtual environment CPython3.8.5.final.0-64 in 94ms creator CPython3Posix(dest=/home/rudrakshi/.virtualenvs/test, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/home/rudrakshi/.local/share/virtualenv) added seed packages: pip==20.3.1, setuptools==51.0.0, wheel==0.36.1 activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator Command '' not found, but can be installed with: sudo apt install mailutils-mh # version 1:3.7-2.1, or sudo apt install meshio-tools # version 4.0.4-1 sudo apt install mmh # version 0.4-2 sudo apt install nmh # version 1.7.1-6 sudo apt install termtris # version 1.3-1 I also installed the mailutils-mh but still getting this. -
Is it possible to use Azure Shared Access Signature outside of Azure?
Since Azures Shared Access Signatures (SAS) is an open standard I want to use it in my Django application which has no links to Azure whatsoever. I basically want to create a piece of code that creates read permission for the next 24 hours on a specific url I'm serving. So I've watched some video's on SAS and I installed the python library for it (pip install azure-storage-blob). I read over the README here on github but as far as I can see it always requires an Azure account. Is it also possible to use SAS in my own (Python) application? I imagine it to create the hashes based on a pre-defined secret key for. If this is possible, does anybody have any example code on how to create the url and how to validate it? Preferably in Python, but example code in other languages would be welcome as well. -
Python-Django-Heroku not able to locate images in heroku, images not visible
so I recently deployed my django/python website (that used sqllite as a database) to heroku which hosts websites for free, everything is functioning normally like when I used to run localhost in my browser, except that this project is using postgressql database with heroku and images aren't appearing on my website, I looked everywhere and I think it has to do with the uploads file in the database(the path of the image is still the same but the location of the image changed). local host image link: "http://localhost:8000/image/download/uploads/products/white_shirt_MERETfT.jpg" heroku image link: "https://supremelebanon.herokuapp.com/image/download/uploads/products/offwhite_shirt_tQWa19c.jpg" it says image not found for when I load the website on heroku hosting. Please anyone I'm still a newbie with heroku I dont really know how it works, if anyone can help it would be much appreciated, thanks in advance. settings.py file: import os from pathlib import Path import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'morrr7ht4t4m)j#%ws34ntr7mdq$pui)+uy2-#%tx^iznh_##6' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['supremelebanon.herokuapp.com', 'localhost', … -
Error when migrating a foreignkey in Django
When I run python .\manage.py makemigrations it gives me the following error in my app called store (this is for making blog posts). python .\manage.py makemigrations Migrations for 'store': store\migrations\0009_auto_20201229_1318.py - Remove field test from post - Add field author to post PS C:\Users\Lukas\Desktop\Projects\hiddenservice> python .\manage.py migrate store Operations to perform: Apply all migrations: store Running migrations: Applying store.0006_post_author...Traceback (most recent call last): File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: new__store_post.author_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Lukas\Desktop\Projects\hiddenservice\manage.py", line 22, in <module> main() File "C:\Users\Lukas\Desktop\Projects\hiddenservice\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\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 "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\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 "C:\Users\Lukas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration … -
How to pass object by id after saving from form using redirect?
I am sorry for asking this. I described a service that uploads an image through a form. The bottom line is that after a successful download (add_picture), I have to get to the image page (picture_detail). I don’t understand why I can’t transfer ID. I did the following: models.py: class Picture(models.Model): url = models.URLField(blank=True, verbose_name='Ссылка на изображение') image = models.ImageField(upload_to='pictures/%Y/%m/%d', width_field='image_width', height_field='image_height', blank=True, verbose_name='Изображение') def get_absolute_url(self): return reverse('home:picture_detail', args=[self.id]) views.py: def add_picture(request, id=None): picture = Picture.objects.filter(is_active=True) # picture_form = None # picture = get_object_or_404(Picture, id=id) if request.method == 'POST': form = PictureCreateForm(data=request.POST, files=request.FILES) if form.is_valid(): form.save() # picture = get_object_or_404(Picture, id=id) bb = Picture.objects.get(id=id) return HttpResponseRedirect(reverse('home:picture_detail', kwargs={'id': id})) else: return render(request, 'add_picture.html', locals()) else: form = PictureCreateForm() return render(request, 'add_picture.html', locals()) urls.py: urlpatterns = [ path('', views.home, name='home'), path('add_picture/', views.add_picture, name='add_picture'), path('picture_detail/<int:id>/', views.picture_detail, name='picture_detail'), ] As a result, I should get to a page of this kind: -
STARTTLS extension not supported by server while attaching more than 1 mb file
I am getting "STARTTLS extension not supported by server" while attaching more than 1 MB file with the mail. While attaching less than 1 MB file the exception is not being generated in python. if file_size <= ATTACHMENT_FILE_SIZE : print('in if condition') logger.info(f'{thread_name} : In If Condition') mailDetails.attach(MIMEText(body_to_be_sent, "html")) attachment = open(filepath, 'rb') payload = MIMEBase('application', 'octet-stream') payload.set_payload(attachment.read()) encoders.encode_base64(payload) payload.add_header('Content-Disposition', "attachment; filename= %s" % f'''{file_name}.xlsx''') mailDetails.attach(payload) try: connection = smtplib.SMTP(SMTPserver) connection.ehlo() connection.starttls() connection.set_debuglevel(False) connection.login(SMTPUSERNAME, SMTPPASSWORD) text = mailDetails.as_string() connection.sendmail(FROM_MAIL_ADDRESS,toAddress.split(",") + ccAddress.split(",")+bccAddress.split(","), text) logger.info(f'{thread_name} : Mail Sent successfully') # os.remove(filepath) -
Django : cannot access body after reading from request's data stream
Im working with REST API and currently sending data from fetch to my django view. Im getting cannot access body after reading from request's data stream. what is wrong? PS: i already tried using request.data but some other problems occuring views.py @csrf_exempt @api_view(['POST']) def createNew(request): data = json.loads(request.body) if request.method == 'POST': serializer = newsSerializer(data =data['title']) if serializer.is_valid(): serializer.save() # return Response(serializer.data) return redirect('http://127.0.0.1:8000/news_list/') my fetch method form.addEventListener("submit", function(e) { e.preventDefault() var url = 'http://127.0.0.1:8000/news_create/' var title = document.getElementById('title').value fetch(url, { method: 'POST', // or 'PUT' headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ 'title': title }), }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch((error) => { console.error('Error:', error); }); }); -
How to add multiple popup form in one page in django
I want to create three tables(In HTML) as follow : Medical School PG University(Name of university and pass-out year) Privilege state to practice(Name of state, License expiry year) I want to add a popup form to information in those three tables on one page(In HTML). -
Database-Query in DjangoChannels Consumer returns coroutine object instead of query-set
I am using an AsyncConsumer from wich an async task calls a syncronous function via the asgiref sync_to_async function. In this function the result of a database query is supposed to be saved to a variable and later iterated over, but instead of the resulting queryset, the variable just saves the coroutine object. a simplified version of the code: class ChatConsumer(AsyncConsumer): ... async def collect_votes_task(self): await sync_to_async(self.process_sessions()) def process_sessions(self): current_session = self.get_current_session(self.room_name) print(current_session) # do other stuff with the query-set @database_sync_to_async def get_current_session(self, current_session_code): current_session = Session.objects.filter( session_code=current_session_code) return current_session prints: <coroutine object SyncToAsync.__call__ at 0x000001B1CBBF03C0> I am fairly new to DjangoChannels, so excuse me if the reason this happens is obvious. -
How TO Get live data of NSE stocks of all symbols in python/Django
How TO Get live data of NSE and BSE stocks of all symbols in python/Django? I am looking for this so that I can eventually filter it a look at what stock I need to concentrate and also to get an experience in Python Programming. It Would Be Great If I Could Know: The Best API to get Live Stock Details From NSE And BSE. Any Resources Associated Anymore Suggestions ¯_(ツ)_/¯ Thank You, You Can Contact Me Through Evan Thomas - LinkedIn -
Django Date and time issue. Server ahead of timezone
I was working on an app and I can't solve the issue of date and time. In setting.py file I have set the timezone to UTC. TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True I live in UTC+05 so when I publish a blog the date and time is 5 hours into the future so the blog can only publish after 5 hours. Is there a way to automatically detect the time zone of users to either add or subtract hours relative to UTC or anything that can automatically solve this issue. models.py class blog(models.Model): blog_text = models.CharField(max_length=1000) pub_date = models.DateTimeField("date published") def __str__(self): return self.blog_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.admin_order_field = "pub_date" was_published_recently.boolean = True was_published_recently.short_description = "Published recently?" -
I want to create a set of buttons (answers to the questions) in Django, how should I do this?
I want to create a quiz site with a selection buttons, it should contain answer and two buttons with answers on em. When new user would open this quiz every button should be inactive, and once he would select one of answers then it should be active (and sent to the database), he could then return to this page and see his answers and change the answers whenever he wants. I want to do this without submit button (every answer should save after clicking). Here's my code: models.py class InterestQuestion(models.Model): q_id = models.AutoField(primary_key=True) question = models.CharField(max_length=255) answer1 = models.CharField(max_length=64) answer2 = models.CharField(max_length=64) class UserInterest(models.Model): q_id = models.ForeignKey(InterestQuestion, on_delete=models.CASCADE) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) selectedInterest = models.CharField(max_length=64) views.py @login_required def select_interests(request): questions_data = InterestQuestion.objects.all() if request.method == 'POST': questionnaire_form = InterestSelectionForm(request.POST, request.user) if questionnaire_form.is_valid(): new_val = questionnaire_form.cleaned_data.get("userAnswer") #answered = questionnaire_form.save() #new_entry = UserInterest.objects.create(select_interests = answered) else: questionnaire_form = InterestSelectionForm() return render(request, 'quiz/quiz_form.html', locals()) quiz.html <form action="." method="post"> {% for q in questions_data %} <ul> <li>{{ q.question }}</li> </ul> {% csrf_token %} <input type="button" class="userAnswerButton" value="{{ q.answer1 }}"> <input type="button" class="userAnswerButton" value="{{ q.answer2 }}"> {% endfor %} </form> I don't know If I should use forms.py in this case, but I'll paste it … -
Redirect URI Mismatch in django
error: redirect_uri_mismatch error_description: redirect_uri did not match any client's registered redirect_uris My redirect uri in OneLogin is 1 -
is it possible to build an app with scrapy without using command line interface?
I am building an app for scraping data from other sources, however, the URL would be entered by the user on a web page, and currently, I am using BeautifulSoup and Selenium to achieve the data and it is extremely slow. How this app will work? The user will visit the website, for example, example.com, and enter the URL in a form, which he/she wants to scrap. Now the problem is how I can achieve the desired result via Scrapy programmatically using Django views. Is it possible? thanks -
how to send OTP to phone number in Django?
I need to verify the phone number while submitting the form(no need to login and register). I am using the Twilio service. Please suggest to me How can I do this. I need to send OTP to the user by filling the number in the form afterward verify then submit the form. Thanks in advance! My Model: class Booking(models.Model): date = models.CharField(max_length=200,blank=True, db_index=True, null=True ) time = models.CharField(max_length=200,blank=True, db_index=True, null=True ) name = models.CharField(max_length=200,blank=True, db_index=True, null=True ) email = models.CharField(max_length=200,blank=True, db_index=True, null=True ) product = models.CharField(max_length=200,blank=True, db_index=True, null=True ) phone = models.IntegerField(max_length=200,blank=True, db_index=True, null=True ) address = models.TextField(max_length=200,blank=True, db_index=True, null=True ) My view import os from twilio.rest import Client from django.shortcuts import render, get_object_or_404, redirect from .models import Product,Technician,FAQ, Booking account_sid = '*******************************' auth_token = '********************************' def booking(request,slug=None,pk=None): products = get_object_or_404(Product,slug=slug) if request.method == 'POST': date = request.POST['date'] time = request.POST['time'] name = request.POST['name'] email = request.POST['email'] product = request.POST['product'] phone = request.POST['phone'] address = request.POST['address'] client = Client(account_sid, auth_token) message = client.messages \ .create( body="Join Earth's mightiest heroes. Like Kevin Bacon.", from_='+********', to=phone ) data = Booking(date=date, time=time, name=name, email=email, product=product, phone=phone, address=address,message=message) data.save() print('Booking Done') return redirect('home') else: return render(request, 'book.html', {'product' : products}) -
How to prevent Django to initialize "prod" DB before test DB
I'm using Django for the backend of my project and I'm currently writing tests. The thing is when I use the command python manage.py test, it first loads my actual DB before creating the test DB. The problem is that on DB initialization, I have some processes that do stuff with the App Registry (in my software you can install/uninstall apps while Django is running). So when I use the test command, it loads my App Registry from my local DB, then it creates the test DB but it seems to be using the same App Registry (since it uses the same settings when it starts). So I have tests that fail because things are already done in the App Registry (because of my local DB), that shouldn't be. So when I do python manage.py test, the output is : I do this : print("DB : ", connection.settings_dict['NAME']) somewhere to show you DB : my-db Creating test database for alias 'default'... System check identified no issues (0 silenced). .DB : test_my-db ..... ...tests are executed... .... Is there any setting that I could use to tell Django : "Hey, I'm using the test command, do not load my local DB … -
How to create an "login page" with Laravel or Django?
I'm starting to create a homepage-application that has a login page. I'm familiar in both Python and PHP, but have not used any frameworks. Do you recommend to use Django (Python) or Laravel (PHP)? Is there some ready code for creating Login pages? They don't have to be free. -
Pick the hidden value from the form that is clicked on - jQuery Djano Ajax
How to pick the hidden value from the form that is clicked on. I have many similar forms and all have a similar field, but values are different. I want to pick up the value numbers shown here to submit the form as a jquery ajax request. <div id="mydiv"> <form name="myForm" action="comment.php" method="post"> <input type="hidden" name="indexvalue" value="1"> </form> <form name="myForm" action="comment.php" method="post"> <input type="hidden" name="indexvalue" value="2"> </form> <form name="myForm" action="comment.php" method="post"> <input type="hidden" name="indexvalue" value="3"> </form> <form name="myForm" action="comment.php" method="post"> <input type="hidden" name="indexvalue" value="4"> </form> </div> $(document).on('click', '#mydiv form', function(e) { e.preventDefault(); $.ajax({ type: "POST", url: "/updatedb", data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), 'indexvalue': $(this).parent("form value").val() }, success: renderSuccess, dataType: 'HTML', error: function (result) { $('#successdiv').empty(); alert('Verify the input, or refresh the page'); } }); }); -
How can I user ordering filter in Django rest framework 3.1~
I want to user ordering filter, so import filters. ... from rest_framework import filters But I kept getting errors. from django.db.models.sql.constants import ORDER_PATTERN ImportError: cannot import name 'ORDER_PATTERN' from 'django.db.models.sql.constants So I searching, then I saw this posting(https://www.gitmemory.com/issue/encode/django-rest-framework/7458/668618981) The ORDER_PATTERN has been removed in Django 3.1, But I want to use ordering filter. How can I use this? I use Djnago 3.1.4, drf 3.11.0 -
Django don't run the collectstatic command anymore when I upload an image from admin
I'm currently developing a Django application. I have a static-res folder that contains all my static data. In production I'm starting the generation of the "static" folder with the collectstatic command. So far everything works. From the admin part I come to import images manually with ImageField, so each time I have to run the collectstatic command... I'd like to be able to import an image in production, without having to run the command each time. Here is my code in the settings : MEDIA_ROOT = os.path.join(BASE_DIR, 'static-res/images') STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = 'static/images/' STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static-res'), os.path.join(BASE_DIR, 'static-res/images'), os.path.join(BASE_DIR, 'static/images'), os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'static-res/js'), ] and in my urls.py file : ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I really can't find a solution so if anyone can help me I thank you! -
Can a Django ManyToManyField contain multiple different Model classes? How would I order it?
I'm building a List model that I want to be able to contain and order various different other model types. class Parent(models.Model): title class Child(models.Model): parent = ForeignKey(Parent) order text class Meta: ordering = ['order',] class List(models.Model): list_items = ManyToMany??? How can I set it up so that a List can contain both Parent and Child models? (And also have a List contain other List models for that matter?) And while I can order Child models for a Parent on the Child level (i.e. child.order), how could I order Parent, Children, and List list_items for a List? -
nginx connet to .sock failed (13:Permission denied) - 502 bad gateway
I am using nginx + uwsgi + django to deploy my very first site on centos7. They worked fine separately in test but I got a 502 bad gateway trying to connet them all together. The /var/log/nginx/error.log file says 2020/12/29 15:52:05 [crit] 1150#0: *1 connect() to unix:/run/uwsgi/site.sock failed (13: Permission denied) while connecting to upstream, client: IPaddress, server: mysite.com, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:/run/uwsgi/site.sock:", host: "IPaddress" I have tried these but none of them managed to fix the problem: 1.moving the site.sock file from my project base directory to /tmp/site.sock, or according to this tutorial, to /run/uwsgi/site.sock. 2.changing the site.sock file permission from 664 to 666. 3.chown socket file to myuser:nginx, and add myuser to nginx group. 4.running nginx and uwsgi with a www-data user by setting user = www-data in nginx.conf and uid = www-data,pid = www-data in site_uwsgi.ini. 5.turning off selinux by setenforce 0, or doing setsebool -P httpd_can_network_connect 1. ps aux | grep nginx: root 1148 0.0 0.0 39296 1972 ? Ss 15:41 0:00 nginx: master process /usr/sbin/nginx nginx 1150 0.0 0.1 39640 2056 ? S 15:41 0:00 nginx: worker process ps aux | grep uwsgi: root 1322 0.0 0.1 54680 3068 ? Ss 15:49 0:00 … -
Problems with django installation
I have a problem with installing django in my venv. When I try to run pip install django inside my venv, I get the following error: ERROR: Could not install packages due to an EnvironmentError: ('Received response with content-encoding: gzip, but failed to decode it.', error('Error -3 while decompressing data: incorrect data check'))