Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery tasks are not adding object to db Django/Postgres
I have trouble with celery using it in docker, it receives tasks and in terminal sends that everything works fine, but it creates nothing in the database(I use Postgres). I think that problem somewhere in docker, but not sure. Consol doesn't give any errors. Can't find anything in the internet about it, please help me with this problem my docker-compose file: version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py makemigrations && python manage.py migrate && python manage.py test&& python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=supersecretpassword - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 depends_on: - db db: image: postgres:13-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword redis: ports: - "6379:6379" image: redis:5-alpine celery-beat: build: . user: root command: celery -A app beat -l INFO environment: - DB_HOST=db - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 depends_on: - db - redis - celery celery: build: . user: root command: celery -A app worker -l INFO --pool=solo environment: - DB_HOST=db - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 depends_on: - db - redis my celery.py import os from celery import Celery from celery.schedules import crontab from app.settings import INSTALLED_APPS os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') app = … -
How to run Django server on device IP address?
When I run Django server using this, python manage.py runserver ip-addr:8000 I can see the server is running in the terminal. But when I open the browser, the This site can't be reached message is displayed. There is no error I see in the terminal or the console. Also, everything works perfectly fine with 127.0.0.1 and 0.0.0.0 but not with my ip-addr. How can I run or know that if there is something wrong or any problem? -
Cookiecutter - Django: Anymail[SES] boto3 region error
I am trying to deploy to AWS(EC2) a Cookiecutter Django project. The AWS user with this credentials has ful S3, SES and SNS policies. The EC2 server has also a role with full SES/S3 policies. In production file in envs I have the keys set up like this. DJANGO_AWS_ACCESS_KEY_ID=xxxxxxxxx DJANGO_AWS_SECRET_ACCESS_KEY=xxxxxxxxxx DJANGO_AWS_STORAGE_BUCKET_NAME=xxxxxxxxxx In settings I have AWS_S3_REGION_NAME = env("DJANGO_AWS_S3_REGION_NAME", default=None) AWS_ACCESS_KEY_ID = env("DJANGO_AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = env("DJANGO_AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = env("DJANGO_AWS_STORAGE_BUCKET_NAME") EMAIL_BACKEND = "anymail.backends.amazon_ses.EmailBackend" ANYMAIL = {} All nice and fine until the project tries to send an email using SES and it crashes with the error bellow . Until now I have tried: adding DJANGO_AWS_S3_REGION_NAME to the production file in envs - no result adding the region in aws config using aws cli - no result overriding the settings in ANYMAIL ={} with credetials and region - no result making a blank project, just adding the aws credentials and not changing anything else - no result creating manually on another project a boto3.session.client with the same credentials and sending a mail - it works This is the error. The second part with 'NoneType' object has no attribute 'send_raw_email' repeats a lot after this. django_1 | [2021-08-13 13:58:14 +0000] [12] [ERROR] Error handling … -
how to loop through a python list of nothing
I am trying to create a online class and want to loop through the list of the classes to see if he/she been registered or not problem is if the list be empty it will return an error I am using django and django-restframework here is my code @api_view(['POST']) @permission_classes([IsAuthenticated,]) def createOrderForOnlineClasses(request): user = request.user data = request.data Class = OnlineClass.objects.get(id= data["classId"]) orderCred = { 'pin' : 'somepin', 'amount' : int(Class.totalPrice), 'callback' : 'http://localhost:3000/verify/', } for i in user.userprofile.onlineClass.all(): if i == Class: return Response({"details": "allready registered"}, status=status.HTTP_400_BAD_REQUEST) else: try: response = requests.post("URL_TO_SOMEWHERE", data=orderCred) if response.status_code == 200 and not response.text.replace('-',"").isdigit(): registeredClass = RegisterStudentForOnlineClass.objects.create( user=user, totalPrice = int(Class.totalPrice), transId = response.text, onlineClassName= Class ) serializer = RegisterForClassSerializer(registeredClass , many=False) return Response(serializer.data) else: return Response({"details": ""} , status= status.HTTP_400_BAD_REQUEST) except Exception as e: return Response({"details": e}) here is the returned error Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` Thank you :) -
Object of type CarBrandForm is not JSON serializable
CarBrandForm in this example is a ModelForm. def post(self,request): if request.method== "POST": form=CarBrandForm(request.POST) if form is not None: if form.is_valid(): form.save() request.session['user']=form return render(request,'carbrand/branddetails.html') return render(request,'carbrand/carbrandregister.html') Showing error when i started to store session variable. This is the first iam using session, So if there is any improvments and precaution that i have to take is always welcome. Thankyou! -
How to use a Python script that uses Selenium in a Web App
I'm looking for some guidance as I'm having trouble finding any answers when I search, as well as struggling to formulate what I actually want into search terms. In short, I currently have a Python script that will take an excel spreadsheet containing 2 columns, 1 containing a number, the other containing a string. It then uses Selenium and chromedriver to log in to a website, enter the number from column 1, do some more clicking and then add the note from column 2. It loops through all of the numbers in Column 1 to do this. The script works perfectly but I need to share it with some colleagues and I figure the best way to do that would be to create a web app using Django that they can upload the excel or csv file to, but I'm struggling to figure out how I would then get the script to run and use the data from the uploaded file. When a user uploads the file, how do I then get this to start the Python script? How do i then post the results of the script, i.e, whether it successfully added a note for each number, back to … -
pass user data to serializer in nested serializers when creating object in django rest framework
When User tries to add an Announcement, should i pass all the informations of the user in the form ? i'm using token authentification. So for adding an Announcement the user must be authenticated. Models.py class User(AbstractUser): username = None email = models.EmailField(max_length=100, verbose_name='email', unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Announcement(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) photo = models.ManyToManyField(Photo, blank=True) class Photo(models.Model): name = models.CharField(max_length=100) content_type = models.CharField(max_length=100) path = models.CharField(max_length=100) class Parameter(models.Model): name = models.CharField(max_length=100) value = models.FloatField(blank=True, null=True) announcement = models.ForeignKey( Announcement,related_name='parameters', on_delete=models.CASCADE) Serializers.py class AnnouncementSerializer(serializers.ModelSerializer): author = UserSerializer(required=True) parameters = ParameterSerializer(many=True, required=False) photo = PhotoSerializer(many=True, required=False) class Meta: model = Announcement fields = ['id', 'name', 'author', 'parameters', 'photo'] class UserSerializer(serializers.ModelSerializer): photo = PhotoSerializer() class Meta: model = User fields = ['id', 'email','photo', ] class ParameterSerializer(serializers.ModelSerializer): class Meta: model = Parameter fields = '__all__' class PhotoSerializer(serializers.ModelSerializer): class Meta: model = Photo fields = '__all__' Views.py class AnnouncementCreate(CreateAPIView): permission_classes = [IsOwner] queryset = models.Announcement.objects.all() serializer_class = AnnouncementSerializer class IsOwner(permissions.BasePermission): def has_permission(self, request, view): return request.user and request.user.is_authenticated() def has_object_permission(self, request, view, obj): return obj.user == request.user When trying the browsable API. to create a new announcement i have to enter all the … -
Crontab seems to start scripts but nothing happens
I have defined quite a few cronjobs in my docker container, that I let running while I went for some holidays. When I came back, everything had stopped. It appears that the container restarted at some point during my time off and I didn't configure my docker well enough for it to restart the crontab service by itself. However now that I have restarted it, my cronjobs do not work. I checked that the services are running, I can ensure that crontab is doing part of its job, because its entries are logged successfully in syslog. But my script doesn't get executed. I started it with a write into a logfile (my tasks are using Django commands and the python logging library), but the log file doesn't get updated. Running the command manually from the command line is still working, my commands specify the absolute path for everything (even the python binary to use...). I don't know where to look at to understand what's wrong at this point. Note : I did update some of my code since I came back from my holidays, but none should affect the starting log message that lies in my scripts. As a test, … -
How to optimize and simplify query in django 2.2
I had a raw sql query: UPDATE store_codeinventory set recipient_id = 1168, claimed_date = NOW() where id = ANY((select array(select id from store_codeinventory where recipient_id is NULL and inv_id = 72 and is_active=true ORDER BY ID ASC LIMIT 1 FOR UPDATE)) ::integer[]) and recipient_id is NULL; and tried to optimize it that led me to the django orm query: CodeInventory.objects.filter( **CodeInventory.objects.select_for_update(skip_locked=True).filter(recipient=None, is_active=True, inv_id=72) .aggregate(id=models.Min('id')) ).update(recipient_id=1168, claimed_date=timezone.now()) Can we optimize it better? -
Create form to change relationship from related model's form
I have two models: class Thing(forms.ModelForm): class Owner(forms.ModelForm): thing = models.OneToOneField(Thing) I want to add a form to change the owner in Thing's UpdateView. I can do it like this: class ThingForm(forms.ModelForm): owner = forms.ModelChoiceField( queryset=Owner.objects.all(), ) class Meta: model = Thing fields = '__all__' And then process the result inside form_valid() method. But isn't there a more direct approach for this, where i just add this to the fields of the form? -
Return the number of times my django model object was retrieved today
With a model like below, I want to return the number of times an object was retrieved today class Watched(Stamping): user = models.ForeignKey("User", null=True, blank=True, on_delete=models.CASCADE, default=None) count = models.PositiveIntegerField() The Stamping is another model with created_at and updated_at -
CSS isn't loading in Django
I have a problem with my Django project which does not want to load static files. I tried a lot of solutions proposed here in the forum like: settings.py -> setting the STATICFILES_DIRS (I had it from the beginning but was trying different things) changing my URL paths in the html links tag moving everything into one template instead of extending adding app name in urls adding css to mime moving load static to head and many more out of which all failed. Could anyone see what the problem in the code is? Thank you My project has a structure like this: my_site blog -- static/blog -- templates/blog -- standard Django files my_site -- standard Django files templates static -- images BLOG: urls.py: from django.urls import path from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns app_name = "blog" urlpatterns = [ path("index", views.index, name="index"), path("posts", views.posts_list, name="posts_list"), path("posts/<slug:slug>", views.post, name="post") ] urlpatterns += staticfiles_urlpatterns() views.py: from django.http.response import HttpResponse from django.shortcuts import render # Create your views here. def index(request): return render(request, 'blog/index.html') def posts_list(request): return render(request, "blog/posts_list.html") def post(request): return render(request, "blog/post.html") templates/blog/index.html: {% extends "base.html" %} {% load static %} {% block title %} Yogiri {% endblock %} … -
Generic DeleteView is returning django.db.models.query_utils.DeferredAttribute object at 0x04725628 - Django
Disclaimer: I'm just a novice trying to learn Django Hello, I'm trying to refactor my code and modify all the views that I have created to be Class Based Views. I have an issue loading a form with DeleteView that is showing the data and at the same time is disabled. I have some success and the only thing that I cannot figure out how to do is to show the data instead of the message that appears now "<django.db.models.query_utils.DeferredAttribute object at 0x04725628>" +models.py: class Note(models.Model): title = models.CharField(max_length=30) image_url = models.URLField() content = models.TextField() owner = models.ForeignKey(Profile, default=8, on_delete=models.CASCADE) def get_absolute_url(self): return reverse(self.pk) def __str__(self): return f'{self.title}' +forms.py class NoteForm(forms.ModelForm): class Meta: model = Note exclude = ('owner',) class DeleteNoteForm(NoteForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for (_, field) in self.fields.items(): field.widget.attrs['readonly'] = True field.widget.attrs['disabled'] = True +views.py class DeleteNoteView(DeleteView): model = Note template_name = 'note-delete.html' form_class = DeleteNoteForm success_url = reverse_lazy('home page') def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data['form'] = self.form_class(instance=self.model) return data +urls.py path('delete/<int:pk>/', views.DeleteNoteView.as_view(), name='delete note'), +template <!--note delete data form--> <div class="form"> <form method="POST"> {{ form }} {% csrf_token %} <input type="submit" value="Delete"/> </form> </div> <!--end note delete data form--> If I use my view … -
Django save via signals in another table
I have a create view (Loan_assetCreateView(generic.CreateView)) where I save if an asset is going to be loaned and when it will be returened in a model called Loan_asset(models.Model). Then I have the asset in a diffrent model Asset(model.Model). I would like to once I have saved my data in my Loan_assetCreateView(generic.CreateView) that is set the value in Asset.is_loaned to True. Via signal, @receiver(post_save, I am trying to save the value. But it creates another asset instead. What am I dong wrong and how can I fix it? My models.py: class Asset(models.Model): # Relationships room = models.ForeignKey("asset_app.Room", on_delete=models.SET_NULL, blank=True, null=True) model_hardware = models.ForeignKey("asset_app.Model_hardware", on_delete=models.SET_NULL, blank=True, null=True) # Fields name = models.CharField(max_length=30) serial = models.CharField(max_length=30, unique=True, blank=True, null=True, default=None) mac_address = models.CharField(max_length=30, null=True, blank=True) purchased_date = models.DateField(null=True, blank=True) may_be_loaned = models.BooleanField(default=False, blank=True, null=True) is_loaned = models.BooleanField(default=False, blank=True, null=True) missing = models.BooleanField(default=False, blank=True, null=True) notes = HTMLField(default="") ip = models.CharField(max_length=90, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class Loan_asset(models.Model): # Relationships asset = models.ForeignKey("asset_app.Asset", on_delete=models.SET_NULL, blank=True, null=True) loaner_type = models.ForeignKey("asset_app.Loaner_type", on_delete=models.SET_NULL, blank=True, null=True) location = models.ForeignKey("asset_app.Locations", on_delete=models.SET_NULL, blank=True, null=True) # Fields loaner_name = models.CharField(max_length=60) loaner_address = models.TextField(max_length=100, null=True, blank=True) loaner_telephone_number = models.CharField(max_length=30) loaner_email = models.EmailField() loaner_quicklink = models.URLField(null=True, blank=True) loan_date … -
Implement Python code into django website
I have written this python script to print the names of new anime on a website for watching anime in japanese. from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC url ='https://animelon.com/' PATH = 'C:\Program Files (x86)\chromedriver.exe' driver = webdriver.Chrome(PATH) driver.get(url) try: section = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CLASS_NAME, 'row ng-show-toggle-slidedown series-content-container')) ) anime = section.find_elements_by_class_name('col-lg-3 col-md-4 col-sm-6 col-xs-12 mini-previews ng-scope') for show in anime: header = show.find_element_by_class_name('anime-name ng-binding') print(header.text) finally: driver.quit() I also have a simple django website. I would like these headings to show on my website. Does anyone know how to do this? I already got the commment about using BS4. Is there a way to do it with Selenium? Thank you! -
i unable to fetch user information from django admin
i am creating user_edit_profile for that i need to show the details when user filled the details when he was signing up.Show Users all details are stored in django admin but i can't fetch it only i can fetch thing was a username <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" name="username" value={{user.get_username}} required> </div> i got the username printed in box but with other only printed required so please somebody help to get out from this headache. edit_profile.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <title>Edit Profile</title> <style> .form-control { display: block; width: 66%; padding: .375rem .75rem; font-size: 1rem; font-weight: 400; line-height: 1.5; color: #212529; background-color: #fff; background-clip: padding-box; border: 1px solid #ced4da; -webkit-appearance: none; -moz-appearance: none; appearance: none; border-radius: .25rem; transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out; } #left{ margin-left: -218px; width: 36rem; } </style> </head> <body> <div class="container"> <div class="col-lg-12 my-4 mx-2"> <h1>Update Profile</h1> <form action= "############" method='POST'> <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" name="username" value={{user.get_username}} required> </div> <div class="form-group"> <label for="fname">First Name</label> <input type="text" class="form-control" id="fname" name="fname" value={{request.user.get_firstname}} required> </div> <div class="form-group"> <label for="lname">Last Name</label> <input type="text" … -
Materialize dropdown in nav is behind elements
I know this type of questions has been asked, I went over them but could not solve my problem. In my page where I am using materialize, I have a nav bar with a dropdown button but whenever i open it, it would be behind another element. I am attaching a image of it I am attaching a image of it. I have made a similar problem in fiddle, https://jsfiddle.net/Illuminator0/pugy1j5b/10/ <ul id='dropdown1' class='dropdown-content'> <li><a class='dropdown-button d' href='#' data-activates='dropdown2' data-hover="hover" data-alignment="left">Drop Me!</a></li> <li><a href="#!">two</a></li> <li class="divider"></li> <li><a href="#!">three</a></li> </ul> <ul id='dropdown2' class='dropdown-content'> <li><a href="#!">one</a></li> <li><a href="#!">two</a></li> <li class="divider"></li> <li><a href="#!">three</a></li> </ul> <nav> <div id="nav-wrapper"> <ul class=" brand-logo center"> <li> <a class='dropdown-button btn' href='#' data-activates='dropdown1' data-beloworigin="true">Drop Me!</a> </li> </ul> </div> </nav> <div class="row"> <div class="col s12 m6"> <div class="card blue-grey darken-1"> <div class="card-content white-text"> <span class="card-title">Card Title</span> <p>I am a very simple card. I am good at containing small bits of information. I am convenient because I require little markup to use effectively.</p> </div> <div class="card-action"> <a href="#">This is a link</a> <a href="#">This is a link</a> </div> </div> </div> </div> I would appreciate the help. -
How to integrate call forwarding in website? To keep someone's real mobile No. Private
We have a website called RentYug on which people can give or take anything on rent. For this, we are taking contact information like mobile number and some other details of renter (who is giving Something on rent). But we don't want to show the mobile number to everyone. We want to forward the call through us like Indiamart to make this website more safe. Website is developed using React.js and Django. I need to know that so I can integrate this before launch. More explanation: It is not related to authentication. If someone wants to give their product on rent so they will provide a mobile number to contact and I don't want to show that number to everyone. Instead of that number I want to show some another number and then I want to connect both consumer and provider without showing their real phone numbers. Website demonstration Please comment your thoughts so I can give more descriptive explanation of this question. -
Django Multiple Databases Set Up
I am trying to configure my django site to utilise two databases. My site is deployed via Heroku and I have a 'follower' database which is a read-only copy of my main database. As per my understanding from the Heroku docs, any changes to my main database are streamed live to the follower database. So what I am trying to achieve is making all read operations go to the follower database and write operations to hit the main database. Any help would be amazing. Cheers, Tom -
Django 3 installed_app shows ModuleNotFoundError in custom folders
while using customized folders, I am having a trouble using my app correctly in Django 3. My folder levels are: --manage.py --mdtour ----settings -------settings.py ----apps ------core ----templates In core app my apps.py file is: from django.apps import AppConfig class CoreConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'core' But i cannot use my app in Django 3. In settings file I tried to add the app in two ways: INSTALLED_APPS = [ 'mdtour.apps.core.apps.CoreConfig.core' ] The error I get: `ModuleNotFoundError: No module named 'mdtour.apps.core.apps.CoreConfig'; 'mdtour.apps.core.apps' is not a packa`ge or INSTALLED_APPS = [ 'mdtour.apps.core.apps.CoreConfig.core' ] this time I get: django.core.exceptions.ImproperlyConfigured: Cannot import 'core'. Check that 'mdtour.apps.core.apps.CoreConfig.name' is correct. How can I correct this error? Thanks -
Frontend stops responding, when using WebSockets with RabbitMQ turned off
I have frontend on VueJS and backend on Django. Some functions are using sockets to contact with backend using RabbitMQ. Example: this.healthCheckWs = new WebSocket(`${wsProtocol}://${host}/health_check_bo/?token=${this.$auth.getToken('local')}`); this.healthCheckWs.onclose = async function(event) { setTimeout(() => { this.connectsCheckHealthWs(); }, 5000); }.bind(this); But if RabbitMQ will be off and you try to use this, website freezes. I can't do anything. When you turn RabbitMQ on, message from front arrives and everything works good. So, my question is: Is there a way to terminate WebSocket connection, if it is not responding, and continue your work on site? Thanks everyone -
Getting 400_BAD_REQUEST when i'm trying to return data from django endpoint
Currently i'm trying to make an APIView that returns data like this: ["question_text": "answer_text", "question_text": "answer_text"] ... So, basically i want to make that in order to get the current user quizzes attempts, with the next REQUEST BODY: "quizname" my UserAnswer model looks like this: class UserAnswers(models.Model): user = models.ForeignKey(User, related_name='User', on_delete=models.CASCADE) answer = models.ForeignKey(Answer,related_name='Answer', on_delete=models.DO_NOTHING) Answer model : class Answer(models.Model): question = models.ForeignKey(Question, related_name='answer', on_delete=models.CASCADE) answer_text = models.CharField(max_length=255, default='', verbose_name="Answer") is_right = models.BooleanField(default=False) is_checked = models.BooleanField(default=False) def __str__(self): return self.answer_text Question model: class Question(models.Model): quiz = models.ForeignKey(Quiz, related_name='question', on_delete=models.CASCADE) question_text = models.CharField(max_length=255, default='', verbose_name="Question") def __str__(self): return self.question_text Basically, the UserAnswers table contains a FK to Answer, that contains a FK to Question, that contains a FK to quiz I tried to do this in my APIView: class UserAnswersView(APIView): permission_classes = [IsAuthenticated] def get(self,request): try: data = request.data # quizName toReturn = {} userAnswers = UserAnswers.objects.filter(user=request.user) # Getting all entries from UserAnswers table WHERE user = request.user for userEntry in userAnswers: # parsing al entries answer = Answer.objects.get(answer_text=userEntry.answer) # Getting the answer of every entry question = Question.objects.get(id=answer.question_id) # Getting the question of every entry quiz = Quiz.objects.get(id=question.quiz_id) # Getting the quiz of every entry if (quiz.category == request.data): … -
Sending an Excel file from postoffice
I am trying to send a base64-encoded excel file through Django post_office lib. Here's the code that I have now An example of encoded content: body = 'UEsDBBQAAAAIAAAAPwBhXUk6TwEAAI8EAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbK2Uy27CMBBF9/2KyNsqMXRRVRWBRR/LFqn0A1x7Qiwc2/IMFP6+k/BQW1Gggk2sZO7cc8eOPBgtG5ctIKEN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AAAAAAAAAAAAAAAgIGyAwAAeGwvd29ya3NoZWV0cy9zaGVldDEueG1sUEsBAhQDFAAAAAgAAAA/AIMYaiVIAQAAJgIAAA8AAAAAAAAAAAAAAICBVAUAAHhsL3dvcmtib29rLnhtbFBLAQIUAxQAAAAIAAAAPwBcdNNwogAAAOsAAAAUAAAAAAAAAAAAAACAgckGAAB4bC9zaGFyZWRTdHJpbmdzLnhtbFBLAQIUAxQAAAAIAAAAPwBproQY+wEAAD0FAAANAAAAAAAAAAAAAACAgZ0HAAB4bC9zdHlsZXMueG1sUEsBAhQDFAAAAAgAAAA/ABj6RlSwBQAAUhsAABMAAAAAAAAAAAAAAICBwwkAAHhsL3RoZW1lL3RoZW1lMS54bWxQSwECFAMUAAAACAAAAD8A05PycyQBAABQAgAAEQAAAAAAAAAAAAAAgIGkDwAAZG9jUHJvcHMvY29yZS54bWxQSwECFAMUAAAACAAAAD8AXrqn03cBAAAQAwAAEAAAAAAAAAAAAAAAgIH3EAAAZG9jUHJvcHMvYXBwLnhtbFBLBQYAAAAACgAKAIACAACcEgAAAAA=' The the code itself: from django.core.files.base import ContentFile from post_office import mail attachments = [{ 'name': 'example.xlsx', 'body': ContentFile(body), 'mimetype': 'application/vnd.ms-excel'}] mail.send(to, from, attachments=attachments, **params) The problem is that the content in the actual file that is sent by email looks like this: What could be the reason for that ? -
(Best practice) Handling multiple simple forms relating to one object in one view
I have a working solution but I would like to know if this is the best way to do it. I have three models: Meal, Indgredient and IngredientWithQuantity (IwQ). Meal can have multiple IwQ and Ingredient can have multiple IwQ. I created a simple view where you can create Meal (one form), add IwQ (another form) and if needed go to another view to create new Ingredient (yet another form) and then come back to this view where you still will edit the previous Meal. The only problem is keeping the information about the meal that is being created. I am doing this through html hidden input field where I store an information about meal_id. I am simply not sure if this is the best way to exchange this information, because at times it seems a little off. Could some take a look and tell me if maybe this could be achieved in a more effective manner? Thanks, models.py class Ingredient(models.Model): name = models.CharField(max_length=200, null=True) #brand #WW def __str__(self): return self.name class Meal(models.Model): EVALUATION = ( ('Perfect', 'Perfect'), ('Average', 'Average'), ('Bad', 'Bad') ) name = models.CharField(max_length=200, null=True) time_eaten = models.DateTimeField(auto_now=False, auto_now_add=False, default=timezone.now, null=True) # time_of_day = jaki posiłek? bolus_n = … -
How to create table with migrate after drop table from postgresql in django?
Using PostgresSQL and Django, I dropped two tables from postgresql manually. drop table ... Then I did make migrations and migrate. But my tables are not recreated. Can not access from shell_plus. Also in this page, django return relation 'table name' does not exists. I want to makemigrations and migrate to create tables again. How can I solve my issue ?