Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I use django channels for background tasks
I am seeing that people are using celery in django for background tasks. But i want to know that is there any way to do background tasks in django with django-channels so please tell me how do i do it. -
Django 404: Uploaded images to admin page in prod not reflected on blog
Now this was working smoothly in dev, but I keep getting the Error 404 in my apache2 prod machine while uploading images from the Django admin page. I see the images get added to my /media/images/ folder from the admin upload, but it fails to load on the website. Is this a permission issue? This is my folder structure within /var/www/: app |_app |_media |_images |_file.png |_static This is my settings.py specification for media: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\','/') This is my urls.py specification: urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [..] (Note: Please request further info in the comments, will keep adding on as-need basis) -
integerity error in django(i think its about that new foregn key)
im have post model and a profile model on profile model i have a OneToOneField this is my profile model: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): GENDER_CHOICES = [('boy', 'پسر'), ('girl', 'دختر'), ('i prefer not to say', 'ترجیح میدهم نگویم')] user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='profile_pictures', blank=True, default='default.jpg') name = models.CharField(max_length=30) age = models.IntegerField(default="0") birth_day = models.CharField(max_length=30)#DateField(blank=True) gender = models.CharField(max_length=20, choices=GENDER_CHOICES) address = models.CharField(max_length=30, blank=True, default="---") bio = models.TextField(max_length=300, blank=True, default="---") phone = models.IntegerField(blank=True, null=True) skills = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم") favorites = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم") favorite_books = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم") favorite_movies = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم") favorite_musics = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم") favorite_sports = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم") and this is my post model: from django.db import models # from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse from taggit.managers import TaggableManager from user.models import Profile class Post(models.Model): STATUS_CHOICES = [('published', 'published'), ('draft', 'draft')] title = models.CharField(max_length=60) slug = models.CharField(max_length=120, unique=True) image = models.ImageField(blank=True, upload_to="posts_images", null=True) image_alt = models.CharField(max_length=35, blank=True, null=True) body = models.TextField() date = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) publish_date = models.DateTimeField(default=timezone.now) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') author = models.ForeignKey(Profile, on_delete=models.CASCADE) tags … -
Django Web API Call Server Pagination Issue
So I am trying to make a call on an API endpoint that could return results to a template in the range of 0 - 450,000 items. The API has a search endpoint as so, https://api.rawg.io/api/games?search=rimworld, and since this only results in 12 games, there's only one page and my function works as expected. When there are more than 20 results, the max allowed per page for this API (RAWG.IO API). This results in the JSON having a "next" key with something like this, https://api.rawg.io/api/games?page=2&search=grand. I cannot for the life of me figure out how to get the data from any of the pages past page 1. I have resorted to using JS to write this function, but I much rather use a Django view. I run into the same issues, where I can't collect past the first page. Whenever there is more than one page, my memory usage skyrockets, the page doesn't show any results, and the loading icon runs forever. There's either a memory leak or the resulting dict that I'm storing these in to display is just that huge. Whether someone can give me some insight in either JS or Python, I'm sure I can figure out … -
sorting of queryset with direction in django rest framework
Request from client side(tabulator) come with query param 'filters[0][value]' for filtering and 'filters[0][dir]' for direction, filtering works but sorting doesn't. Following are my code class UserSerializerView(generics.ListAPIView): model = User serializer_class = UserSerializer pagination_class = CustomPagination filter_backends = [filters.OrderingFilter] ordering_fields = ['username', 'email', 'is_approved'] ordering = ['username', 'email', 'is_approved'] def get_queryset(self): queryset = User.objects.exclude(is_staff=True) names = self.request.query_params.get('filters[0][value]', None) if names: queryset = queryset.filter( Q(username__icontains=names) | Q(first_name__icontains=names) | Q(last_name__icontains=names)) return queryset -
Django prefetch_relatad with ManyToMany field
I have this two models im my django application (latest version). class Company(models.Model): trade_name = models.CharField(....) focal = models.ManyToManyField(Focal) class Focal(models.Model): name = models.CharField(....) Django automaticaly created a third table to conect the models: company_focal. I want to implement the prefetch_related in the admin queryset. I`ve been trying something like this, but it didnt worked well. def get_queryset(self, request): queryset = super(FocalAdmin, self).get_queryset(request) return queryset.prefetch_related('company') How to correctly do it? -
Unable to access Media files in django template
I am trying store a set of files manually in media folder and access them through path in a template. Here goes my settings for media MEDIA_URL="/media/" MEDIA_ROOT=os.path.join(BASE_DIR,"media") Here is my project urls urlpatterns = [ path('admin/', admin.site.urls), path('',include('books.urls')), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) Here goes my template code <div class="category-img"> <img src="/media/logo.png" alt=""> </div> And there is no image displayed .Media folder has logo.png file in it.I got following error. Internal Server Error: /media/bordered.jpg/ Traceback (most recent call last): File "C:\Users\Sriram\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Sriram\anaconda3\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Sriram\Desktop\books_site\books\views.py", line 42, in bookinfo book["description"]=descriptions[zonar][books[zonar].index(book_name)] KeyError: 'media' -
Could not resolve URL for hyperlinked relationship using view name "book-detail"
Previously I was using ModelSerializer and there were no error. When I replaced it with HyperlinkedModelSerializer this error was thrown Could not resolve URL for hyperlinked relationship using view name "book detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. this is serializers.py file: class BookSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Book fields = ['id', 'url', 'title', 'subtitle', 'isbn'] model.py class Book(models.Model): title = models.CharField(max_length=250) subtitle = models.CharField(max_length=250) author = models.CharField(max_length=100) isbn = models.CharField(max_length=13) def __str__(self): return self.title views.py class BookListView(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer and urls.py router = routers.DefaultRouter() router.register('books', BookListView) app_name = "books" urlpatterns = [ path('', include(router.urls)), ] view name book-detail doesn't exist in my views, probably Django created it automatically and I don't know where to find and debug it? Thank you. -
How to install Pillow in Django can anyone help me by step to step. i am using mac os 10.15 catalina
i am getting error ERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/_c/881z7d3138d5s14sgxctc_y40000gn/T/pip-install-w34kt0to/pillow/setup.py'"'"'; file='"'"'/private/var/folders/_c/881z7d3138d5s14sgxctc_y40000gn/T/pip-install-w34kt0to/pillow/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/_c/881z7d3138d5s14sgxctc_y40000gn/T/pip-record-sun2k_so/install-record.txt --single-version-externally-managed --compile --install-headers /Library/Frameworks/Python.framework/Versions/3.9/include/python3.9/Pillow cwd: /private/var/folders/_c/881z7d3138d5s14sgxctc_y40000gn/T/pip-install-w34kt0to/pillow/ Complete output (172 lines): running install running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.9 creating build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MpoImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageMode.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PngImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/XbmImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PcxImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/SunImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/SpiderImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/TarIO.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/FitsStubImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MpegImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/BdfFontFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/GribStubImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageStat.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PixarImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/GimpPaletteFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageColor.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ContainerIO.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MspImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MicImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/_version.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImtImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/GifImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PalmImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageQt.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageMath.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PaletteFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/FontFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PdfParser.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ExifTags.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageCms.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/FpxImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageChops.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/BufrStubImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PSDraw.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PcdImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageFilter.py … -
django this is not working.. image is not showing in the page
I am trying to make simple webpage but I am unable to load the image in the page <div class="background_image" style="background-image:url({% static 'static/images/home_slider.jpg'%})"></div> -
Django Oscar version updated automatically
I am learning about Django Oscar. I was following a tutorial yesterday that is using Django Oscar version 1.6. I followed all the instructions in the tutorial. It was working fine yesterday. Now, when I ran my project today using python manage.py runserver, I got the error about using get_core_apps which has been removed in Django Oscar 2. I ran pip freeze to see the version of Django Oscar installed on my device and it said 2.0.2. Was it updated automatically? I did not make any changes to the project since working on it yesterday. -
Django - Replace None by an empty string on the CharField model - best practices
I've decided to review my Django App and I found some issues in my models. My issue is related to the CharField blank and null options. I was reading about best practices in Django and I've just found out that I was doing everything wrong. Many posts here explain that we should not use blank and null options on CharField at the same time. To follow the rule I deleted the null=True and kept just blank=True Here comes my doubt: I'm populating my DB from a web scrape code. Sometimes the CharField options are returned as None from the website and when my code tried to send it to the DB (I am not doing it in Forms) I get the Invalid Format error telling me that I shouldn't use None - because I took of the null=True. I've read some stuff about it and figure out one solution, which I'm presenting here to hear from you, guys/girls. Is this the best approach? I feel like Django might have something out of the box for this very common situation. class Empresa(models.Model): #I've chosen just some fields to keep it simple userstelegram = models.ManyToManyField(UserTelegram, blank=True) nome = models.CharField(max_length=150, blank=True) denominacao_social = … -
my django web app is working fine on local host but showing at runtime on pythonanywhere it's error log is showing this error
df_path = request.POST.get('path') dataframe = pd.read_csv(df_path) This is the code which is showing this error when hosted on pythnanywhere. Is there anything I am missing while hosting ? I have tried several things but I am stuck at this point... Internal Server Error: / Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/gauravraj/Outlier_Detection (copy)/Outlier_Detection/views.py", line 75, in home dataframe = pd.read_csv(df_path) File "/usr/lib/python3.8/site-packages/pandas/io/parsers.py", line 685, in parser_f return _read(filepath_or_buffer, kwds) File "/usr/lib/python3.8/site-packages/pandas/io/parsers.py", line 439, in _read fp_or_buf, _, compression, should_close = get_filepath_or_buffer( File "/usr/lib/python3.8/site-packages/pandas/io/common.py", line 224, in get_filepath_or_buffer raise ValueError(msg.format(_type=type(filepath_or_buffer))) ValueError: Invalid file path or buffer object type: <class 'NoneType'> -
How to run a series of manage.py django commands with gunicorn + nginx?
I have a django project. To run, I execute python3 manage.py runserver , then I run python3 manage.py listener. I would like to run this with gunicorn + nginx. I am only able to run the first portion python3 manage.py runserver with my gunicorn + nginx setup and not sure how to include the second command python3 manage.py listener. When running with gunicorn only, I run the command gunicorn --bind 0.0.0.0:8000 slack.wsgi:application and that loads the app locally fine for the runserver part but not sure how to include the second command 'listener'. nginx is also setup but same like above, only runs the first part for runserver. This is the tutorial I have been following for my django project https://github.com/subodh-malgonde/slack-django-tutorial Any help is greatly appreciated. I tried using subprocess in the views.py to execute python3 manage.py listener but could not get that to work and just got "django.request ERROR Internal Server Error:". I know this is not the right way to do it but could not finding anything online. Thanks -
I cant get this template due to this views.py loop in django
I am a new developer in Django type programming. I have a problem with sending this value to the database. What I want to do is the value is dynamically sent from the website then the process of the data will be sent to the database with the models.py in (processing folder) from the views.py(app folder) through forms.py in (processing folder). this is my code in models.py (processing folder) class Accountdetail(models.Model): firstname = models.CharField(max_length = 20) lastname = models.CharField(max_length = 20) address = models.CharField(max_length = 100) city = models.CharField(max_length = 50) country = models.CharField(max_length = 50) postalcode = models.CharField(max_length = 20) position = models.CharField(max_length = 50) university = models.CharField(max_length = 50) course = models.CharField(max_length = 50) secondschool = models.CharField(max_length = 50) primaryschool = models.CharField(max_length = 50) aboutme = models.CharField(max_length = 300) this is my form.py(processing folder code) from django.forms import ModelForm from django import forms from .models import Accountdetail class AccountForm(ModelForm): class Meta: model = Accountdetail fields = '__all__' def __init__(self, *args, **kwargs): super(AccountForm, self).__init__(*args, **kwargs) self.fields['firstname'].widget=forms.TextInput( attrs={ "placeholder" : "First Name" } ) self.fields['lastname'].widget=forms.TextInput( attrs={ "placeholder" : "Last Name" } ) self.fields['address'].widget=forms.TextInput( attrs={ "placeholder" : "Address" } ) self.fields['city'].widget=forms.TextInput( attrs={ "placeholder" : "City" } ) self.fields['country'].widget=forms.TextInput( attrs={ "placeholder" : … -
Git push heroku doesn't run properly
So I am pushing files from a git repository to a heroku git repository. However, when I run this, things go normal, then errors start happening. -----> Installing python-3.8.6 -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip Collecting dj-database-url==0.5.0 Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) Collecting Django==3.1.2 Downloading Django-3.1.2-py3-none-any.whl (7.8 MB) Collecting gunicorn==20.0.4 Downloading gunicorn-20.0.4-py2.py3-none-any.whl (77 kB) Collecting psycopg2-binary==2.7.7 Downloading psycopg2-binary-2.7.7.tar.gz (428 kB) Collecting whitenoise==5.2.0 Downloading whitenoise-5.2.0-py2.py3-none-any.whl (19 kB) Collecting asgiref~=3.2.10 Downloading asgiref-3.2.10-py3-none-any.whl (19 kB) Collecting pytz Downloading pytz-2020.1-py2.py3-none-any.whl (510 kB) Collecting sqlparse>=0.2.2 Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB) Building wheels for collected packages: psycopg2-binary Building wheel for psycopg2-binary (setup.py): started Building wheel for psycopg2-binary (setup.py): finished with status 'error' ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-uvz1913i/psycopg2-binary/setup.py'"'"'; __file__='"'"'/tmp/pip-install-uvz1913i/psycopg2-binary/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-0ilqbc20 cwd: /tmp/pip-install-uvz1913i/psycopg2-binary/ Complete output (72 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.8 creating build/lib.linux-x86_64-3.8/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/sql.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_ipaddress.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/psycopg1.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_range.py -> … -
Heroku Local works fine and it is connected to Postgresql DB hosted by Heroku. Once attempt to deploy, got error code=H14 status=503
I hope I can get some help in what should be my approach to deploy through Heroku. I have a Python app with Django framework and Postgresql db. When I changed the environment from development to production, I used gunicorn to set up a wsgi path and then allowed the host in settings.py. I created a Procfile where manage.py lives, migrated my db to postgres and installed whitenoise middleware to collect static files. When I run Heroku local to verify that my app is running, everything works correctly. Static files are located, can access the database and the localhost is ‘0.0.0.0’. When I push to Heroku, I get the link where the app is released, and verifying deployment is done. Once I click on the link I see the error page displayed. ‘Heroku logs --tail’ gets me an error code=H14 status=503. I know It has to be an issue with Procfile because it is not in my root directory. When I attempt to move Procfile to the root directory, gunicorn stops working because it doesn’t find a wsgi file nor manage.py. How can I fix this conflict and what should be my approach? I don’t understand why everything works perfectly … -
Unable to authenticate user from oracle database (python 3.8.3 and django 3.0)
how do I a login in from the database? I need to use two elements (user and password) of a table from Bd to perform a login. Someone know the format of what i need to put in models.py, views.py or more specific, the things that i need to do a correct login, thanks. -
Django: How to create a Customized Reference code for each Order?
I have an E-commerce project and I am trying facilitate reading order reference codes for me, so currently I am generating random figures as following: My current code generated is: def create_ref_code(): return ''.join(random.choices(string.ascii_lowercase + string.digits, k=6)) model.py class Order(models.Model): ref_code = models.CharField(max_length=20, blank=True, null=True) ordered_date = models.DateTimeField() def __str__(self): return self.user.username Reference code is generated every time a payment is executed: def payment_complete(request): ---------payment codes------------- payment.save() # assign the payment to order order_items = order.items.all() order_items.update(ordered=True) for item in order_items: item.save() order.payment = payment order.ordered = True order.ref_code = create_ref_code() order.save() My question is how do I generate a code in the following format that includes that day, month, year, hour, minute and a digit that increases with a new transaction DDMMYYHHMMXXX Day, Month, Year, Hour, Minute,3 digits starting with 001 and increasing with each new order. How can I adjust my function to reach this? -
'ObtainAuthToken' object has no attribute 'request'
Currently i wanna use viewset and auth, and generating token using obtainauthtoken via apiview, but it is returning error 'ObtainAuthToken' object has no attribute 'request' How to solved it? This is the version that i use Django==3.1.2 djangorestframework==3.12.1 The Code class LoginViewSet(viewsets.ViewSet): """Checks email and password and returns an auth token.""" serializer_class = AuthTokenSerializer def create(self, request): """Use the ObtainAuthToken APIView to validate and create a token.""" return ObtainAuthToken().post(request) -
I am getting an additional message after I ran server of windows shell
Though I am successfully able to run my server from shell but I also got one more message with that . I am attaching the message below. Help me figure it out what it really wants to say and will it create any problems in the future for me? [10/Oct/2020 05:11:37] "GET / HTTP/1.1" 200 16348 [10/Oct/2020 05:11:37] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [10/Oct/2020 05:11:37] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304 [10/Oct/2020 05:11:37] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348 [10/Oct/2020 05:11:37] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564 Not Found: /favicon.ico [10/Oct/2020 05:11:37] "GET /favicon.ico HTTP/1.1" 404 1978 -
Exclude records on manytomany relationship in Django
I have two models with a many to many relationship as shown: class Season(models.Model): name = models.CharField(max_length=255) total_weeks = models.IntegerField() active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class League(models.Model): name = models.CharField(max_length=50) code = models.CharField(max_length=10, null=True) admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='admin_id') users = models.ManyToManyField(settings.AUTH_USER_MODEL) season_set = models.ManyToManyField(Season, through='LeagueSeason') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.code = uuid.uuid4().hex[:6].upper() super(League, self).save(*args, **kwargs) class LeagueSeason(models.Model): GANADOR = 1 RESULTADO_EXACTO = 2 Type = ( (GANADOR, 'Escoger ganador'), (RESULTADO_EXACTO, 'Escoger resultado exacto'), ) league = models.ForeignKey(League, on_delete=models.PROTECT, related_name='leagues_set') season = models.ForeignKey(Season, on_delete=models.PROTECT, related_name='season_set') season_type = models.IntegerField(choices=Type, default=GANADOR) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = "leagues_seasons" def __str__(self): return 'League {} - {}'.format(self.league.name, self.season.name) My season serializers are like this: class LeagueSeasonSerializer(serializers.ModelSerializer): class Meta: model = LeagueSeason fields = [ 'league_id', 'season_type' ] class SeasonsSerializer(serializers.ModelSerializer): season_set = LeagueSeasonSerializer(many = True) class Meta: model = Season fields = '__all__' All is good and fine, but when I make a request /league/7/seasons I get this result: [ { "id": 1, "season_set": [ { "league_id": 7, "season_type": 1 }, { "league_id": 8, "season_type": 2 } ], "name": "2020 Season", "total_weeks": 21, … -
smtplib.SMTPAuthenticationError in Django with pythonanywhere
I have made a little Django app which I plan to use on a real website here. Register an account. A dummy account if you want, log out and click on the link to reset your password. If you enter in your email, You will get an error like this First of all, I don't want to see this error from pythonanywhere. I want my own custom 500 InternalServerError which is this one: I don't know why I get an error because everything works fine on the localhost. So what I really wanted to do is notify the staff users on that are registered about an InternalServerError like so def error_500_view(request): staff_members = [i.email for i in Person.objects.all() if i.is_staff] send_mail( '500 Error', 'There was an InternalServerError in our website. Let\'s fix it!', 'testkenny00@gmail.com', staff_members, fail_silently=False, ) context = { 'title': 'InternalServerError' } return render(request, '500.html', context) But that gave me an smtplib.SMTPAuthenticationError. Again, this also works on the localhost. The registered staff users get an email from the localhost that there is an 500 error. When I hosted this on PythonAnywhere I got this smtplib.SMTPAuthenticationError. -
Django createview creates extra instance without foreign keys
I am using Django createview to create Bid items in an auction site. The createview will create the new object but it creates an extra object instance without the corresponding foreign keys. I am using @staticmethod to to ascertain whether the bid being submitted is indeed the highest bid then create in related Listing. Thank you in advance if you could point what im doing incorrectly. models.py class Bid(TimeStampMixin): """model representing bid obj""" auction = models.ForeignKey( Listing, on_delete=models.SET_NULL, related_name='offer', null=True) bidder = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='bid_user') amount = models.PositiveIntegerField() objects = BidQuerySet.as_manager() def __str__(self): return f"{self.amount} in Listing No: {self.auction.id}" class Meta: ordering = ['amount'] @staticmethod def high_bid(auction, bidder, bid_amount): """util method to ascertain highest bid in auction then create in related auction obj :param auction---listing being bid on, bid__auction :param bidder---user bidding :param amount--- current highest bid """ ###error checks, is auction running? is current bid less than start bid? etc if bid_amount < auction.start_bid: return if (auction.highest_offer and bid_amount < auction.highest_offer.amount): return if bidder.id is auction.user.id: raise PermissionDenied ##after checks create highest bid object in listing model new_high_bid = Bid.objects.create( auction= auction, bidder = bidder, amount = bid_amount ) auction.highest_offer = new_high_bid auction.save() class Listing(TimeStampMixin): user = … -
ModelMultipleChoiceField django and debug mode
i'm trying to implement a ModelMultipleChoiceField in my application, like that: Link model.py class Services(models.Model): id = models.AutoField(primary_key=True) type = models.CharField(max_length=300) class Professionals_Services(models.Model): professional = models.ForeignKey(User, on_delete=models.CASCADE) service = models.ForeignKey(Services, on_delete=models.CASCADE) form.py class ProfileServicesUpdateForm(forms.ModelForm): service = forms.ModelMultipleChoiceField(required=False, queryset=Services.objects.all()) class Meta: model = Professionals_Services fields = ['service'] def clean(self): # this condition only if the POST data is cleaned, right? cleaned_data = super(ProfileServicesUpdateForm, self).clean() print(cleaned_data.get('service')) view.py class EditProfileServicesView(CreateView): model = Professionals_Services form_class = ProfileServicesUpdateForm context_object_name = 'services' template_name = 'accounts/edit-profile.html' @method_decorator(login_required(login_url=reverse_lazy('professionals:login'))) def dispatch(self, request, *args, **kwargs): return super().dispatch(self.request, *args, **kwargs) def post(self, request, *args, **kwargs): form = self.form_class(data=request.POST) if form.is_valid(): services = form.save(commit=False) services.save() html <select class="ui search fluid dropdown" multiple="" name="service" id="id_service"> {% for service in services_list %} <option value="{{ service.id }}">{{ service.type }}</option> {% endfor %} </select> For development i'm using Pycham Professionals(latest version) with docker, when i run the application and i try to make a POST the answer is: Cannot assign "<QuerySet [<Services: Services object (2)>, <Services: Services object (5)>, <Services: Services object (6)>, <Services: Services object (7)>]>": "Professionals_Services.service" must be a "Services" instance. But if i run the application in debug mode and with a breakpoints on the if form.is_valid(): the application works fine That's because …