Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django import export get() returned more than one
I have a small Django application with cities_light, smart_selects, and import_export. I am able to properly export from the admin site into csv files using resources and ForeignKeyWidget from import_export. However, there is something wrong with my import and I'm not sure how to fix it. When trying to import through the admin site from the same exported csv file, I get jobs.models.City.MultipleObjectsReturned: get() returned more than one City -- it returned 2!. This question is similar to this one but I still do not understand what is wrong. Would greatly appreciate if the responses contain links to the documentation that explain what I am doing wrong, since I've gone through ReadTheDocs but have been unsuccessful at finding my mistake. Thanks. models.py class Country(AbstractCountry): pass connect_default_signals(Country) class Region(AbstractRegion): def __str__(self): return self.name country = models.ForeignKey(Country, on_delete=models.PROTECT) connect_default_signals(Region) class SubRegion(AbstractSubRegion): pass connect_default_signals(SubRegion) class City(AbstractCity): def __str__(self): return self.name region = models.ForeignKey(Region, on_delete=models.PROTECT) connect_default_signals(City) class JobPost(models.Model): title = models.CharField(max_length=100) company = models.CharField(max_length=100) urlCompany = models.URLField(blank=True) urlApplication = models.URLField(blank=True) contactEmail = models.EmailField(max_length=100, blank=True) jobType = models.CharField(max_length=100, blank=True) country = models.ForeignKey(Country, on_delete=models.PROTECT, blank=True) region = ChainedForeignKey( Region, chained_field="country", chained_model_field="country", show_all=False, auto_choose=True, sort=True, blank=True ) city = ChainedForeignKey( City, chained_field="region", chained_model_field="region", show_all=False, auto_choose=True, sort=True, blank=True … -
how to get data from foreign key to save in database in django
I have two models that are related with many to many relationship. I need the data of the second model to be stored in the database when creating the object from the first model so that later if the values of the second model change, it will not affect the values we entered in the first model. How should I act? # models.py class First(models.Model): percent = models.IntegerField() two = models.ManyToManyField(Two, blank=True) class Two(models.Model): title = models.CharField(max_length=50, null=True) amount = models.PositiveIntegerField(null=True) # forms.py class FirstAddForm(forms.ModelForm): class Meta: model = First def save(self, commit=True): instance = super(FirstAddForm, self).save(commit=False) instance.percent = self.cleaned_data['percent'] / 100 . # How should I act? # . if commit: instance.save() self.save_m2m() return instance # views.py def FishDetailView(request, pk=None): first = First.objects.all() . . for i in First: two= Two.objects.filter(first__id=i.id) . . context = { 'first': first 'two': two, } -
Django DELETE Endpoint gives permission denied, but every other endpoint works fine
I tried to search around including how HTTP DELETE and POST are called. But can't seem to understand why DELETE endpoint doesn't work. The POST endpoint has the exact same Permissions and Serializer, but when I try to DELETE via Postman, it says permission denied. Doesn't make any sense. #this one works fine class PhoneNumberCreateApi(generics.CreateAPIView): permission_classes = [custompermission.IsStaff] queryset = Phone.objects.all() serializer_class = PhoneNumberSerializer #this one does not class PhoneNumberDeleteApi(generics.DestroyAPIView): permission_classes = [custompermission.IsStaff] queryset = Phone.objects.all() serializer_class = PhoneNumberSerializer Any insight is appreciated. Never seen this error before. -
Django: Reverse for 'download_excel/309' not found. 'download_excel/309' is not a valid view function or pattern name
I am currently working on designing a Django app that would allow a person to download an excel with data from a page. I am trying to connect a hyperlink to a view function but it keeps returning the reverse match. I am able to go directly to the url and it downloads the excel but when I can't load the index.html file because of the error. Am I naming the hyperlink wrong? urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('Excel/<int:study>', views.Excel, name='Excel'), path('download_excel/<int:study>', views.download_excel, name='download_excel'), ] index.html <html> <title>Download File</title> </head> <body> <enter> <h1>Download File using Django</h1> <a href="{% url 'polls:download_excel/309' %}">Download State Impulsivity Excel</a> </enter> </body> </html> views.py def download_excel(request, study): with BytesIO() as b: writer = pd.ExcelWriter(b, engine='xlsxwriter') Retrieve(study) df = pd.DataFrame(data) df.to_excel(writer, sheet_name='Sheet1') writer.save() Names(study) filename = str(name) + "_" + str(current_time) + ".xlsx" response = HttpResponse( b.getvalue(), content_type=mimetypes.guess_type(filename) ) response['Content-Disposition'] = 'attachment; filename=%s' % filename return response -
Django Apscheduler
I'm looking to use Django Apscheduler or Django Celery to allow a user to input a cron expression and add it to the jobs list to be run at the user specified time. I also would like the user to be able to edit the cron expression if needed down the road. From django apscheduler docs I'm aware updates and creates aren't registered till the server is restarted and I'm okay with the server being restarted nightly to import the new jobs. -
Object of type bytes is not JSON serializable when trying to return jwt_token
Really confused because this functionality was working a few days ago and I made no substantial changes to my code. I am getting this traceback: Traceback (most recent call last): File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response File "C:\Users\15512\anaconda3\lib\site-packages\django\core\serializers\json.py", line 105, in default return super().default(o) File "C:\Users\15512\anaconda3\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type bytes is not JSON serializable To summarize, I am sending a name to the Twilio library with the expectation of receiving a JWT_token. The API endpoint would then return a dict with a key: title and jwt_token This is what my view for the end point looks like: class TokenView(View): def get(self, request, username, *args, **kwargs): voice_grant = grants.VoiceGrant( outgoing_application_sid=settings.TWIML_APPLICATION_SID, incoming_allow=True, ) access_token = AccessToken( settings.TWILIO_ACCOUNT_SID, settings.TWILIO_API_KEY, settings.TWILIO_API_SECRET, identity=username ) access_token.add_grant(voice_grant) jwt_token = access_token.to_jwt() full_data = {'token': jwt_token} # print(type(jwt_token)) return JsonResponse(json.dumps(full_data), content_type="application/json", safe=False) I've also tried to have this in the return statement: JsonResponse({"token": jwt_token}) -
Django Rest Framework Ordering Filter by an element in nested list
I am using OrderingFilterBackend from django_elasticsearch_dsl_drf to order the results for the api call, i can order by fields and nested fields fine. Now i would like to order by a field in the first element in a nested list. So for each item in the list returned from the api get request the data structure looks like: { id: 1, events: [ { id:2, name: "test_1" }, { id:3, name: "test_2" } ] } I want to order by my_list[0].name. My serializers.py: class EventSerializers(serializers.ModelSerializer): id = serializers.UUIDField(read_only=True) name = serializers.CharField(read_only=True) class Meta: model = models.Event fields = ( 'id', 'name', 'created', 'updated' ) class OrganisationSerializer(WritableNestedModelSerializer): events = EventSerializers(many=True, required=False) class Meta: model = models.Organisation fields = ( 'id', 'events', 'created', 'updated' ) My views.py: class OrganisationViewSet(SearchWriteNestedViewSet): model = models.Organisation serializer_class = OrganisationSerializer queryset = models.Organisation.objects.all() document = OrganisationDocument filter_backends = [ OrderingFilterBackend ] ordering_fields = { 'id': None, "events": { 'field': 'events.name', 'path': 'events', } } I believe where i have gone astray is somewhere here ordering_fields = { 'id': None, "events": { 'field': 'events.name', 'path': 'events', } } i have tried 'field': 'events.0.name', 'field': 'events.[0].name' and 'field': 'events[0]name', I have searched for the answer but i cannot find … -
How we can use Drf SerializerMethodField with django-filters backend
Getting an error likes this. I am not able to understand that how to create a logic here please create some logic(for me it interesting). Here is the error: FieldError at /api/website/member/ Cannot resolve keyword 'is_you' into field. Choices are: about, address, age, avatar, blocked_author, blocked_person, blog, blogcategory, blogtag, bookmark_author, bookmark_person, children, city, country, created_at, date_joined, education, email, employement, ethnicity, eye_color, faq, favourite_author, favourite_person, first_name, gender, groups, hair_color, height, hidden_author, hidden_person, id, income, interests, is_active, is_online, is_online_show, is_staff, is_superuser, language, last_login, last_name, logentry, looking, password, phone, postal, province, relationship, religion, skin_color, smoke, sports, star, status, updated_at, user_permissions, username, verified, weight Here is the error: User model (Models.py) class User(AbstractUser): username = models.CharField('username', max_length=150, unique=True) email = models.EmailField('email address', unique=True, max_length=255) first_name = models.CharField(max_length=250, null=True, blank=True) last_name = models.CharField(max_length=250, null=True, blank=True) phone = models.CharField(max_length=15, null=True, blank=True) about = models.CharField(max_length=1000, null=True, blank=True) country = models.CharField(max_length=100, null=True, blank=True) province = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) postal = models.CharField(max_length=100, null=True, blank=True) address = models.CharField(max_length=500, null=True, blank=True) gender = models.CharField(max_length=500, null=True, blank=True) age = models.CharField(max_length=500, null=True, blank=True) is_online = models.BooleanField(null=True, blank=True) is_online_show = models.BooleanField(null=True, blank=True) looking = models.CharField(max_length=100, null=True, blank=True) employement = models.CharField(max_length=50, null=True, blank=True) education = models.CharField(max_length=500, null=True, blank=True) religion = … -
How to get userid in Django classviews?
I have this class that changes user password: class PasswordsChangeView(PasswordChangeView): from_class = PasswordChangingForm success_url = reverse_lazy( "base:password/passwordsuccess", ) And I would like to insert User Avatar Img Path in context. This Img is inside a UserComplement model. When I create function views, it works doing: @login_required def password_success(request): try: obg = UserComplement.objects.get(pk=request.user.id) context = { "img_avatar": obg.avatar_image, } return render(request, "registration/passwordsuccess.html", context) except UserComplement.DoesNotExist: return render(request, "registration/passwordsuccess.html") The problem is that I cannot get the userID in classviews to pass it through the context on success_url. -
Django List Sending To API
We are currently in the process of making a new online store program for our students. The current framework we are using is DJANGO. On one of our views which is called completed checkout, it sends an email to the student's counselor to approve the following purchase. That email we are sending via 3rd party is called Postmark. The reason we decided to go with the third party as opposed to Django is to monitor the tracking of the emails and not have to deal with SMTP issues. The API is a REST API and requires JSON, dictionary, or list to be sent to populate the template. I'm going to show you the postmark template in HTML. The following lines within the template are what the API pushes data to. <td width="60%" class="align-left purchase_item">{{product__name}}</td> <td width="40%" class="align-right purchase_item">{{product__point_price}}</td> Template <table class="purchase_content" width="100%" cellpadding="0" cellspacing="0"> <tr> <th class="purchase_heading"> <p class="align-left">Description</p> </th> <th class="purchase_heading"> <p class="align-right">Amount</p> </th> </tr> {{#each receipt_details}} <tr> <td width="60%" class="align-left purchase_item">{{product__name}}</td> <td width="40%" class="align-right purchase_item">{{product__point_price}}</td> </tr> {{/each}} <tr> <td width="80%" class="purchase_footer" valign="middle"> <p class="purchase_total purchase_total--label">Total Points</p> </td> <td width="20%" class="purchase_footer" valign="middle"> <p class="purchase_total">{{points}}</p> </td> </tr> </table> Now below here is the Completed Checkout View. The issue we are … -
Django error no reverse match with arguments '('',)'
I feel kinda bad using my first post as a cry for help but hey, im certainly not the first lulz, anyway, im teaching myself python/django and im really stuck atm and ive been slogging through problems myself lately and wasting a lot of time doing it and this one has me stuck. Im getting the error: NoReverseMatch at /messages/newreply/1/ Reverse for 'newreply' with arguments '('',)' not found. 1 pattern(s) tried: ['messages/newreply/(?P<post_id>[0-9]+)/\Z'] This is my url file; app_name = 'board' urlpatterns = [ path('', views.index, name='index'), path('<int:post_id>/', views.postdetail, name='detail'), path('newmsg/', views.newmsg, name='newmsg'), path('newreply/<int:post_id>/', views.newreply, name='newreply') view def newreply(request, post_id): post = Post.objects.get(id=post_id) if request.method != "POST": form = ReplyForm() else: form = ReplyForm(data=request.POST) if form.is_valid(): newreply= form.save(commit=False) newreply.post = post newreply.save() return redirect('board:index') context = {'form':form} return render(request, 'board/newreply.html', context) template; {% extends 'pages/base.html' %} {% block content %} <p>Add your reply here</p> <form action="{% url 'board:newreply' post.id %}"method ='post'> {% csrf_token %} {{ form.as_p }} <button name = "submit">Add post</button> </form> {% endblock content %} Ive tried so many things now im not even sure where i began anymore so id really appreciate any help, especially knowing why its actually happening as ive read through a few posts with … -
Need help in displaying items from ManyToMany relation in Django template
I am struggling with displaying items from manytomany field in my html file. models.py class Ingredients(models.Model): name = models.CharField('Nazwa', max_length = 100) ingredient_category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE) class ShoppingList(models.Model): name = models.CharField('Nazwa', max_length = 100) status = models.BooleanField(default = False) last_updated = models.DateTimeField('Ostatnia aktualizacja', auto_now=True) publish = models.DateTimeField('Stworzono', default=timezone.now) ingredient_list = models.ManyToManyField(Ingredients, related_name='shopping_list') slug = models.SlugField(unique=True, blank=True, max_length=254) views.py class HomePageView(TemplateView): template_name = "homepage.html" queryset= ShoppingList.objects.all() def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) shopping_list = ShoppingList.objects.all() context['shopping_list'] = shopping_list return context homepage.html {% for list in shopping_list.ingredient_list.all %} <div class="tab-pane fade {% if forloop.first %}show active{% else %}{% endif %}" id="list-{{list.id}}" role="tabpanel" aria-labelledby="list-{{list.id}}-tab">{{list.name}}</div> {% endfor %} -
Django how to validate a form in CreateView when using foreignkeys and using multiple databases
Hello This is my first question so please forgive the formatting: Current lab setup 1 project: library 1 app catalog 2 databases library_admin_db (admin-mysql) catalog_db (mysql1 I'm trying to add a database object on "catalog_db" database using a "CreateView" Class based view I already set up the Databases connection: DATABASES = { # Must use Default 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'library_admin_db', 'USER': 'root', 'PASSWORD': 'password', 'HOST': '192.168.164.128', 'PORT': '8002' }, 'catalog': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'catalog_db', 'USER': 'root', 'PASSWORD': 'password', 'HOST': '192.168.164.128', 'PORT': '8000', } } I set up the DATABASE_ROUTERS: DATABASE_ROUTERS = [ BASE_DIR / 'routers.db_routers.LibraryRouter'# the "MyApp1Router is the class inside the db_routers file" ] here is my model with the foreign keys: from django.db import models from django.urls import reverse import uuid # Create your models here. class Genre(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=600) isbn = models.CharField('ISBN', max_length=13, unique=True) genre = models.ManyToManyField(Genre) language = models.ForeignKey('language', on_delete=models.SET_NULL, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('book_detail', kwargs={"pk":self.pk}) class Language(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Author(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) date_of_birth = models.DateField(null=True,blank=True) class Meta: ordering = ['last_name','first_name'] … -
Issue with NoReverseMatch at Django website
I am making a web with Django-python, following a step by step tutorial, I put it below. My problem is the following: and this appears to me: NoReverseMatch in /. The reverse of 'login' was not found. 'login' is not a valid view Exception Type: NoReverseMatch. Exception Value: Failed to find the reverse side of 'login'. 'login' is not a valid view function or pattern name. And this is the error code: The reverse side of 'login' has not been found. 'login' is not a valid view function or pattern name. 8 {% url 'public:contact' as contact_url %} 9 <span>{% if request.path == contact_url %}Contacto{% else %}<a href="{{ contact_url }}">Contacto</a>{% endif%}</span> 10 <span> 11 <span style="float:right"> 12 {% if user.is_authenticated%} 13 {% url 'profile' as profile_url%} 14 <span>Hola {% if request.path == profile_url%}{{user.username }}{% else %}<a href="{{ profile_url}}">{{user.username}}</a>{%endif%}</span> 15 <!--<span> Hola <a href={% url 'profile' %}">{{user.username}}</a>!</span> --> 16 <span><a href="{% url 'logout' %}">Salir</a></span> 17 {% else %} 18 <span><a href="{% url 'login' %}">Ingresar</a></span> 19 {% endif %} 20 </span> 21 </nav> error line: 18 What can I do about this? Maybe it's a problem with the views or I will have to define login? If you can help me, thank … -
why is django server not working? (connection refused error)
I am doing a course : cs50 web programming with python and in project 2 Commerce while using python manage.py runserver I am getting this error: This site can’t be reached 127.0.0.1 refused to connect. this is project 2 commerce. https://cs50.harvard.edu/web/2020/projects/2/commerce/ I have not made any changes to the distribution code I am stuck please help me as soon as possible. -
How to have a number related to each one of many to many field objects? (e.g. A score for a homework a student has done)
I'm making an Learning Management System. There's this model called Homework and User model which is basically a model for students. class User(AbstractUser): # some code class Homework(models.Model): # some code ... students_done = models.ManyToManyField(User, blank=True, related_name='homeworks_done') I wanted to keep track of students that have done a specific homework and I did it by adding students_done field. Now I want the teacher to have the option to give each student a score for a done homework. How can I save the score in the database? I just can't figure out what field to use and how to use it. -
How to get a specific record in a lookup table in Django
I'm building a Django app that manages client data. I store phone numbers, email addresses, addresses, etc., in lookup tables. I would like to create a queryset that returns the primary numbers for all clients. Here is an abbreviated version of the client table: id last first etc 100426 Smith John etc 114988 Johnson Thomas etc An example of the phones table: id client_id type_id is_primary number 1 100426 1 t 427-567-8382 2 100426 2 f 427-567-7789 3 114988 1 t 914-223-4597 And finally, the phone_type table: id type 1 mobile 2 home 3 office 4 condo An extract of the client model: class Client(models.Model): id = models.IntegerField(primary_key=True) last = models.CharField(max_length=32) first = models.CharField(max_length=32) phone = models.ForeignKey( Phone, on_delete=models.PROTECT, blank=False, null=False ) The phone model: class Phone(models.Model): id = models.IntegerField(primary_key=True) client_id = models.IntegerField type_id = models.ForeignKey( PhoneType, on_delete=models.PROTECT, blank=False, null=False) is_primary = models.BooleanField country_code = models.CharField(max_length=5) phone_number = models.CharField(max_length=16) And the phone_type: class PhoneType(models.Model): id = models.SmallIntegerField(primary_key=True) type = models.CharField(max_length=16, blank=False, null=False) My ClientListView: class ClientListView(ListView): model = Client template_name = 'client/client_list.html' context_object_name = 'clients' def get_queryset(self): return Client.objects.order_by('-id').filter(status_id=3).select_related(Phone) The get_queryset function is a placeholder for now. How can I replace the get_queryset function so that I'm able to list … -
Why does celery worker keep trying to connect to amqp even though the broker is sqs?
I tried to configure broker via settings and directly from the celery file . Settings that apply to celery below. AWS_SQS_SECRET = os.environ.get("AWS_SQS_SECRET") broker_url = 'sqs://%s:%s@' % (AWS_SQS_ACCESS, AWS_SQS_SECRET) task_default_queue = os.environ.get("DEFAULT_QUEUE") AWS_SQS_REGION = os.environ.get("AWS_REGION") broker_backend = "SQS" broker_transport_options = { "region": AWS_SQS_REGION, # 'queue_name_prefix': '%s-' % 'dev' , # os.environ.get('ENVIRONMENT', 'development'), 'visibility_timeout': 7200, 'polling_interval': 1, } accept_content = ['application/json'] result_serializer = 'json' task_serializer = 'json' Also, as I mentioned, I tried to configure directly from the celery file. import os from celery import Celery from celery.schedules import crontab from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyApp.settings') AWS_SQS_ACCESS = os.environ.get("AWS_SQS_ACCESS") AWS_SQS_SECRET = os.environ.get("AWS_SQS_SECRET") app = Celery('MyApp') #,, broker='sqs://%s:%s@' % (AWS_SQS_ACCESS, AWS_SQS_SECRET), backend='django-db' # app.config_from_object('django.conf:settings') #, namespace='CELERY' CELERY_CONFIG = { "CELERY_TASK_SERIALIZER": "json", "CELERY_ACCEPT_CONTENT": ["json"], "CELERY_RESULT_SERIALIZER": "json", "CELERY_RESULT_BACKEND": None, "CELERY_TIMEZONE": "America/Sao_Paulo", "CELERY_ENABLE_UTC": True, "CELERY_ENABLE_REMOTE_CONTROL": False, } BROKER_URL = 'sqs://%s:%s@' % (AWS_SQS_ACCESS, AWS_SQS_SECRET) CELERY_CONFIG.update( **{ "BROKER_URL": BROKER_URL, "BROKER_TRANSPORT": "sqs", "BROKER_TRANSPORT_OPTIONS": { "region": "sa-east-1", "visibility_timeout": 3600, "polling_interval": 60, }, } ) app.conf.update(**CELERY_CONFIG) app.autodiscover_tasks() During deployment on elastik beanstalk , in the service I am running the command: $PYTHONPATH/celery -A celery worker -Q default-dev -n default-worker \ --logfile=/var/log/celery/celery-stdout-error.log --loglevel=DEBUG --concurrency=1 Tried to run before: $PYTHONPATH/celery -A MyApp worker -Q default-dev -n default-worker \ --logfile=/var/log/celery/celery-stdout-error.log --loglevel=DEBUG --concurrency=1 But … -
Django-CKeditor broken on Heroku
My django website is hosted on Heroku (with static files on AWS S3) and the ckeditor recently stopped working on my admin pages. If I check the console, I can see this error : Refused to execute script from 'https://mysite-web.herokuapp.com/admin/' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Any idea how to fix this ? -
CSS malfunctioning in social media platform chat between two users
Social Media Platform: I am trying to get the image to line up above the sent message as you would have it in most standard DMs: example But for some reason, my images stick to the right side of the chat box: without CSS When I add float: right; to my CSS the image and the text layer horizontally in a strange manner: with CSS Ideally, the image should be on the same side as the texts from the person who sent the image and should be just above the message that was attached to the image (as is commonplace). style.css: .sent-message { background-color: #d7a5eb; border-radius: 30px; padding: 10px 25px; width: 25%; float: right; } .received-message { background-color: #cc64c3; color: #000; border-radius: 30px; padding: 10px 25px; width: 25%; float: left; } .message-receiver-container { margin-left: 0; margin-right: auto; } .message-image-received { border-radius: 10px; max-width: 35%; height: auto; float: left; } .message-image-sent { border-radius: 10px; max-width: 35%; height: auto; float: right; } thread.html: {% for message in message_list %} <div class="row"> {% if message.sender_user == request.user %} <div class="col-md-12 my-1"> {% if message.image %} <div> <img src="{{ message.image.url }}" class="message-image-sent" /> </div> {% endif %} <div class="sent-message my-3"> <p>{{ message.body }}</p> </div> … -
Django - Disable Cache key warnings
I am currently designing a Django application and set up a database cache, increased the key size to 500 characters, however I constantly receive this warning: CacheKeyWarning: Cache key will cause errors if used with memcached: key_text (longer than 250) Reading through the documentation here: https://docs.djangoproject.com/en/3.2/topics/cache/ If you are using a production backend that can accept a wider range of keys (a custom backend, or one of the non-memcached built-in backends), and want to use this wider range without warnings, you can silence CacheKeyWarning with this code in the management module of one of your INSTALLED_APPS. I've created management folder in my app (tried various places) and added the code required inside it as management.py but it's not working. Has anyone managed to silence these warnings and can please share where they added it? Thanks -
How to convert image address and save to imagefield in Django
I want to convert the image address to image, and django-storages will automatically upload the image to cloud storage when saving the model. I have tried a few things with no success, any help would be great!(forgive my ugly English) class Register(APIView): permission_classes = [permissions.AllowAny] def post(self, request, *args, **kwargs): username = request.data.get('nickname', None) avatarUrl = request.data.get('avatarUrl', None) if not username or not avatarUrl: return Response(status=status.HTTP_400_BAD_REQUEST) # Convert image address to file, use django-storages to automatically upload images to cloud storage when model on save, so no need to save local image ... ... user, created = UserProfile.objects.get_or_create(username=username, defaults={'avatar': convert_image_from_url}) return Response(status=status.HTTP_200_OK) -
django - check if the user has saved the post in the template
How can i check if the user has saved the post or not? Post model: class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=50, default='slug') text = models.TextField(null=True, blank=True) text_allowed = models.BooleanField(default=True) image = models.ImageField(upload_to='posts/images/', null=True, blank=True) image_allowed = models.BooleanField(default=True) video = models.FileField(upload_to='posts/videos/', null=True, blank=True) video_allowed = models.BooleanField(default=True) server = models.ForeignKey(Server, on_delete=models.CASCADE, related_name='posts') creator = models.ForeignKey(User , on_delete=models.CASCADE, related_name='posts', null=True) created = models.DateTimeField(auto_now=True) type = models.CharField(max_length=5, choices=post_type_choices, default='text') votes_count = models.IntegerField(default=0) tag = models.ForeignKey(ServerTag, on_delete=models.CASCADE , default=1) Save model: class Save(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='saved') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_saves') created = models.DateTimeField(auto_now='True') I've tried: post-page.html: {% if request.user.user_saves %} <a href="{% url 'posts:save-post' post.id %}"><img class="save-btn" src="{% static 'posts/svgs/saved.svg' %}" alt="save post button"></a> //show this svg if the user has saved this post {% else %} <a href="{% url 'posts:save-post' post.id %}"><img class="save-btn" src="{% static 'posts/svgs/save.svg' %}" alt="save post button"></a> {% endif %} -
How to insert data into django db from a sql file
I have generated a dataset from mockaroo called x.sql want to import this into django models where the database is default a.k.a sqlite3 -
Django returns blank QuerySet despite names matching
I have a model Employee, where one of the fields is manager, which is a ForeignKey to another model called Manager. I am checking whether a manager value I'm passing through the previous page matches with an object of Employee that has the same manager, and I want to get only those objects where the manager matches. However, despite me having employees that have different managers each, I try filtering using Employee.objects.get(manager=manager) or Employee.objects.filter(manager=manager), and neither returns anything. filter returns a blank queryset and get says Employee matching query does not exist. despite it clearly matching. Any help would be appreciated, thanks! CODE views.py from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.utils import timezone from .models import Attendance from .models import Employee, Manager from datetime import datetime employee_list = ["John", "Jane", "Jacob", "Mark", "Jingleheimer", "Rob", "Schmidt"] # Create your views here. @login_required def home(request): return render(request, 'index.html') @login_required def attendance(request): manager_list = Manager.objects.all() now = timezone.now().date status = 0 for manager in manager_list: if ' ' in manager.name: manager.select_name = manager.name.replace(' ', '_') else: pass if request.method == 'POST': manager = request.POST.get('manager') print(manager) return redirect('mark_attendance', manager=manager) return render(request, 'attendance.html', { "date": now, "status": …