Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
For loop in django html depending on the index (repeat every 3 times)
I am working with a bootstrap template for a django app <div class="row"> <div class="col-12"> <div class="card-deck-wrapper"> <div class="card-deck"> {% if posts %} {% for post in posts %} <div class="card d-block"> <img class="card-img-top" src="{{ post.image }}" height="200"> <div class="card-body"> <h5 class="card-title">{{ post.title }}</h5> <p class="card-text">{{ post.description }}</p> <p class="card-text"> <small class="text-muted">{{ post.creation_date }}</small> </p> </div> </div> <!-- end card--> {% endfor %} {% endif %} </div> <!-- end card-deck--> </div> <!-- end card-deck-wrapper--> </div> <!-- end col--> </div><!-- end row --> Mi main target is to repeat each "card" just 3 times, otherwise the templates looks awful, but have no idea how to iterate just 3 times, and at the 4th, 7th, 10th, and so on time, create a new "card-deck" to continue with post 4-5-6, then another "card-deck" for post 7-8-9 and so on Thank you! -
Django, The 'image' attribute has no file associated with it
I'm getting this strange error The 'image' attribute has no file associated with it. when I'm trying to register new user. I have a signal that creates profile for new user and when this error happens, user gets registered but profile is not created. Here is my code: #views.py def registration(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = RegistrationForm() return render(request, 'registration.html', {'form': form}) #models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_directory_path_ppic, null=True, blank=True) #signals.py: @receiver(post_save, sender=User) def create_profile(sender, instance, **kwargs): Profile.objects.create(user=instance) -
Probem to install psycopg2
I'm trying to install psycopg2 with pip3 install psycopg2 and getting this error It appears you are missing some prerequisite to build the package from source. You may install a binary package by installing 'psycopg2-binary' from PyPI. If you want to install psycopg2 from source, please install the packages required for the build and try again. after this I runned pip3 install psycopg2-binary but still getting this error I tried to run sudo apt install python3-dev libpq-dev and returned: Reading package lists... Done Building dependency tree Reading state information... Done python3-dev is already the newest version (3.8.2-0ubuntu2). Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: libpq-dev : Depends: libpq5 (= 12.6-0ubuntu0.20.04.1) but 13.2-1.pgdg20.04+1 is to be installed E: Unable to correct problems, you have held broken packages. I'm improving my English, be patient. -
How to use Google Maps with Django
I'm completely new to Django and maps, can someone help me with a guide or a project to refer and start. Want to implement Google maps with django to display a dynamic map on my homepage, I referred to the docs but can't figure out how to implement it -
How to add fields to the django user model
I am trying to add an 'address' field to the my user 'Profile' model, but only the email, first name and last name fields are appearing. forms.py: class RegisterForm(UserCreationForm): email = forms.EmailField() address = forms.CharField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'address', 'email', 'password1', 'password2'] models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username}' I have added the email field and it appears on the list, however, the address field doesn't appear -
How to abstract dash plotly component into another file with a callback?
Currently, I have my application python file separated with the specific component in the Django framework. I have seen a lot of examples writing each component with callback in the same file with the app python file. I am wondering how to write the update_output_div() function in a file with callback and let the app call it? Thank you so much! app = dash.Dash(__name__, external_stylesheets=external_stylesheets) app.layout = html.Div([ ... ]) @app.callback( Output(component_id='my-output', component_property='children'), Input(component_id='my-input', component_property='value') ) def update_output_div(input_value): return 'Output: {}'.format(input_value) if __name__ == '__main__': app.run_server(debug=True) -
Django logger settings
I am trying to create a log file for each APIs. I get the response from the API. But it not generate log files. In my logger_settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'large': { 'format': '%(username)s %(asctime)s %(levelname)s %(process)d %(pathname)s %(funcName)s %(lineno)d %(message)s' }, 'tiny': { 'format': '%(asctime)s %(message)s ' } }, 'handlers': { 'errors_file': { 'level': 'ERROR', 'class': 'logging.handlers.TimedRotatingFileHandler', 'when': 'midnight', 'interval': 1, 'filename': './logs/error.log', 'formatter': 'large', }, 'info_file': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'when': 'midnight', 'interval': 1, 'filename': './logs/info.log', 'formatter': 'large', }, }, 'loggers': { 'error_logger': { 'handlers': ['errors_file'], 'level': 'WARNING', 'propagate': False, }, 'info_logger': { 'handlers': ['info_file'], 'level': 'INFO', 'propagate': False, }, }, } In my views.py: def list(self, request, *args, **kwargs): try: logging.getLogger("info_logger").info(repr('try period list'), extra={ 'Start period list api requested by': self.request.user}) .... response['status_code'] = 200 logging.getLogger("info_logger").info(repr("End period list api inside else"), extra={ 'requested by': self.request.user}) return Response(response, status=status.HTTP_200_OK) except Exception as e: logging.getLogger("error-log").error(repr('try period list'), extra={ 'error in period list api requested by': self.request.user}) massage = str(e) response = get_error_details(massage) return Response(response) when I am hitting list API it create info.log file. But inside file(info.log) it showing nothing... :( I miss anything??? -
Django - Customize error email sent to admins using mail_admins in logging. Too much sensetive information
The current email that goes out to admins during errors contains sensitive information so I'd like to change course and instead include instructions on how to quickly view the log files and find the traceback. I'm not sure how to piggyback off the current functionality and add a custom message rather than the standard message. So any help would be awesome. -
Django/DRF endpoint to serve SVG static files
I'm building an API with Django and Django Rest Framework. I'm stuck in building an endpoint to serve a collection of SVG files (some fun emojis :P). These SVG files aren't stored in the DB (hence I don't have a Django Model for them), instead they are in the project's static folder where dey have their own sub-folder: | project | + static | | + assets | | | + emojis | | | | | smile.svg | | | | | laugh.svg | | | | | etc... I have tried different approaches but I'm not sure. One was the following view: # Python from os import listdir from os.path import isfile, join # Django from django.http import HttpResponse def list_emojis(request): emojis_path = 'project/static/assets/emojis/' emojis = [f for f in listdir(emojis_path) if isfile(join(emojis_path, f))] ret = [] for emoji in emojis: ret.append(open(emojis_path+emoji, 'r')) return HttpResponse(ret, content_type='multipart/form-data') This is returning a binary file downloaded (when I go to the URL with my browser) which looks like this: <_io.TextIOWrapper name='project/static/assets/emojis/094-user.svg' mode='r' encoding='UTF-8'><_io.TextIOWrapper name='project/static/assets/emojis/059-sad-11.svg' mode='r' encoding='UTF-8'><_io.TextIOWrapper name='project/static/assets/emojis/006-shooting-star.svg' mode='r' encoding='UTF-8'><_io.TextIOWrapper name='project/static/assets/emojis/120-briefcase.svg' mode='r' encoding='UTF-8'><_io.TextIOWrapper name='project/static/assets/emojis/016-monkey.svg' mode='r' encoding='UTF-8'><_io.TextIOWrapper name='project/static/assets/emojis/185-tongue.svg' mode='r' encoding='UTF-8'> I have never returned files from an API before. What would be the … -
Can DRF Simple JWT be used to validate a token it didn't generate?
I'm using @azure/msal-react for AAD authentication on the client. It returns an accessToken and an idToken that I need to send to my Django/DRF API where they need to be validated, user it belongs to found or created if they don't exist, and then a JWT issued back to allow further client-API communication. I'm currently sending the accessToken in the header as Authorization: Bearer <accessToken>. Because I have the following in my settings.py, I am getting Unauthorized: /api/v2/auth/aad_token/validate/: 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), The response says: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } It looks like it the DEFAULT_AUTHENTICATION_CLASSES is intercepting it and can't validate it, I assume because it is one it didn't generate. Due to this, I was about to start writing DRF custom authentication that subclasses BaseAuthentication, permitting the HTTP_AUTHORIZATION to be received where I can do with it what I need. However, I read the Microsoft documentation a few more times, these parts in particular: There are also several third-party open-source libraries available for JWT validation - there is at least one option for almost every … -
Django serialization of multiple big QuerySets into one json object
Hello I have this problem about serialization QuerySets for now I do it like that: I have 9 querys like that: s1 = S280000020E3120.objects.filter(date__range=[dateo, datee]).values('date', 'temprature') s1 = s1.filter(date__minute=20) |s1.filter(date__minute=40) |s1.filter(date__minute=00) ...[sinp]... And then I go list() on all of them result = { 'ds1':[ list(s1), S280000020E3120.objects.last().sensor.description, ], ...[sinp]... And at the end of view I go just return JsonResponse(result, safe=False) And this is slow and my raspberry is running all the time with usage of 100% memory and swap because of list() I guess. I tried to replace list() with django.core serializers like that: result = { 'ds1':[ serializers.serialize('json', s1), S280000020E3120.objects.last().sensor.description, ], ...[sinp]... But this didn't do the trick either, it was even slower than plain list(). With list() it take approximately 60s to serialize everything and output on the website. With serializers.serialize() it is approximately 80s. The whole 9 query take like split of a second to complete and return data. So my question is: Is there a way to do it better? How do I cut some time and memory usage? But mostly I care about time to be honest. -
how to sum many fieldes in django
hi i want to sum a student degree for all subject like below and stor it in to TotalSub TotalSub = (ArabicSub+EnglishSub+MathSub+GeographySub+SinceSub+ReliganSub) any idea her is my model class StudentDgree(models.Model): StdIDNumber = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') GroupNumber = models.SmallIntegerField(null=True,default=0000) StdName = models.CharField(max_length=250) ArabicSub = models.SmallIntegerField(null=True,default=None) EnglishSub = models.SmallIntegerField(null=True,default=None) MathSub = models.SmallIntegerField(null=True,default=None) GeographySub = models.SmallIntegerField(null=True,default=None) SinceSub = models.SmallIntegerField(null=True,default=None) ReliganSub = models.SmallIntegerField(null=True,default=None) TotalSub = models.SmallIntegerField(null=True,default=None) -
How do I query a Foreign key, but in reverse and list them in Django Rest Framework?
I'm having a hard time getting my head around this for some reason. I know how to do this in plain Django, but not sure how to do this in DRF. class Novel(models.Model): name = models.CharField(max_length = 100) image = models.URLField(blank = True) linkNU = models.URLField(blank = True) author = models.ForeignKey(Author, on_delete = models.CASCADE, null = True) category = models.ManyToManyField(Category) description = models.TextField(blank = True) slug = models.SlugField(primary_key = True, default = None, max_length=100) numOfChaps = models.IntegerField(default = 0) novelStatus = models.BooleanField(default = True) #True will be for Ongoing, False for Completed def __str__(self): return self.name Chapter Model looks like this class Chapter(models.Model): index = models.IntegerField(default = None, blank = True) text = models.TextField(max_length=None) title = models.TextField(max_length = 100) novelParent = models.ForeignKey(Novel, on_delete = models.CASCADE, verbose_name = "chapter") nextChap = models.BooleanField(default = False) novSlugChapSlug = models.CharField( max_length = 100, blank = True, default = None) def __str__(self): return f"Chapter {self.index} - {self.novelParent}" Right now this is what I have for ChapterSerializer but it doesn't work: class ChapterSerializer(serializers.ModelSerializer): novel = serializers.CharField(source = 'novelParent.name') novSlug = serializers.CharField(source = 'novelParent.slug') class Meta: model = Chapter fields = "__all__" # fields = ('index','title','text','nextChap','novel','novSlug','novSlugChapSlug') I've read around and feel like it probably is going to … -
Is there a way to use pandas in django without using models or db
This may be a stupid question but I need help with a project I'm working on (also english isnt my first language so bear with me...). I'm developing a web app with Django to perform sentiment analysis of live tweets (using tweepy) and I am using a form to get from user input the keyword to search from django import forms class TwitterForm(forms.Form): keyword = forms.CharField(max_length=50) And now I have to fetch tweets using this function here def get_tweets(self, query, count=100): tweets = tweepy.Cursor(self.api.search, q=query, lang="en", since='2021-01-01').items(count) cleaned_tweets = [self.clean_tweet(tweet.text) for tweet in tweets] sentiment_object = [TextBlob(tweet) for tweet in cleaned_tweets] #sentiment_object[0].polarity, sentiment_object[0] sentiment_values = [[tweet.sentiment.polarity, str(tweet)] for tweet in sentiment_object] #sentiment_values[0] Now, I run this code on Colab and everything worked, I printed the fecthed tweets with pandas. But how does it work on Django? I wrote down this code in views.py but I've literally no clue... def prediction(self, request): sentiment_df = pd.DataFrame(self.sentiment_values, columns=["polarity", "tweet"]) sentiment_df["analysis"] = sentiment_df["polarity"].apply(self.getAnalysis) #sentiment_df.head() if request.method=='POST': self.api = TwitterSentClass() t=request.POST['keyword'] result = self.api.get_tweets(query=t, count=100) return render(request,'myapp/prediction.html',{}) I searched everywhere on internet and google and Pandas is always used for Django models or queries...How do I use pandas to just print fetched live tweets? Thank … -
how to perform a query with filter in the django template
hello family by the way I am a beginner in web programming with the python language and its django framework my concern is to be able to display the information coming from the join of several tables or models in my case I have the following tables: Country table city table church table but I used the mptt for country and city and everything is working fine but I want to display the list of all the countries with their respective cities as well as all the churches for each city. this is where the great difficulty lies for the month. If there is someone who can help me I will be very very happy -
Django rest framework; how do you use the ID of a foreign key to create an instance through the serializer?
I have two serializers, one for Country and one for my model Foo, I want to save the object by using the foreign key for this model but it errors out whenever I try to validate. I have this class Actor(TLPWrappedModel, CommentableModel): label = models.CharField(max_length=56, unique=True) country_of_origin = models.ForeignKey(Country, on_delete=models.CASCADE) class FooSerializer(serializers.ModelSerializer): country_of_origin = CountrySerializer() class Meta: model = Actor fields = [ 'id', 'country_of_origin', 'label', ] class Country(models.Model): label = models.CharField(max_length=56, unique=True) iso_code = models.CharField(max_length=3, unique=True) class CountrySerializer(serializers.ModelSerializer): class Meta: model = Country fields = [ 'iso_code', 'label', ] And this is what I'm trying to do serializers = FooSerializer(data={'label': 'Foobar', 'country_of_origin': self.country.id}) serializers.is_valid() print(serializers.errors) print(serializers.validated_data) serializers.save() But I get this error {'country_of_origin': {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got int.', code='invalid')]}} is it possible to use the ID of a foreign key to validate and create the object using the serializer? -
When I enter 'python manage.py runserver' it takes a lot of time and shows "env: python: Argument list too long" on Mac terminal and pycharm
I just started learning Django after completing python. When I enter the command 'python manage.py runserver' it takes a lot of time and shows "env: python: Argument list too long" on Mac terminal and pycharm. How should I fix this? -
Django session Conflict between logged users
I am using the estructure below to login a custom user: usuario = Usuario.objects.get(pk=uuid) request.session['usuario_id'] = usuario.pk But some users are logging and using session of the other user. I have a lot number of the views per day, i belive be concurrency. Exemple: A "User B" logged and this User posted comments with "User X" session My config: VPS server: Nginx Gunicorn Postgres Memcached Somebody can help me? -
BrowsableAPIRenderer in Django 2.2 for function-based-views
I am new to Django rest Framework. I am trying to create a public POST api and on display it should also have the HTML form like it does with the class based views. Here is my view. @api_view(['POST']) @permission_classes([permissions.AllowAny, ]) @authentication_classes([]) @renderer_classes([JSONRenderer, BrowsableAPIRenderer]) def lead_create(request): serializer = LeadSerializer(data=request.data) if serializer.is_valid(): try: serializer.save() except Exception as e: return Response( str(e), status=status.HTTP_400_BAD_REQUEST ) return Response( {'message': 'Lead Successfully Saved'}, status=status.HTTP_201_CREATED ) My problem is the output is something like below: Why am I not getting the HTMLForm even when i have added the 'BrowsableAPIRenderer' renderer class -
Django REST framework - Adding Depth in Serializer gives Foreign Key Constraint Failed on POST data
I am having a model like this: class KioskShelfMapping(models.Model): mapped_shelf_basket_name_reference = models.ForeignKey(ShelfBasketMapping, on_delete=models.CASCADE, default=1) mapped_shelf_name = models.CharField(max_length=15, null=False, blank=False, default="default") mapped_kiosk_name = models.CharField(max_length=15, blank=False, null=False, default="default") shelf_position = models.PositiveSmallIntegerField(null=False, blank=False, default=0) and below is my Serializer: class KioskShelfMappingSerializer(serializers.ModelSerializer): class Meta: model = KioskShelfMapping fields = ['id', 'mapped_shelf_basket_name_reference', 'mapped_shelf_name', 'mapped_kiosk_name', 'shelf_position'] depth = 2 The issue I am facing is whenever I am adding the depth on POSTING some data to the model gives me FOREIGN KEY constraint failed But when I remove the depth field, I am able to POST the data to the model successfully. I tried searching for the same issue and found this and modified my serializer accordingly: class KioskShelfMappingSerializer(serializers.ModelSerializer): class Meta: model = KioskShelfMapping fields = ['id', 'mapped_shelf_basket_name_reference', 'mapped_shelf_name', 'mapped_kiosk_name', 'shelf_position'] depth = 2 def __init__(self, *args, **kwargs): super(KioskShelfMappingSerializer, self).__init__(*args, **kwargs) request = self.context.get('request') if request and request.method =='POST': print('Method is POST') self.Meta.depth = 0 print(self.Meta.depth) else: self.Meta.depth = 2 This doesn't seem to work. I still get the same error. Where am I going wrong? Thanks for you help in advance. -
Django app - sourcing static files from S3
I've tried every possible tutorial that I could find on the internet but I still can't figure out what I'm doing wrong. I'm trying to use AWS S3 in order to serve the static and media files for my app. The access to the bucket is public and seems to be working fine because I can access any of the files there in the browser. Furthermore, I'm able to download and save a file from there when running this command: import boto3 session = boto3.session.Session() s3 = session.client( service_name='s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, ) print(s3) s3.download_file(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key='research_files/abc.xlsx', Filename='research_files/abc.xlsx') The problem is that Django is not looking at AWS for the static files. I'm getting 404 errors as Django is unable to find the files on my local server: 127.0.0.1/:10 GET http://127.0.0.1:8000/static/css/material-kit.css?v=2.0.7 net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:13 GET http://127.0.0.1:8000/static/js/core/jquery.min.js net::ERR_ABORTED 404 (Not Found) I've added 'storages' to my list of apps and tried all kind of different AWS settings in my settings.py as you will see from the commented out lines below. settings.py: # Static files (CSS, JavaScript, Images) # STATIC_URL = '/static/' # MEDIA_URL = '/images/' # STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] # MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') … -
How to test a view that needs authentication with PyTest?
I am starting out with Django and I wanted to get my hands dirty with TDD. I am confused on whether this is the correct way to test a view, especially that I want to implement it in Heroku. I want to emphasize that I want to test the status code. Is this the right way to do so? Here is my code below @pytest.mark.django_db def test_get_personal_successful(client): headers = {"Authorization": "Bearer " + user["idToken"]} r = client.get("http://127.0.0.1:8000/personal-infos/", headers=headers) assert r.status_code == 200 Note that the assertion is successful in the code above. -
Apply django authentication for all views
I am trying to implement Django basic authentication for all of the views in my views.py file. Although I can add the authentication code snippet in every view, but it will not be easy to apply this to upcoming views. Is there any way that every view in my views.py will automatically check for the authentication? views.py def mgmt_home(request): ############################################################## # This code is repetitive ############################################################## if request.user.is_anonymous: return redirect("/login") ############################################################## test_name = Test.objects.all()[0].test_name metadata = { "test_name": test_name, } return render(request, "mgmt_home.html", metadata) Is there any way where I can avoid this repetitive code in all of my views? -
I need a text when your login "Your password incorrect"
Can you help me to understand logic : I need when I enter have a message near login form "Your password incorrect" "Your login incorrect. I have a base registration form with this messages: class RegistrationForm(auth_forms.UserCreationForm): """ A form that creates a user """ error_messages = { 'password_mismatch': 'Password mismatch.', } password1 = forms.CharField( label='Password', strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}) ) password2 = forms.CharField( label='Access password', widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), strip=False ) I think to write the same for login : Class AuthForm(AuthenticationForm): error_messages = { 'password_mismatch': ("Password mismatch" ), 'invalid_login': ("Invalid login"), } But I think it is not correct. my views.py this: class BaseRegistrationView(ActivationEmailMixin, generic.FormView): form_class = RegistrationForm @transaction.atomic def form_valid(self, form): self.new_user = form.save(commit=True) self.new_user = authenticate( username=form.cleaned_data['email'], password=form.cleaned_data['password1'], ) login(self.request, self.new_user) self.send_activation_email() return super().form_valid(form) # new class BaseLoginView(LoginView): authentication_form = AuthForm And html in templates: {% if field.is_hidden %} {% render_field field %} {% else %} <div class="form-group"> <label class="form-group__label"> {{ field.label }} {% if field.field.required %}* {% endif %} </label> {% if field.field.widget.input_type == 'checkbox' %} {% render_field field class="form-group__control" %} {% else %} {% render_field field class="input form-group__control" %} {% endif %} {% if field.errors %} {% for error in field.errors %} <div class="form-group__error"> {{ error }} </div> … -
Show error for django unique_together in CreateView form
I'm using Django CBV CreateView and have a unique_together setting on the model class Meta: unique_together = ('field1', 'field2',) When the user adds a non-unique new record, it triggers an error at the database level, which is a 500 error. I'd like to instead just explain to the user that their entry was a duplicate and to add something else. Any idea for an easy way to do this with CBV and the unique_together setting (or a validator)? I'd like to keep this at the model level so the unique check happens regardless if the user creates, edits, or if an admin does it in the Django admin. Thank you!