Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I got IntegrityError with Bid system in my project Django
Django Error: IntegrityError at /Post/18/bid NOT NULL constraint failed: auctions_bid.bidWon Request Method: POST Request URL: http://127.0.0.1:8000/Post/18/bid Django Version: 3.2.8 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: auctions_bid.bidWon I am trying to apply this Specification: If the user is signed in and is the one who created the listing, the user should have the ability to “close” the auction from this page, which makes the highest bidder the winner of the auction and makes the listing no longer active. If a user is signed in on a closed listing page, and the user has won that auction, the page should say so. but when I runserver i got this error Please take a look at my code: url.py urlpatterns = [ # bids Close Bid path('Post/<int:id>', views.viewList, name='viewList'), path("Post/<int:id>/bid", views.take_bid, name="take_bid"), path('Post/<int:id>/close', views.closeListing, name="closeListing"), ] model.py # DONE class Post(models.Model): # data fields title = models.CharField(max_length=64) textarea = models.TextField() # bid!!!!!!!!!!! startBid = models.FloatField(default=0) currentBid = models.FloatField(blank=True, null=True) imageurl = models.CharField(max_length=255, null=True, blank=True) category = models.ForeignKey( Category, on_delete=models.CASCADE, default="No Category Yet!", null=True, blank=True) creator = models.ForeignKey( User, on_delete=models.PROTECT, related_name="all_creators_listings") watchers = models.ManyToManyField( User, blank=True, related_name='favorite') date = models.DateTimeField(auto_now_add=True) # for activated the Category activate = models.BooleanField(default=True) buyer = models.ForeignKey( … -
After changing a variable in django need to restart the server to update the variable
I'm a beginner in python and django and learned how to send data to the template, but if I'm trying to change the data (variable) while the server is running and reload the page, the data remains old, and to fix that I need to restart the server. Am I missing something? views.py from django.shortcuts import render # Create your views here. def index(request): context = { 'name': 'Nick', 'age': 24 } return render(request, 'index.html', context) index.html <h1>Hi, {{name}}<br>You are {{age}} years old</h1> -
AttributeError at /profile/ 'function' object has no attribute 'object
here is my views.py file but i keep getting this error, what could be the issue here. Profile is a class in the models.py code. if you need another part of my code please ask from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get("username") messages.success(request, f"Your account has been created! You are now able to login!") return redirect("login") else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def Profile(request): profile.objects.get_or_create(user=request.user) if request.method == "POST": u_form = UserUpdateForm( request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f"Your account has been updated!") return redirect("profile") else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.Profile) context = { 'u_form': u_form, 'p_form': p_form, } return render(request, "users/profile.html", context) AttributeError at /profile/'function' object has no attribute 'objects' Request Method: GET Request URL: http://127.0.0.1:8000/profile/ Django Version: 2.2.8 Exception Type: AttributeError Exception Value:'function' object has no attribute 'objects' Exception Location: /Users//Desktop/project/users/views.py in profile, line 20 Python Executable: /Users//.local/share/virtualenvs/project-9FFMjpiO/bin/python -
Django User default permission
I want to add permissions (view, add, change, delete) to every user, so I add this meta class in each Model class Meta: default_permissions = ('add', 'change', 'delete', 'view') but when I log in (with new user) to the Django admin site, the user hasn't got the permission yet. Is my approach wrong? -
It's possible to have relationships between models stored in different databases in Django?
I'm currently working on a project where I handle both public and private information, both stored as different models in a common database. I would like to split this database in two, one with the private model objects and another one with the public ones. The thing is, both this models have a ForeignKey relationship with each other, and I've found conflicting answers over the internet about if this relationships can work even if the models are in two different databases. So, is this possible? Is there a better approach for doing this? Just to clarify why I want to do this, I want the project to be open source, therefore the public database should be public, but the sensitive information (users and passwords) should be kept private. -
How to pass a JSON data from React to Django using POST request?
I have a React frontend which has a state variable that contains an array. I want to pass this state variable onClick to my Django's views.py. What I have so far is something like this: App.js const [dataSource, setDataSource] = useState([]); // Where the data is stored in const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(dataSource), }; const handleSubmit = () => { fetch("http://localhost:8000/insert", requestOptions); }; <Popconfirm onConfirm={handleSubmit}> <Button>Submit</Button> </Popconfirm> views.py def insert(request): if request.method == 'POST': json_data = request.POST.get() # I'm not sure what should I be putting as a parameter for .get() method return render(request, 'frontend/index.html') urls.py ... urlpatterns = [ ... path('insert/', views.insert), ... ] Am I using the right approach? If it's right, what should I be passing as parameters to the get() method? *P.s. I'm not using DRF for this approach and I'm building the app where Django and React is in one app (not separate) where the frontend is an app of Django. -
How to access subset of kwargs.pop or another way of setting different forms based on question type?
I am building a survey app, which has questions with an attribute of type, where it can be of checkbox, textarea or radio. it also has a model of options (which has question as a foreign key) In my answerform i want to pass different types of form based on the type of the question. So far i have: (with all questions and options having radio type form... class Question(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) prompt = models.CharField(max_length=128) class Type(models.TextChoices): YesOrNo = 'YesOrNo' Text = 'Text' MultipleChoice = 'MultipleChoice' CheckBox = 'CheckBox' type = models.CharField(max_length=15, choices=Type.choices, default=None, blank=True, null=True) class Option(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) text = models.CharField(max_length=128) And in my Forms I have: class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ["prompt", "type"] class OptionForm(forms.ModelForm): class Meta: model = Option fields = ["text"] class AnswerForm(forms.Form): def __init__(self, *args, **kwargs): options = kwargs.pop("options") choices = {(o.pk, o.text) for o in options} super().__init__(*args, **kwargs) option_field = forms.ChoiceField( choices=choices, widget=forms.RadioSelect, required=True) self.fields["option"] = option_field -
django upload image by Ajax without form
I have an input type="file" element for image upload, I attached ajax in change event listener. and used a form data for transmission. However, I failed to fetch the value in django backend. <input type="file" /> const imageUpload = function( file, success, error, ) { let fd = new FormData(); fd.append('file', file); console.log(fd); console.log(file); $.ajax({ type: "POST", url: "{% url 'image-upload' %}", data: fd, processData: false, contentType: false, success: success, error: error, }) }, @login_required @csrf_exempt def editorImageUploadPost(request): if request.is_ajax and request.method == 'POST': print(request.POST) file = request.POST['file'] portray = Portray(image=file) portray.save() request.user.profile.portrays.add(portray) request.user.profile.save() return JsonResponse({}, status=400) js console: changed FormData: No Properties File: lastModified: 1629099905000 name: "Screen Shot 2021-08-16 at 3.45.01 pm.png" size: 3716526 type: "image/png" webkitRelativePath: " python terminal: <QueryDict: {}> error message: System check identified no issues (0 silenced). November 06, 2021 - 03:28:49 Django version 3.2.8, using settings 'zzd.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [06/Nov/2021 03:28:50] "GET /articles/update/1 HTTP/1.1" 200 10010 <QueryDict: {}> Internal Server Error: /articles/new/post/ajax/upload/image Traceback (most recent call last): File "/Applications/MAMP/htdocs/canvas/src/zzd/env/lib/python3.7/site-packages/django/utils/datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) KeyError: 'file' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Applications/MAMP/htdocs/canvas/src/zzd/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, … -
How to upload and use images on heroku django
so i make this app in which you can make products. And those products have an image that was saved in a file while i was using this app localy. I deployed my app on heroku and ofc since there are no normal files like localy it cant be saved there. How can i save it somewere and use it? I also use postgesql btw to store other data so maybe i can store the image too. class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, blank=True, null=True) image = models.ImageField(upload_to='images', blank=True, null=True) price = models.FloatField(max_length=255, blank=True, null=True) description = models.TextField(max_length=255, blank=True, null=True) category = models.ForeignKey(Category, blank=True, on_delete=models.CASCADE) seller = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name -
running virtual env and installing packages in aws lightsail
I want to install a package which requires virtual environment before it can be installed properly. I have installed the project and other packages but there is a pakage which is not installing because I am not running my command from inside the virtual environment. Please how can I make use of virtualenv in django aws lightsail. Thanks -
Another "fk_name ' ' not a foreignkey to" problem [Python/Django]
please don't judge with my question. I tried every suggestion here but still no luck. here's my code --- admin.py from django.contrib import admin from .models import candidates_info, address class addressInline(admin.TabularInline): model = address fk_name = 'id' @admin.register(candidates_info) class candidates_infoAdmin(admin.ModelAdmin): fields =['last_name', 'first_name', 'middle_name', 'moniker'] inlines = [addressInline] models.py import datetime from django.db import models from django.utils import timezone class candidates_info (models.Model): last_name = models.CharField(max_length=50) first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50) #position = models.ForeignKey('positions', db_column='position_id', on_delete=models.CASCADE, null=False) #birth_date = models.ForeignKey('birthdate', db_column='date_of_birth_id', on_delete=models.CASCADE, null=False) #contact_info = models.ForeignKey('contact_info', db_column='contact_info_id', on_delete=models.CASCADE) addr = models.ForeignKey('address', on_delete=models.SET_NULL, null=True) moniker = models.CharField(max_length=35) #party = models.ForeignKey('political_parties', db_column='political_parties_id', on_delete=models.CASCADE, null=False) registration_dt = models.DateTimeField('date registered') class address(models.Model): lot_no = models.DecimalField(max_digits=5, decimal_places=0) block_no = models.DecimalField(max_digits=5, decimal_places=0) note: the codes commented out (#) are part of my code in models.py which I temporarily disabled as part of my code to see if it's conflicting with the declaration of foreignKey. and another thing, tried declaring and undeclaring fk_name on admin.py but still no luck. Please help guys. Been stock here for a few days now. I can't seem to find the bug. TIA btw.. here's the error from console --- <class 'votenow.admin.addressInline'>: (admin.E202) fk_name 'id' is not a ForeignKey to 'votenow.candidates_info'. -
Django template language doesn't display anything
Django 3.2.9 views.py: from django.shortcuts import render # Create your views here. def index(request): context = { 'name': 'Patrick' } return render(request, 'index.html', context) index.html: <h1> Welcome {{name}} </h1> The outcome: As you can see nothing Workspace: Just in case So my question is obvious, am I missing anything? All the tutorials, the documentation, everything is just like in them, but outcome is differ -
Form wont validate, says that all fields are empty Django
In a view I have 3 forms: forms.py class PostForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(PostForm, self).__init__(*args, **kwargs) class Meta: model = Post fields = ['subtitle', 'latitude', 'longitude', 'tags', 'body'] widgets = { 'body': forms.Textarea(attrs={'class': 'log-body editable'}), 'tags': forms.TextInput(attrs={'id': 'tags-field', 'class': 'log-form-field'}), 'latitude': forms.TextInput(attrs={'id': 'latitude-field', 'class': 'log-form-field'}), 'longitude': forms.TextInput(attrs={'id': 'longitude-field', 'class': 'log-form-field'}), 'subtitle': forms.TextInput(attrs={'id': 'subtitle-field', 'class': 'log-form-field'}), } labels = { 'subtitle': 'Subtitle:', 'tags': 'Tags:', 'latitude': 'Latitude', 'longitude': 'Longitude', 'body': '' } class ImageForm(forms.ModelForm): images = forms.ImageField(label='Images', widget=forms.ClearableFileInput( attrs={ 'multiple': True, 'class': 'file-upload', 'id': 'file-upload-button-image', 'name': 'images'} ) ) class Meta: model = PostImage fields = ('images',) class VideoForm(forms.ModelForm): videos = forms.FileField(label='Videos', widget=forms.ClearableFileInput( attrs={ 'multiple': True, 'class': 'file-upload', 'id': 'file-upload-button-video', 'name': 'images' } ) ) class Meta: model = PostVideo fields = ('videos',) And I have a template that creates a post and stores the videos and pictures and that works great. Where I'm having a hard time is updating a 'Post'. class PostEditView(TemplateView): template_name = 'Logging/edit view.html' post_form_class = PostForm image_form_class = ImageForm video_form_class = VideoForm def get_context_data(self, **kwargs): context = super(PostEditView, self).get_context_data(**kwargs) context['post_pk'] = self.kwargs['pk'] context['post_form'] = PostForm(instance=Post.objects.get(pk=self.kwargs['pk'])) context['image_form'] = ImageForm(empty_permitted=True, use_required_attribute=False) context['video_form'] = VideoForm(empty_permitted=True, use_required_attribute=False) context['images'] = PostImage.objects.filter(post_id=self.kwargs['pk']) context['videos'] = PostVideo.objects.filter(post_id=self.kwargs['pk']) return context def … -
Custom Auth Backend
I am looking to create a custom auth backend for my Django project using one field for private key. How to achieve that with removing the "django.contrib.auth.backends.ModelBackend" and replace it with the new auth? Simply, if private key match public key in the database, login that user, else raise error. Note, at the moment all users have public key (RSA) stored in the database, and the private key in stored in the sessions. -
Can't Download my Video via PyTube ending with mp3
Hello, does anyone know what I did wrong? Or why my video is downloaded in mp4 but NOT in mp3? def converter(request): if request.method == 'POST': link = request.POST['link'] video = YouTube(link) format = request.POST['format'] if format == "3": stream = video.streams.get_audio_only() download_folder = os.path.expanduser("~")+"/Downloads/" stream.download(download_folder) os.rename(stream.download + ".mp3") elif format == "4": stream = video.streams.get_highest_resolution() download_folder = os.path.expanduser("~")+"/Downloads/" stream.download(download_folder) return render(request, 'home/videoconverter.html',) -
request.get: Temporary failure in name resolution. Cannot use Session()
Inside of a Django web app, I synchronously call an external API using requests. request(url=api_url, method="GET") This gets called roughly 1 or 2 times per minute, and can scale up to 10 times per minute. It mostly works fine, though sometimes I get this error: HTTPSConnectionPool(host='example.com', port=443): Max retries exceeded with url: /api_url/endpoint.json (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f637a4e63a0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')) Now, I understand the correct solution would be to use Session() so that the underlying TCP connection is reused and requests doesn't have to perform a name resolution every time (which, as we've seen, could sometime fail for no avoidable reason). However, Session() would not persist once my Django app has responded to the user. The app works synchronously: I would need an external service that persists the TCP connection to external APIs, only for this purpose... that'd be madness. More simply, I'd like to cache the name resolution somewhere, potentially for days. Is this possible? I have the IP address the api_url resolves to. But I obviously can't query that directly. What's the solution here? -
Best way to declare additional data in Django project
I'm looking for the best practice in order to declare the additional data in a Django project. Imagine I need to store a huge list of choices to use in app1/models.py (I have seen a lot of best practices keep declaring those choices in the body of the models). In another scenario, Imagine I need to keep tens of config data in order to use them in my views.py. Is it common to declare them in the function/class? In my opinion, there would be two common methods in order to do that. (Not sure even recommended at all) Method #1 I can actually keep them all in my settings.py file and access them with importing (like from django.conf import settings). settings.py: ... NBA_TEAMS = ( ("red", "Bulls"), ("yellow", "Lakers"), ... ) Method #2 Keep them all in a file named data.py right next to the settings.py, and try importing it at the end of the settings file like this. settings.py ... try: from .data import NBA_TEAMS, .. except: pass Is there any best practice about this issue? Thank you. -
How to migrate from Sqlite to PostgresSQL in Django? OperationalError
I am learning to use Django through a tutorial in which we are developing a small project, i'm trying to connect a PostgresSQL database and do the migrations, but i have certain problems when doing 'python manage.py migrate' in the terminal Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DEMO_TEST', 'USER' : 'postgresql', 'HOST': 'localhost', 'PASSWORD':'lew123lew123', 'PORT': '5432', } } Traceback File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle self.check(databases=[database]) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 419, … -
Force tests to fail if migrations aren't run
I'm blatantly oblivious sometimes, and it led me down a 30 minute blackhole trying to figure out why my constraints weren't being applied in my tests. Turns out I forgot to run makemigrations. Is there a way to configure pytest or django to fail without makemigrations? I know if very clearly warns me Your models have changes that are not yet reflected in a migration, and so won't be applied. Just looking for something a little more obvious/in your face? -
TypeError: expected str, bytes or os.PathLike object, not JpegImageFile (or PngImageFile)
When I am uploading a picture to check a picture according to tensorflow h5 model, I am loading image using load_model of tensorflow.keras.models but it is not accepting. For JPG, it is showing TypeError: expected str, bytes or os.PathLike object, not JpegImageFile and for PNG, it is showing as TypeError: expected str, bytes or os.PathLike object, not PngImageFile. What to do now? I tried the code with raw python but it worked nicely. Code: #views.py import numpy as np from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing import image pic = request.FILES['image'] img = Image.open(pic) detection=load_model(os.path.join(settings.BASE_DIR,'static/auto_chloro_model.h5')) test_img=image.load_img(img,target_size=(48,48)) test_img=image.img_to_array(test_img) test_img=np.expand_dims(test_img,axis=0) result=detection.predict(test_img) a=result.argmax() print(a) #models.py class image(models.Model): img = models.ImageField(upload_to="images_api", default="") def __str__(self): return self.product_name #forms.py class imageForm(forms.ModelForm): image = forms.ImageField() class Meta: model = image fields = ['image'] -
how can i use browser_cookie3 on deployed app (heroku)
if request.method=="POST": link=request.POST.get('link') try: link=link.replace("https://www","") link="https://mbasic"+link cookies = browser_cookie3.chrome(domain_name='.facebook.com') html=requests.get(link,cookies=cookies).content.decode('utf-8') s=BeautifulSoup(html,'html.parser') l=s.find('a', {'href': re.compile(r'/video_redirect/')}) url=l['href'] url="https://mbasic.facebook.com"+url print(url) return JsonResponse(json.dumps({'fblink': url}), safe=False) except ConnectionError: return JsonResponse(json.dumps({'error': 'Invalid Link','fblink': ''}), safe=False) deployment to heroku was successful. but when i ran the function, it gives me error 2021-11-05T22:11:32.239159+00:00 app[web.1]: Internal Server Error: /VideoDownloader/downloadFb 2021-11-05T22:11:32.239180+00:00 app[web.1]: Traceback (most recent call last): 2021-11-05T22:11:32.239181+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/secretstorage/init.py", line 72, in dbus_init 2021-11-05T22:11:32.239181+00:00 app[web.1]: connection = open_dbus_connection() 2021-11-05T22:11:32.239186+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jeepney/io/blocking.py", line 332, in open_dbus_connection 2021-11-05T22:11:32.239186+00:00 app[web.1]: bus_addr = get_bus(bus) 2021-11-05T22:11:32.239187+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jeepney/bus.py", line 53, in get_bus 2021-11-05T22:11:32.239187+00:00 app[web.1]: return find_session_bus() 2021-11-05T22:11:32.239187+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jeepney/bus.py", line 42, in find_session_bus 2021-11-05T22:11:32.239188+00:00 app[web.1]: addr = os.environ['DBUS_SESSION_BUS_ADDRESS'] 2021-11-05T22:11:32.239188+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/os.py", line 679, in getitem 2021-11-05T22:11:32.239189+00:00 app[web.1]: raise KeyError(key) from None 2021-11-05T22:11:32.239189+00:00 app[web.1]: KeyError: 'DBUS_SESSION_BUS_ADDRESS' 2021-11-05T22:11:32.239189+00:00 app[web.1]: 2021-11-05T22:11:32.239190+00:00 app[web.1]: The above exception was the direct cause of the following exception: 2021-11-05T22:11:32.239190+00:00 app[web.1]: 2021-11-05T22:11:32.239190+00:00 app[web.1]: Traceback (most recent call last): 2021-11-05T22:11:32.239190+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner 2021-11-05T22:11:32.239190+00:00 app[web.1]: response = get_response(request) 2021-11-05T22:11:32.239191+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response 2021-11-05T22:11:32.239191+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2021-11-05T22:11:32.239191+00:00 app[web.1]: File "/app/VideoDownloader/views.py", line 48, in downloadFb 2021-11-05T22:11:32.239191+00:00 app[web.1]: cookies = browser_cookie3.chrome(domain_name='.facebook.com') 2021-11-05T22:11:32.239192+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/browser_cookie3/init.py", line 632, in chrome 2021-11-05T22:11:32.239192+00:00 … -
Why does Django add a dollar sign in my URL pattern? (
I spent my entire day trying to fix this bug and I have no idea how to do it. I am trying to create a new markdown file and redirect the user to the new page after submitting the form. I tried to change the URL name, tried to change variable names but nothing works. The problem may be the fact that Django adds a dollar sign in my URL pattern but I am not sure about it because I have tried to give the URL the value of an existing page. I would appreciate a detailed explanation for this problem. my views.py: def entry(request, entry): entryPage = util.get_entry(entry) if entryPage is None: message = messages.warning(request, 'There is not a page with this name.') return render(request, 'encyclopedia/error.html', { 'entryTitle': entry, 'message': message }) else: return render(request, 'encyclopedia/entry.html',{ 'entry': markdowner.convert(entryPage), 'title': entry }) def new(request): if request.method == 'POST': # Get the form form = Post(request.POST) if form.is_valid(): # Clean the form title = form.cleaned_data['title'] lower_title = form.cleaned_data['title'].lower() text = form.cleaned_data['textarea'] entries = util.list_entries() # Check for existing entry for entry in entries: if lower_title == entry.lower(): message = messages.warning(request, "There is already a page with this name.") context = { … -
List & tuple aren't working despite addressing `django.core.excptions.ImproperlyConfigured: The TEMPLATE_DIRS setting must be a list or a tuple` error
I've been hitting a snag with my Django app. Running Python manage.py runserver in my development environment, I get this error: django.core.excptions.ImproperlyConfigured. The TEMPLATE_DIRS setting must be a list or a tuple. After changing TEMPLATE_DIRS to a tuple in settings.py as this TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) I got : TypeError('Invalid path type: %s' % type(value).__name__)TypeError: Invalid path type: tuple. I got a similar response when I changed it to a list. Meanwhile, running Python manage.py runserver outside the development environment I got: expected str, bytes or os.PathLike object, not tuple on both times I changed TEMPLATE_DIRS to a list and tuple. I should also add that my template files aren't loading. I get: Using the URLconf defined in myProject.urls, Django tried these URL patterns, in this order: accounts/ admin/ The current path, index/, didn't match any of these Here is the project tree: |_______myApp |______ |______pycache__ | |______migrations | |________init__ | |______admin | |______apps | |______models | |______tests | |______urls | |______views |______myProject | |________init__ | |______asgi | |______settings | |______urls | |______wsgi |______env |______static |______templates |______myApp |______index.html |______signup.html manage.py myProject/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('accounts/', include('accounts.urls')), path('admin/', admin.site.urls), ] myApp/urls.py from … -
I am having problems with crispy_forms and formsets
I am using django_crispy_forms and have 2 formsets within the main form. The formsets are generating & saving data correctly, except for the first row, the data is never saved. In the source of the page, the first row does not have an instance number and the second row has an instance number of 0. for example, the id of vegetationType for the first row is id_vegetation-prefix-VegetationType, for the second row it is id_vegetation-0-VegetationType. If I remove the formhelper from the html page ({% crispy formset_vegetation%} instead of {% crispy formset_vegetation formset_vegetation.form.helper%}, the formset renders correctly without the extra row at the top, but the rows are not formatted as an inline formset. Does anyone see what I am doing incorrectly? models.py class Landcover(models.Model): Site = models.ForeignKey(Site, on_delete=models.RESTRICT, default=None, blank=True, editable=True, verbose_name='1. Site Name') Recorders = models.ManyToManyField(ProjectStaff, default=None, verbose_name = '2. Recorders(s)', help_text='select all that apply') Date = models.DateField(default=None, verbose_name='3. Date') Latitude = models.DecimalField(max_digits=9, decimal_places=6, default=None, verbose_name='4. Latitude') Longitude = models.DecimalField(max_digits=9, decimal_places=6, default=None, verbose_name='5. Longitude') class VegetationLevels(models.Model): Landcover = models.ForeignKey(Landcover, on_delete=models.RESTRICT, default=None, editable=True) VegetationLevel = models.ForeignKey(VegetationLevel, on_delete=models.RESTRICT, default=None, verbose_name='Vegetation Level') VegetationType = models.ManyToManyField(VegetationType, default=None, verbose_name='Vegetation Types') class DensiometerReadings(models.Model): Landcover = models.ForeignKey(Landcover, on_delete=models.RESTRICT, default=None, editable=True) Latitude = models.DecimalField(max_digits=9, decimal_places=6, default=None) Longitude … -
How to route to specific viewset methods Django
I've been studying the viewset and router docs for Django and I can't figure out how to set up a route to access the method on a viewset. For example, here is my urls.py: from rest_framework.routers import DefaultRouter from users.views import (UserViewSet, testing) router = DefaultRouter() router.register(r"users", UserViewSet, basename="users") urlpatterns = [ path('testing', testing) ] And then this is my views file in my user directory @csrf_exempt class UserViewSet: def create(self): return JsonResponse({ 'the create endpoint' }) @csrf_exempt def testing(request): return JsonResponse({ "title": "My json res" }) Using postman, I can hit the endpoint example.com/testing and have the json response logged out. However, I try to hit example.com/users/create and I get a 404. I thought the basename propery when registering the viewset with the router would group all of the methods inside that class under that route path and then the methods would all be their own endpoint. Am I thinking about this incorrectly? Any help would be lovely as I am new to Django. I've mostly done Express and Laravel. Thanks!