Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
github workflow fails while testing a django app
I created a django rest api and I am setting up a github action that performs linting and testing only. I run the test locally using pytest, pytest-django and pytest-cov and all tests pass. Django creates the dummy database and the api is tested. when i run the github action I get an error (see below) and I think this is due to the fact the inside the github enviroment there is no database. this is the github action: name: Python package on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest steps: - name: Check out repository code uses: actions/checkout@v2 # Setup Python (faster than using Python container) - name: Setup Python uses: actions/setup-python@v2 with: python-version: "3.7" - name: Install pipenv run: | python -m pip install --upgrade pipenv wheel - id: cache-pipenv uses: actions/cache@v1 with: path: ~/.local/share/virtualenvs key: ${{ runner.os }}-pipenv-${{ hashFiles('**/Pipfile.lock') }} - name: Install dependencies if: steps.cache-pipenv.outputs.cache-hit != 'true' run: | pipenv install --deploy --dev - name: Lint with flake8 run: | pipenv install flake8 # stop the build if there are Python syntax errors or undefined names pipenv run flake8 . - name: Run Migrations run: pipenv run python django_api-project/manage.py … -
Frequent 'out of shared memory' exceptions
I'm maintaining a Django app that CRUDs data on a Postgres DB. I frequently get ERROR: out of shared memory HINT: You might need to increase max_locks_per_transaction. messages from time to time ... especially when i try to run some adhoc jobs. This is basically what my function (decorated as a Celery task) looks like: @app.task() def myfunc(params): LOGGER.info("Starting func.") col1, col2, col3 = transformer(params) count_new_records = 0 with transaction.atomic(): for item in my_iterable: template_obj, created = MyTable.objects.get_or_create( col1=col1, defaults={ 'col2': col2, 'col3': col3 } ) if not created: template_obj.col3 = template_obj.col3 + col3 template_obj.save() else: count_new_records += 1 LOGGER.info(str(count_new_records) + " new records created.") LOGGER.info("Ending func.") Is there an issue with my code that causes the errors? Maybe locks not getting released correctly? If so, how can I resolve this issue & avoid having to increase max_locks_per_transaction every time? -
Django i18n in production
I gotta bilingual project. It works properly in local development, but when I deploy it on heroku, it won't read the locale folder whereas it works on development As I found out, git automatically ignores .mo and .po files, How can I undo that gitignore? -
Django - get a queryset following relationships
Let's say I have 3 models that are linked by One-to-Many relationships: class Company(models.Model): [...] class Reporter(models.Model): reporter = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='reporters') [...] class Article(models.Model): reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE, related_name='articles') [...] Is it possible to retrieve all articles linked to a specific company, starting from the company instance? I already know I can achieve that by doing: company = Company.objects.first() articles = Article.objects.filter(reporter__company=company) But could I directly use related names? Something like: company = Company.objects.first() articles = company.reporters... # directly starting from the "parent" -
Create many-to-many relations with bulk_create during file reading
I have trouble with the code architecture for adding many-to-many links when reading a file and creating new objects models.py class GS(models.Model): name = model.CharField() country_code = ManyToMany(Lang) class Lang(models.Model): code name I read the csv file and create new objects on each row file.csv **Name**,**Lang** name1,US; JP; AU name2,MX; ID; UA; CZ; ZA; HU; SK .... The Lang model is already in the database.I.e. I need to iterate through the file and create a new instance of GS and an intermediate model to link this instance with all the appropriate Lang objects. def handle(self, *args, **options): path = path_to 'file.csv' df = pd.read_csv(path) # set an empty queryset lang = Lang.objects.none() geo_segment = [] for i, row in df.iterrows(): # get list of language code lang_code = [c_c.strip(' ') for c_c in row['Lang'].split(';')] -> [MX, ID, UA, CZ .....] # get appropriate Lang objects langs = Lang.objects.filter(code__in=lang_code) # fulfill lang queryset distinct lang = lang | langs segment = GS(name=row['Name'] ) geo_segment.append(segment) # create new GS instancess but without realtions with Lang objects GS.objects.bulk_create(geo_segment) #SOME NEW LOGIC And here I'm lost, how to make the new created GS objects with all the corresponding Lang objects. In the for loop … -
Djangoform field is not displayed
i've got register form forms class RegisterForm(UserCreationForm): name = forms.CharField(max_length=255, label='Username', widget=forms.TextInput(attrs={'class': 'form-group'})) email = forms.EmailField(max_length=255, label='Email', widget=forms.EmailInput(attrs={'class': 'form-group'})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': 'form-group'})) password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput(attrs={'class': 'form-group'})) class Meta: model = User fields = ('name', 'email', 'password1', 'password2') views class RegisterFormView(FormView): form_class = UserCreationForm success_url = '/login/' template_name = 'blog/signup.html' def form_valid(self, form): form.save() return super(RegisterFormView, self).form_valid(form) def form_invalid(self, form): return super(RegisterFormView, self).form_invalid(form) html <form method="POST" class="register-form" id="register-form" action=""> {% csrf_token %} {% for field in form %} {{ field.errors }} {{ field.label_tag }} {{ field }} {% endfor %} <div class="form-group form-button"> <input type="submit" name="signup" id="signup" class="form-submit" value="Register"/> </div> </form> i tried {{form.as_p}} and for field . in both cases email field doesn't shows and labels too. register is working -
Return response statement is not returning any response
I am creating a logout view to logout from my django restframework using simplejwt. There is no direct way to logout so only blacklisting the refresh token is the workarround. Those print statements works expectedly so it does blacklist the tokens but the return statement doesn't return anything, why is that and how may I return a Response?I am guessing the save function doesnt return anything, is it ture? class LogoutSerializer(serializers.Serializer): refresh = serializers.CharField() def validate(self, attrs): self.token = attrs['refresh'] return attrs def save(self, **kwargs): try: RefreshToken(self.token).blacklist() print('done') return Response({'msg':'token has been blacklisted'}) except TokenError: print('not done') return Response({'msg':'token is expired or blacklisted'}) views.py class LogoutAPIView(APIView): serializer_class = LogoutSerializer permission_classes = [IsAuthenticated] def post(self, request): serializer = self.serializer_class(data = request.data) serializer.is_valid(raise_exception = True) serializer.save() return Response(status = status.HTTP_204_NO_CONTENT) -
ForeignKey Reciprocation
I want to be able to see the existance of the ForeignKey, but in the other admin.py app. The one to which is the receiver of the ForeignKey. In this case, I want to be able to see the Email ForeignKey in the Client admin.py. Client App Structure: Project Client model.py Client model.py Code: class Client(models.Model): primary_key = models.AutoField(primary_key=True) unique_num = models.TextField(max_length=30) name = models.TextField(max_length=30, default='Name Not Found') number = models.TextField(max_length=30) email = models.EmailField() Email App Structure: Project Email model.py Client model.py Code: class ScheduledEmail(models.Model): primary_key = models.AutoField(primary_key=True) recipient_name = models.TextField() subject = models.TextField() message = models.TextField() datetime_sent = models.TextField(max_length=20, default='Not Yet Sent') datetime_created = models.TextField(max_length=20) recipient_email = models.EmailField(max_length=50, default='Email Not Found') sent = models.BooleanField(default=False) recipient = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='scheduled_emails_sent') -
Multiple Django sites in the same server with different databases
I'm deploying the same Django project twice in a server with different settings and databases each one. First one is a production project using production.py settings and PostgreSQL database The second one is a test project using development.py settings and Sqlite database Following this tutorial, each one has a different socket, Gunicorn configuration, Nginx site enabled and different subdomain. The problem is that when I'm trying to login into the test's project admin site I have to use the production credentials and see production data. Which is the problem here? -
After hosting the django website showing 502 bad gateway
I deployed django website in gcloud everything is done after deploying when i search the url in google its showing like 502 bad gateway -
Firefox and Chrome not recognising json [closed]
I have a fetch request from an api , that collects data for the user and then pushes that data into arrays inside of my js script. This function works perfectly in Safari , but in Chrome and Firefox it comes back as a '500 Internal error'. I checked the content-type of the Response Headers, in safari it comes back as 'application/json' , but in chrome and firefox its 'text/plain; charset=utf-8' , can someone explain why this is happening and how to fix, I'm still new to JS. Here is my fetch function : var trackNames = []; var trackUrl = []; var albums = []; async function getUserTracks() { try { await fetch("https://www.soundpro.city/music/music_all?format=json", { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }) .then(response => { const contentType = response.headers.get('content-type'); if (!contentType || !contentType.includes('application/json')) { throw new TypeError("Oops, we haven't got JSON!"); } return response.json(); }) .then(data => { for (item of data) trackNames.push(item['title']), trackUrl.push(item['track']), albums.push(item['artist_name']) }) } catch(error) { console.log(error) } } -
Cannot send kendo-react-pdf from react to django using axios
Currently i'm trying to send a PDF file that is generated when the button is pressed (using kendo-react-pdf) to my Django API but it won't work. Here's my Django View: class quizPdfView(APIView): parser_classes = [MultiPartParser,FormParser] def post(self,request): try: print(request.data) quizPDF.objects.create(user=request.user,pdf=request.data['pdf']) return Response(status=status.HTTP_200_OK) except Exception as e: print(e) return Response(status=status.HTTP_400_BAD_REQUEST) Here's how i generated the PDF using kendo-react: const pdfExportComponent = useRef(null); <PDFExport ref={pdfExportComponent} paperSize="A4" margin="1cm"> # DATA return ( <> </PdfExport> <Button onClick = {saveToPDF} > Save </Button> </> ); And here's 'saveToPDF' function : const saveToPDF = (e) => { var file = pdfExportComponent.current axiosInstance.post('/uploadpdf/',{ pdf:file // Sending the PDF to django }).then((res) => { console.log(res.status) }) .catch((function (error) { console.log(error) })) pdfExportComponent.current.save() //User saves it on his //local computer //**that works properly** } The problem must be caused by kendo-react-pdf because i tested the django endpoint using postman (with a normal .pdf file) and everything works properly. Does anyone know how am i supposed to send the kendo-react-pdf? Thank you! -
Would implementing product images in an e-commerce store as a separate database entity take a long time to query? Is there a better approach?
I am creating an e-commerce store in Django and am currently trying to decide between implementing product images as an entity of their own then linking to the product by a foreign key or putting image fields as attributes in the product entity. I would prefer doing the image as a separate entity because then, I will not have a limit to the number of images I can add to a product. My concern is will this come at a huge speed cost for the customers using my website i.e. for my product listing page, I would have to, for each product, filter (query) the images corresponding to the particular product. Are there better, more optimal approaches to doing this? I would give a number of rows in the images table but, I have no idea how many images I will wind up having for the store. -
Django/Django Rest How do I save user device to prevent tedious 2FA on every login?
Hello I have been working with Django Rest Framework and I successfully made Two factor authentication Login based on Email OTP but one thing I want to improve is I want to improve login and save user's device so that repeated 2FA(Two factor Authentcation) can be minimized? here is certain instance of code I did for sending otp on user email. serializers.py class UserLoginSerializer(serializers.Serializer): email = serializers.EmailField() password = PasswordField() views.py classUserLoginView(generics.CreateWithMessageAPIView): """ Use this end-point to get login for user """ message = _('Please check your email for 6 digit OTP code.') serializer_class = serializers.UserLoginSerializer def perform_create(self, serializer): usecases.UserLoginWithOTPUseCase(self.request, serializer=serializer).execute() usecases.py class UserLoginWithOTPUseCase(CreateUseCase, OTPMixin): def __init__(self, request, serializer): self._request = request super().__init__(serializer) def execute(self): self._factory() def _factory(self): credentials = { 'username': self._data['email'], 'password': self._data['password'] } self._user = authenticate(self._request, **credentials) if self._user is not None: """ Sends email confirmation mail to the user's email :return: None """ code = self._generate_totp( user=self._user, purpose='2FA', interval=180 ) EmailVerificationEmail( context={ 'code': code, 'uuid': self._user.id } ).send(to=[self._user.email]) else: raise PermissionDenied( { 'authentication_error': _('User name or password not matched') } ) I am confused how can I allow or save device to prevent repetitive 2FA. -
verify validation code in django rest framework
I'm trying to verify email by sending a code, the first step is to generate the code wheneever the user enters his email, send him the code in the mail then verify this code and return a response. that's how i'm approaching the problem: I created a model named Email_for_Verification ith two fields (email , code) the code is generated randomly, i create an instance of this model when the user enters his email, i send the generated code on email, in the second step, the user enters the received code, and i'm proceeding to the validation with a View named : Verify_code. but i'm encountring an error 'QuerySet' object has no attribute 'code' i have the follwing auestions is it the true approach ? why am i encountring this error ? Here is my code: Models.py def generate_activation_code(): return int(''.join([str(random.randint(0,10)) for _ in range(6)])) class Email_for_Verification(models.Model): email = models.EmailField( max_length=100, verbose_name='email', unique=True) code = models.CharField(max_length=6, default=generate_activation_code) Views.py class Verify_code(APIView): def post(self, request): data = request.data code = data.get('code') email = data.get('email') email_for_verification = models.Email_for_Verification.objects.filter(email=email) if code == email_for_verification.code: return Response({"valid" : "Valid code", "email": email}, status=status.HTTP_404_NOT_FOUND) Response sent in browsable api: { "email":"dummy@mail.com", "code":487954 } Please note that i … -
Access query parameters using axios
So I am using React in the frontend and Django in the backend and I am currently doing the API integration for which I am using Axios. So in the frontend side I am calling a URL like this http://localhost:3000/attempt/?quiz_id=6 and I want the quiz_id = 6 so that I can use this afterward to access data in the backend. I am not sure how to do this, I am new to Web Development. It would be great if you can tell me what should I do. I am using Functional components if that helps. Thanks in advance -
How to auto increment a class variable on django model instance creation?
I am trying to auto increment a model (class variable ) by using django signals. It is working fine but only each time I do switch off my computer the count restart to zero. I do not know what I am doing wrong exactly. Here is the models.py class Project(models.Model): Count = 0 manager = models.ForeignKey( User, related_name="project_managing", on_delete=models.SET_NULL, blank=True, null=True, ) class Saga(models.Model): status = ( ("Do", "Done"), ("Td", "To do"), ("Ir", "In Review"), ("Un", "Under Review"), ("Ap", "Approved"), ("Ca", "Cancelled"), ) name = models.CharField(max_length=45) epic_project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name="sagas", blank=True, null=True ) epic_status = models.CharField(max_length=2, blank=True, null=True, choices=status) epic_key = models.CharField(max_length=30, blank=True, null=True) Here is the signals.py @receiver(pre_save, sender=Saga) def epicKey(sender, instance, *args, **kwargs): if not instance.epic_key: instance.epic_key = ( instance.epic_project.key + "-" + str(instance.epic_project.Count + 1) ) instance.epic_project.__class__.Count += 1 Don't really know why it is re-initializing the count variable. -
Django API: How to get all objects that match certain value in UUID field
when trying to query objects on their foreignkey field, I dont manage to get any details. The company ID is and uuid (uuid4) field. I have a Model called "contacts": class Contact(models.Model): firstname = models.CharField(max_length=35) lastname = models.CharField(max_length=35) company = models.ForeignKey(Company, on_delete=models.CASCADE) I want to get all Contacts, that work for the same company. Therefore I have created a ListAPIView whitin views.py Views.py class ContactViewSet(viewsets.ModelViewSet): queryset = Contact.objects.all() serializer_class = ContactSerializer class CompanyContactsListView(generics.ListAPIView): serializer_class = ContactSerializer def get_queryset(self): company = self.kwargs['company'] return Contact.objects.filter(company=company) And to get a URL I added the path in urls.py urlpatterns = [ path('', include(router.urls)), path('contacts/<uuid:company>/', CompanyContactsListView.as_view(), name='contacts') ] Problem is, that when i try to go for that path and enter an UUID of an company that exists and has related contacts, I get the following error HTTP 404 Not Found Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } Is it possible, that my URL is wrong and therefore cant query the ListAPIView? Because I want result like that: [ { "id": 1, "firstname": "Joshuah", "lastname": "Bankhurst", "company": "e871c47b-9b91-4cf9-94a6-e8135510c11d" }, { "id": 2, "firstname": "Clayborn", "lastname": "Sylett", "company": "e871c47b-9b91-4cf9-94a6-e8135510c11d" } ] Thanks in advance! -
Django : Quering data from related models
So i use Django 3.2.7 and i would like to query all orders from a customer. Models.py class Order(models.Model): STATUS=( ('Pending','Pending'), ('Out for Delivery','Out for delivery'), ('Delivered','Delivered'), ) customer = models.ForeignKey(Customer,null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product,null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=200, null=True, choices=STATUS) Views.py def customer(request,pk): customer = Customer.objects.get(id=pk) orders = customer.order_set.all() my_context={ 'customer':customer, 'orders':orders } return render(request, 'accounts/customer.html', context=my_context) Urls.py path('customer/<str:pk>/', views.customer), Template {% for order in orders %} <tr> <td> {order.product} </td> <td> {order.product.category} </td> <td> {order.date_created} </td> <td> {order.status} </td> <td><a href="">Update</a></td> <td><a href="">Delete</a></td> </tr> {% endfor %} My problem is that instead of printing the actual data on the template is prints the query data. I think the problem is at orders = customer.order_set.all(). What im doing wrong? -
Turning RabbitMQ off makes Django to freeze
I have this class in my project: class CreateReportConsumer(AsyncJsonWebsocketConsumer): async def connect(self): if self.scope['user'].is_authenticated: await self.accept() else: await self.close(401) async def disconnect(self, code): await self.close(code) async def receive_json(self, content, **kwargs): task_id = content.get('task_id') if task_id: result = AsyncResult(task_id) start = datetime.now() while not result.ready(): await sleep(1) if datetime.now() - start > timedelta(seconds=60 * 5): await self.send_json(self.construct_answer([False, 'Connection timed out'])) await self.close(500) break else: if result.state == 'SUCCESS': if len(result.result) == 2: await self.send_json(self.construct_answer(result.result)) await self.close(200) else: await self.close(500) else: await self.send_json(result.result) await self.close(500) else: await self.close(500) def construct_answer(self, data): return {'success': data[0], 'message': data[1]} It gets result from Celery task, when someone using this. But if I turn RabbitMQ off (I am using docker container for that), it freezes. Is there any way of avoiding that? I have tried using pika, but with the same result. Thanks everybody. -
module 'keras.optimizers' has no attribute 'Adam'
when i run this python FlappyBird_AI.py -m train this error occured AttributeError: module 'keras.optimizers' has no attribute 'Adam' -
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'leads.user', but app 'leads' doesn't provide model 'user'
i'm making crm when i type python manage.py migrate i got this error: ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'leads.user', but app 'leads' doesn't provide model 'user'. if you wan't more detail you can tell me i'm little bit beginner here's settings.py AUTH_USER_MODEL = 'leads.User' here's models.py from django.db import models from django.contrib.auth.models import User, AbstractUser class User(AbstractUser): pass class Lead(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) phone = models.BooleanField(default=False) agent = models.ForeignKey("Agent",on_delete=models.CASCADE, null=True) class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) -
Access data after the Question mark(?) [closed]
Suppose I have a URL like this given below and I want to access the quiz_id parameter. http://localhost:3000/attempt/?quiz_id=6 How do I make this possible using Axios and in Django? -
Question regarding to Reactjs and Django, the use of serializer in django-rest-framework
I have a question regarding to the serializer from Django-rest-framework and Reactjs. My question is that can the serializer work itself without the django model? since I don't need to save anything in database. I just want to do post request to backend, and it will take the data and run the ML model, and show the result back to frontend. After that the record will be cleared. Will it be possible to do so without using model? Can I only save serializer instance and give a get request to show it in the frontend? Thank you! -
how to deploy a django project with apache and basic authentication?
I've finished a django project and i want to deploy that on ubuntu server with public ip. but i don't want this project visible to public and i want to set an basic authentication for that. i thought if i set apache basic authentication for a specefic port (for example 8000) and then run django on this port, everything will be ok, but i faced the Listening port for another service (apache) problem and i can't run django on this port. how i can solve this problem? here is my apache config: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> <VirtualHost *:8000> <Location /> #the / has to be there, otherwise Apache startup fails Deny from all AuthUserFile /usr/local/etc/httpd/users AuthName authorization AuthType Basic Satisfy Any require valid-user </Location> DocumentRoot /var/www/html/project ServerName teamproject.example </VirtualHost>