Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
display picutre in grid layout djang-admin
first, I am having issues with displaying thumbnails in Django-admin, I tried the code below but it is not working it seems, class Pictures(models.Model): image = models.ImageField(null=True) date_added = models.DateField(auto_now_add=True) organization = models.ForeignKey(Organisation,on_delete=models.CASCADE) def __unicode__(self): return f"{self}" @mark_safe def image_img(self): if self.image: return format_html('<img src="{0}" style="width: 60px; height:65px;" />'.format(self.image.url)) else: return format_html('<img src="" alt={0} style="width: 60px; height:65px;" />'.format("noimagefound")) image_img.short_description = 'Image' image_img.allow_tags = True class PicturesAdmin(admin.ModelAdmin): list_display = ('image', 'date_added','image_img') autocomplete_fields = ['organization'] list_display_links = ('date_added',) I also want to display these thumbnails in the grid layout, how can I achieve that any simple approach -
Django filter ListViews
I am still rookie.. This is my first experience with CBV. My goal is to create one template with list that i can filter by my models field, like Date, Category, and more. My first try was to create more than one ListView, each for category but it's just doesn't look and feel right and I can't find anything to solve that on Google or django documentation.. What am I missing? This is the code: class TaskListView(ListView): context_object_name='list' model=models.Task_app class TaskWorkListView(ListView): context_object_name='work' template_name='Tasks/Task_app_work.html' model=models.Task_app def get_queryset(self): return Task_app.objects.filter(Q(Category__exact='Work')) template: <table class="table"> <tr> <th scope="col">Task:</th> <th scope="col">Content: </th> <th scope="col">Hour:</th> </tr> {% for task in list %} <tr> <td scope="row"><a href="{{ task.id }}">{{task.Task_Name}}</a></td> <td scope="row">{{task.Content}}</td> <td scope="row">{{task.Start_Time|time:"G:i"}}</td> </tr> {% endfor %} </table>``` Thanks -
How to filter queryset by another's Model CharField?
I have three models which are related to each other. Now I want to query a set of Poller entries which is filtered by the categories_selected by the user that stores strings of poller_category. # Models class Category(models.Model): """ Holds all available Categories """ poller_category = models.CharField(max_length=30) class UserCategoryFilter(models.Model): """ Holds Categories selected by user """ user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.CharField(max_length=2000) class Poller(models.Model): """ Holds Poller objects """ poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) poller_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) # View def render_random_poller(request): # Get user category filter if logged in if request.user.is_authenticated: # Get the Users filter as a list of selections category_filter = UserCategoryFilter.objects.filter(user=request.user).values_list('categories_selected', flat=True) print(category_filter) # Get a Category instance filtered by user selection of categories category_instance = Category.objects.filter(poller_category__in=category_filter) print(category_instance) # Apply user's selection to the poller query and take 100 latest pollers qs_poller = Poller.objects.filter(poller_category__in=category_instance).order_by('-created_on')[:100] else: [...] However, print(category_instance) returns an empty queryset, even though print(category_filter) returns ['category_foo']. How to best build the queryset? -
Issue while creating Foreign Key constraint
Issue Details 'Can't create table django.clientauth_tblusers (errno: 150 "Foreign key constraint is incorrectly formed")') What am I doing? I created a tinyint auto increment field below but when referencing it in another table causing issue. Code in Model file class TinyIntField(AutoField): def db_type(self, connection): return "tinyint(3) AUTO_INCREMENT" class tblroles(models.Model): role_id = TinyIntField(primary_key=True, verbose_name = "role_id") name = CharField(max_length = 20) class tblusers(models.Model): user_id = BigAutoField(primary_key=True) role = ForeignKey(tblroles, on_delete = models.CASCADE) Code in Migration File migrations.CreateModel( name='tblroles', fields=[ ('role_id', clientauth.models.TinyIntField(primary_key=True, serialize=False, verbose_name='role_id')), ('name', models.CharField(max_length=20)) ], ), migrations.CreateModel( name='tblusers', fields=[ ('user_id', models.BigAutoField(primary_key=True, serialize=False)), ('role', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='clientauth.tblroles')), ], ), -
installing django in pycharm
Do I really need to install django in pycharm every time I'm going to run a project? I mean I already did it yesterday and today when I run in the terminal the "python manage.py runserver" it said that "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" Is there a way to install it just once so I can just run my project or is that how it really works?I'm sorry I am just a beginner please don't judge me. -
Django Rest Framework, group_by queries using .values(), and embedding a related record
I can't figure out how to embed a related record into a Django Rest Framework response when using .values() on a Django query set to return grouped by aggregated values. Sample Models, Serializers, and Viewset included below along with current response and a sample desired response. Each Trade has one security. Multiple trades can exist for a security. I have a need to display Trades individually and also grouped by security. When grouping by security, I want to return the embedded security in the response along with the aggregate values for the associated trades, but so far I can only get the security id returned. Any attempt to get the security itself in the response results in an exception 'int' object has no attribute 'pk' Trade model class Trade(models.Model): security = models.ForeignKey('Security') ticker = models.CharField( max_length=128, null=True, blank=True, db_index=True, ) shares = models.FloatField(db_index=True) value_usd = models.FloatField(db_index=True) days_to_trade = models.FloatField(db_index=True) trade_date = models.DateField( db_index=True, null=True, blank=True, ) Security model class Security(models.Model): name = models.CharField( db_index=True, blank=True, null=True, ) ipo_date = models.DateField( null=True, blank=True ) Trade View class TradeViewSet(viewsets.ModelViewSet): def get_queryset(self): // param and filter setup/defaults snipped for clarity ... qs = Trade.objects.filter(**qs_filter) // if group_by param is passed in, then group … -
'Photo' object is not iterable
I have a web page that show the details that is from my database, but when the user click on the view button, it did redirect me to the details page and get the id, but at the same time it give me an error 'Photo' object is not iterable, what is wrong with my code? How do I fix the error? Error: traceback error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/details/6/ Django Version: 2.2.20 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account.apps.AccountConfig', 'crispy_forms'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django_session_timeout.middleware.SessionTimeoutMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template E:\Role_based_login_system-master\templates\logisticbase.html, error at line 67 'Photo' object is not iterable 57 : &lt;/div&gt; 58 : {% endfor %} 59 : {% endif %} 60 : &lt;div id="home_body"&gt; 61 : {% block content %} 62 : 63 : {% endblock %} 64 : &lt;/div&gt; 65 : &lt;!-- Optional JavaScript --&gt; 66 : &lt;!-- jQuery first, then Popper.js, then Bootstrap JS --&gt; 67 : &lt;script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT 7abK41JStQIAqVgRVzpbzo5smXKp4Y fRvH+8abtTE1Pi6jizo" crossorigin="anonymous"&gt;&lt;/script&gt; 68 : &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"&gt;&lt;/script&gt; 69 : &lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"&gt;&lt;/script&gt; 70 : &lt;/body&gt; 71 : &lt;/html&gt; Traceback: File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in … -
django why getting this error 'RelatedManager' object has no attribute 'email_confirmed'?
When I am using user.email_confirmed I am not getting any error but when using user.userprofile.email_confirmed getting RelatedManager error. Why I am getting this error when trying to get user details from userprofile model? here is my code: class UserManagement(AbstractUser): is_blog_author = models.BooleanField(default=False) is_editor = models.BooleanField(default=False) is_subscriber = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) email_confirmed = models.BooleanField(default=False) #there is no error when obtaining email_confirmed object from abstract user model. class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile") email_confirmed = models.BooleanField(default=False) #I am using this for email verification class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.userprofile.email_confirmed) #error rising for this line #six.text_type(user.email_confirmed) #I am not getting error if I use this line ) account_activation_token = AccountActivationTokenGenerator() views.py ....others code if user is not None and account_activation_token.check_token(user, token): user.userprofile.email_confirmed = True #why it's not working and rising error? #user.email_confirmed = True #it's working user.save() .....others code -
Display only one instance of same object in model (Distinct other instances of same object)
I am building a simple question and answer site and I am trying to implement a functionality in which user can upload 4 answers But I am trying to hide show only any one answer And this is showing all the answers related to a question. For Example :- question_a has 4 answers then i am trying to show any one of them. models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) marked = models.BooleanField(booleanField) class Answer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question_of = models.ForeignKey(BlogPost, on_delete=models.CASCADE) body = models.CharField(max_length=30) views.py def page(request): query_2 = Answer.objects.filter(question_of__marked=True)[:1] context = {'query_2':query_2} return render(request, 'page.html', context) In this query I am trying to show Answers of qustions which have marked=True and i am also trying to show only one answer of a question But it is showing 4. And after using [:1] it is only showing result in all. I will really appreciate your Help. Thank You -
Method POST not allowed [DRF]
This is my User Model class User(AbstractBaseUser, PermissionsMixin, Base): user_id = models.AutoField(primary_key=True) email = models.EmailField(db_index=True, max_length=100, unique=True) is_advisor = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) And this is my UserProfile class UserProfile(Base): profile_id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile') first_name = models.CharField(null=True, blank=True, max_length=100) last_name = models.CharField(null=True, blank=True, max_length=100) This is my UserProfileSerializer class UserProfileSerializer: class Meta: model = UserProfile fields = "__all__" And this is my view class UserProfileViewSet(viewsets.ModelViewSet): queryset = UserProfile.objects.all() parser_classes = (MultiPartParser, ) serializer_class = UserProfileSerializer lookup_field = 'user' This is my urls.py router = SimpleRouter(trailing_slash=False) router.register(r'user', UserViewSet) router.register(r'user/profile', UserProfileViewSet) urlpatterns = [ path(r'user/activate', ActivateUser.as_view(), name='activate_user'), ] + router.urls When I try to create an User using the url http://localhost:8000/api/user/profile/2 I get detail : Method POST not allowed What am i doing wrong here? Any help appreciated. -
The .mp3 file that generated by AWS Polly does not run at all
I have made a rest API using Django Rest Framework. I gonna convert a sentence to speech using AWS Polly and tried to run it in my local environment. When I run the endpoint, a .mp3 file has generated in the root folder. The result message says "save success!". But the file does not work as well the file contains the size. I am hearing nothing. As actually the result file should work by Media player. I followed the AWS Polly article, [here][1] Class: class TexttoSpeechView(CreateAPIView): serializer_class = TexttoSpeechSerializer permission_classes = (IsAccessedUser,) def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): text = serializer.data.get('text') voice = "Mizuki" response = use_polly(text) if "AudioStream" in response: # Note: Closing the stream is important because the service throttles on the # number of parallel connections. Here we are using contextlib.closing to # ensure the close method of the stream object will be called automatically # at the end of the with statement's scope. with closing(response["AudioStream"]) as stream: output = os.path.join(BASE_DIR, "speech.mp3") data = stream.read() try: # Open a file for writing the output as a binary stream with open(output, "wb") as file: file.write(data) print("save success") except IOError as error: # Could not … -
How to restart a Django project after terminal shut down
I've been learning Django from a Youtube Tutorial. I have a good basis in python, but have never worked with this. we have been starting an app and ran a server with "python3 manage.py runserver" command. Everything was working fine. problem is that terminal shut down, and i have no idea how to just restart the server. I go to the same directory as we did the first time, activate my virtual environment, but when I type the runserver command, i face this error: ModuleNotFoundError: No module named 'main' I have no clue how to solve this. Any advice ? Thanks ! -
Django - 'AssertionError: .accepted_renderer not set on Response' on DRF endpoint with Middleware
So I wanted to create Middleware to add authentication to every endpoint automatically. It seems to be creating issues for Django Rest Framework endpoints using @api_view decorator. Whenever I run my unit tests for the below endpoint I get "AssertionError: .accepted_renderer not set on Response." How do I fix this so that my middlware works on both APIView classes and endpoints with @api_view decorator? View.py @api_view(['GET']) @swagger_auto_schema( operation_description="Get <count> most recent posts by category" ) def get_most_recent_posts_by_category(request, category, count): return Response(status=status.HTTP_200_OK) Middleware from datetime import datetime from rest_framework import status from rest_framework.response import Response from cheers.core.api.jwt_helpers import decode_cognito_jwt class CognitoMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_view(self, request, view_func, view_args, view_kwargs): auth = request.headers.get("Authorization", None) if not auth: return Response(dict(error='Authorization header expected'), status=status.HTTP_401_UNAUTHORIZED) parts = auth.split() if parts[0].lower() != "bearer": return Response(dict(error='Authorization header must start with bearer'), status=status.HTTP_401_UNAUTHORIZED) elif len(parts) == 1: return Response(dict(error='Token not found'), status=status.HTTP_401_UNAUTHORIZED) elif len(parts) > 2: return Response(dict(error='Authorization header must be Bearer token'), status=status.HTTP_401_UNAUTHORIZED) token = parts[1] try: res = decode_cognito_jwt(token) expiration = datetime.utcfromtimestamp(res['exp']) current_utc = datetime.utcnow() if current_utc > expiration: return Response(dict(error=f'current time:{current_utc} is after expiration:{expiration}', user_msg='Please login again'), status=status.HTTP_400_BAD_REQUEST) except Exception: # Fail if invalid return Response(dict(error="Invalid … -
TypeError: %i format: a number is required, not str (python, phonenumbers)
I'm trying to use phonenumbers, but how do I throw an exception so that it gets posted back to the post form? gives an error % i format: a number is required, not str instead of showing it as an error about incorrect filling in the form on the site models.py import phonenumbers def validate_phone_number(value): try: z = phonenumbers.parse(value, None) except phonenumbers.NumberParseException: print('NOT VALID 0') raise ValidationError(_('%(value) is not a valid phone number'), params={'value': value},) if not phonenumbers.is_valid_number(z): print('NOT VALID') raise ValidationError( _('%(value) is not a valid phone number'), params={'value': value}, ) class Storehouses(models.Model): phone = models.CharField(validators=[validate_phone_number], unique=True, max_length=17) views.py class StorehouseSettingsAddView(TemplateView): template_name = 'storehouse/settings/storehouse_settings_add.html' def get(self, request, *args, **kwargs): # get work good ... def post(self, request, *args, **kwargs): formOne = StorehouseAddCategoryForm(self.request.POST, prefix='one_form') if formOne.is_valid(): form_one = formOne.save(commit=False) form_one.save() return HttpResponseRedirect(reverse_lazy('storehouse_settings_add')) else: print('NotValid') context = self.get_context_data() formOne.prefix = 'one_form' context.update({'formOne': formOne}) return self.render_to_response(context) #error here gets to return self.render_to_response (context) but throws an error -
Group by date in Django
I am trying to achieve the result the SQL query SELECT UNIX_TIMESTAMP(DATE((FROM_UNIXTIME(`timestamp`)))) AS `x`, COUNT(`timestamp`) as y FROM somedb.events WHERE user_id=3 AND `timestamp` > 1612117800 AND `timestamp` < 1614450600 AND `kind`='food' GROUP BY `x` ORDER BY `x` desc; using Django ORM. Expected output: [ { "x": 1613759400, "y": 2 }, { "x": 1612463400, "y": 1 } ] Here is what I tried so far: queryset = events.objects.filter( user=request.user, timestamp__range=dates, kind=self.model.FOOD ) result = queryset.annotate( trunc_date_timestamp=Func(Value( TruncDate( Func( F('timestamp'), function='FROM_UNIXTIME', ) )), function='UNIX_TIMESTAMP', output_field=models.IntegerField() ) ).values(x=F('trunc_date_timestamp')).annotate(y=models.Count('x')).order_by('-x') This produces the output: [ { "x": 0, "y": 3 } ] and result = queryset.annotate( trunc_date_timestamp=Func( Func( F('timestamp'), function='FROM_UNIXTIME', output_field=models.DateField() ), function='UNIX_TIMESTAMP' ) ).values(x=F('trunc_date_timestamp')).annotate(y=models.Count('x')).order_by('-x') produces the output: [ { "x": 1613831760, "y": 1 }, { "x": 1613810160, "y": 1 }, { "x": 1612520520, "y": 1 } ] -
How to make API endpoints for stepwise continuous upload use case?
I have a good experience with Android Frontend REST API calls, but I am very new to Backend and learning Django Framework so I need help for designing the below API endpoints. For better understanding I have uploaded a video over here https://youtu.be/z87Hz1uHrYY. This is the solution which I was thinking of doing, ) HTTP-Method: POST EndPoint URL: /recipe/ Request Params: {"name":"Pizza"} "image": pizza.png Response Params: {"id":"123xyz"} // unique id ) HTTP-Method PATCH EndPoint URL: /recipe/123xyz/ Request Params: {"serving":2, "difficulty": "m", "prep_time": 80} Response Params: {"id":"123xyz", "serving":2, "difficulty": "m", "prep_time": 80} ) HTTP-Method: PATCH EndPoint URL: /recipe/123xyz/ingredients/ Request Params: [{"ingredient":”rice”, “amount”: “1/2”, “unit”: “g”},{"ingredient":”water”, “amount”: “1/2”, “unit”: “ml”}] Response Params: {"id":"123xyz", "serving":2, "difficulty": "m", "prep_time": 80, “ingredients”: [{"ingredient":”rice”, “amount”: “1/2”, “unit”: “g”, “index”:1},{"ingredient":”water”, “amount”: “1/2”, “unit”: “ml”, “index”:2}] } ) HTTP-Method: PATCH EndPoint URL: /recipe/123xyz/steps/ Request Params: [{"description":”abc”, “image”: “s3//step1.png”, "index": 1},{"description":”xyz”, “video”: “s3//step2.mp4”, "index": 2}] Response Params: {"id":"123xyz", "serving":2, "difficulty": "m", "prep_time": 80, “ingredients”:[{"ingredient":”rice”, “amount”: “1/2”, “unit”: “g”, “index”:1},{"ingredient":”water”, “amount”: “1/2”, “unit”: “ml”, “index”:2}], "steps":[{"description":”abc”, “image”: “s3//step1.png”, "index": 1},{"description":”xyz”, “video”: “s3//step2.mp4”, "index": 2}]} These are the API breakdowns that I can think of with the questions below. ) How to handle reordering of ingredients and steps? ) When to … -
Django tinymce does not upload image in production
I have trouble uploading images in production mode with django tinymce. It does upload images in development mode but not in production. It Would be great if someone could me help me get this going. settings.py import os from pathlib import Path import json with open('/Users/omidsoroush/Desktop/config/config.json') as config_file: config = json.load(config_file) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config['SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', '49.12.203.203', 'www.example.org'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', 'blog.apps.BlogConfig', 'pytutorial.apps.PytutorialConfig', 'users.apps.UsersConfig', 'sendemail', 'crispy_forms', 'tinymce', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'pypro.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'pypro.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'pypro_db', 'USER': 'postgres', 'PASSWORD': config['DB_PASS'], 'HOST': 'localhost', 'PORT': '5432', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': … -
Create object if not exists in Django ImportExportModelAdmin
I have these two models: Profile_model.py class Profile(models.Model): firstname = models.CharField(max_length=200, blank=False) lastname = models.CharField(max_length=200, blank=False) email = models.CharField(max_length=200, unique=True, blank=False) ... Investment_model.py class Investment(models.Model): invested = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) ... and I have this admin: Investment_admin.py class InvestmentResource(resources.ModelResource): ... firstname = fields.Field(attribute='profile', widget=ForeignKeyWidget(Profile, field='firstname'), column_name='firstname') lastname = fields.Field(attribute='profile', widget=ForeignKeyWidget(Profile, field='lastname'), column_name='lastname') email = fields.Field(attribute='email', widget=ForeignKeyWidget(Profile, field='email'), column_name='email') class Meta: model = Investment fields = ( 'firstname', 'lastname', 'email', 'invested',) export_order = fields class InvestmentAdmin(ImportExportModelAdmin, admin.ModelAdmin): ... resource_class = InvestmentResource ... I am using django's ImportExportModelAdmin for bulk imports and exports but when I try to import, I get this error: I get that its producing this error because the profile hasn't been created yet. But what do I have to do to implement an update_or_create inside the ImportExportModelAdmin? -
The best way to catch IntegrityError on admin page?
I am trying to catch IntegrityError in admin.py file, but cannot do it properly. Is there a way at all? Note, that I use UniqueConstraint for my recipe model, since I do not want duplicated tags and ingredients. For many to many fields in my Recipe Admin model I've used inliners. IntegrityError is raised when I specially try to create a recipe with two identical tags. from recipes.models import ( Recipe, Ingredient, Tag, RecipeIngredient, RecipeTag ) from django.contrib import admin class RecipeIngredientInline(admin.TabularInline): model = Recipe.ingredients.through class RecipeTagInline(admin.TabularInline): model = Recipe.tags.through class RecipeAdmin(admin.ModelAdmin): search_fields = ('name',) readonly_fields=('total_favorites',) list_filter = ('tags',) inlines = (RecipeIngredientInline, RecipeTagInline) @admin.display(empty_value='---empty---') def total_favorites(self, obj): return obj.userrecipe_set.all().count() def save_model(self, request, obj, form, change): # Here I am trying to catch the exception, but without joy. breakpoint() super().save_model(request, obj, form, change) class IngredientAdmin(admin.ModelAdmin): search_fields = ('name',) list_filter = ('measurement_unit',) class TagAdmin(admin.ModelAdmin): search_fields = ('name',) list_filter = ('slug',) class RecipeIngredientAdmin(admin.ModelAdmin): search_fields = ('recipe__name',) class RecipeTagAdmin(admin.ModelAdmin): search_fields = ('recipe__name',) admin.site.register(Recipe, RecipeAdmin) admin.site.register(Ingredient, IngredientAdmin) admin.site.register(Tag, TagAdmin) admin.site.register(RecipeIngredient, RecipeIngredientAdmin) admin.site.register(RecipeTag, RecipeTagAdmin) -
Change image size with a input range value in Django
I'm trying to make a range field that whenever the user changes its value, it is inserted as the size of an image. {% extends "base.html" %} {% load i18n %} {% load static %} {% load crispy_forms_tags %} {% block conteudo %} <script> function updateTextInput() { var value = document.getElementById("range").value; var img = document.getElementById('imageRange'); img.style.height = value updateTextInput() } function SetSize(porte){ var tamanho; switch (porte){ case 'pequeno': tamanho = 40 break; case 'medio': tamanho = 80 break; case 'grande': tamanho = 120 break; } document.getElementById("range").value = tamanho; updateTextInput(); } </script> <! -- page content ... -- > <form enctype="multipart/form-data" action="submit", method="POST">{% csrf_token %} <input type="number" class="form-control" name="pet-id" value="{{ pet.id }}" hidden> <div class="container"> <div class="form-group"> <label><b>{% trans "Porte" %}</b>:</label><br> <button class="btn btn-primary" style="color:black; font-size:70%" onclick="SetSize('pequeno')" type="submit" value="Submit">Pequeno porte</button> <button class="btn btn-primary" style="color:black; font-size:70%" onclick="SetSize('medio')" type="submit" value="Submit">Médio porte</button> <button class="btn btn-primary" style="color:black; font-size:70%" onclick="SetSize('grande')" type="submit" value="Submit">Grande porte</button><br><br> <table class="fixed"> <tr> <td><img src="https://cdn.pixabay.com/photo/2018/03/30/13/04/silhouette-3275316_960_720.png" height="150" /></td> <td style="vertical-align:bottom"><img id="imageRange" src="https://image.flaticon.com/icons/png/512/91/91544.png" height="80" /></td> </tr> </table> <input class="form-range" style="width:30%" id="range" type="range" min="40" step="0" max="120" oninput="updateTextInput();" > </div> The code in an isolated file is working perfectly. However, when including it in a Django template, it doesn't work. I tested and the functions are being … -
Instantiating new form object doesn't give me a new form (Django)
This problem suddenly happened and I have no idea what I'm doing wrong. I have a function-based view. It checks if a form is posted, creates a new model object, and is supposed to return an empty form. Problem is when I do form = EventForm() and print the form, it prints a form with previous values when last submitted! from django.shortcuts import render from .forms import EventForm from .models import Event def home(request): if (request.method =='POST'): form = EventForm(request.POST) if form.is_valid(): form.save() event_list = [] events = Event.objects.all() for event in events: event_list.append({ 'title': event.title, 'start': event.date.strftime("%Y-%m-%d") }) form = EventForm() print(form) # previously filled form!! context = { 'form': form, 'events': event_list } return render(request, 'cal/calendar.html', context) This is what is being printed: <tr><th><label for="title_id">Title:</label></th><td><input type="text" name="title" class="form-control" placeholder="Enter event title" id="title_id" maxlength="200" required></td></tr> <tr><th><label for="date_id">Date:</label></th><td><input type="date" name="date" class="form-control" id="date_id" required></td></tr> <tr><th><label for="title_id">Title:</label></th><td><input type="text" name="title" class="form-control" placeholder="Enter event title" id="title_id" maxlength="200" required></td></tr> <tr><th><label for="date_id">Date:</label></th><td><input type="date" name="date" class="form-control" id="date_id" required></td></tr> -
Deploying django + graphql to AWS EC2 with Nginx
Hi I have an issue with Graphql url after deployment to EC2 using Nginx and gunicorn So locally everything is working I can access: http://127.0.0.1:8000/graphql When I deploy that to EC2 I'm getting an error 404 not found (ec2-.........compute.amazonaws.com/graphql) Django urls.py urlpatterns = [ path('admin/', admin.site.urls), path('graphql' , jwt_cookie(csrf_exempt(GraphQLView.as_view(schema=schema, graphiql=True)))), path('', index), re_path(r'^.*', index) ] Nginx/site-enable/django server { listen 80; server_name ec2-.........compute.amazonaws.com; location = /favicon.ico { access_log off; log_not_found off; } # main django application location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/project/run.sock; } location /static/ { autoindex on; alias /home/ubuntu/project/static/; } } Thanks in advance! -
How to exclude deleted records in a model save?
I am using django.contrib.postgres.field.DateRangeField in a model with an exclusion constraint to make sure 2 dateranges don't overlap: class MyModel(models.Model): date_range = DateRangeField() class Meta: constraints = [ ExclusionConstraint( name='exclude_overlapping_periods', expressions=[ ('date_range', RangeOperators.OVERLAPS), ], ), ] This works, but fails ugly with an integrityError (as it should). I want to validate the model with a clean method to make a user friendly response: def clean(self): error_dict = {} if MyModel.objects.exclude(id=self.id).filter( date_range__overlap=self.date_range): error_dict['date_range'] = ValidationError( 'Range can not overlap with an existing period.', code='overlap_period') if error_dict: raise ValidationError(error_dict) This works, but not in the instance when I use a formset and one instance is deleted at the same time another is updated. How can I accomodate this? -
allow page access only for admin user Django
So I need to allow page access only for admin user in Django, I'm trying this piece of code to use in app views.py, but its not working well.. from django.shortcuts import redirect def index(request): if not request.user.is_superuser: return redirect('https://xx.com') return render(request, 'scan_debug/index.html') -
Javascript - how to process argument within innerHTML iframe?
I have the following snipped at my Django HTML template: <script> function PlayTrack() { document.getElementById("iframeMusicPlayer").innerHTML = "<iframe src=\"{% url 'stream_audio' pk=track.file.pk|safe|cypher_link_stream %}\" height=\"250\" width=\"325\" ></iframe>"; } </script> <button type="button" class="btn" onclick="PlayTrack()"><i class="fal fa-play"></i></button> As you can see I have src="{% url 'stream_audio' pk=track.file.pk|safe|cypher_link_stream %}" set as src. But actually I want to have this as a argument like so (pseudo code): <script> function PlayTrack(track) { document.getElementById("iframeMusicPlayer").innerHTML = "<iframe src=\"$track\" height=\"250\" width=\"325\" ></iframe>"; } </script> <button type="button" class="btn" onclick="PlayTrack(track={% url 'stream_audio' pk=track.file.pk|safe|cypher_link_stream %})"><i class="fal fa-play"></i></button> How can I format my JS code so that I can simply pass the url as argument into the innerHTML iframe call?