Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Restrict multiple login for a user in Django Rest Framework
I am attempting to restrict multiple login from a single user in my webapp and for the same I am following this tutorial: https://dev.to/fleepgeek/prevent-multiple-sessions-for-a-user-in-your-django-application-13oo I followed this step by step and when I am logging in using postman(or anything): http://localhost:8000/api/token/ I am unable to see any session that has been created in the ORM. Is it because I am using JWTAuthentication ? apps.py class AccountsConfig(AppConfig): name = 'users' def ready(self): import users.signals signals.py @receiver(user_logged_in) def on_user_logged_in(sender, request, **kwargs): LoggedInUser.objects.get_or_create(user=kwargs.get('user')) @receiver(user_logged_out) def on_user_logged_out(sender, **kwargs): LoggedInUser.objects.filter(user=kwargs.get('user')).delete() Models.py class User(AbstractUser): is_company = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) is_client = models.BooleanField(default=False) @property def full_name(self): return self.first_name + " " + self.last_name class LoggedInUser(models.Model): user = models.OneToOneField(User, related_name='logged_in_user', on_delete=models.CASCADE) # Session keys are 32 characters long session_key = models.CharField(max_length=32, null=True, blank=True) def __str__(self): return self.user.username When I try runserver with this configuration it shows the following error: django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: users settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'users', 'users.apps.AccountsConfig', Where users is the application name -
Image is not shown in django template,
I have a django template where i send an image actually its for an email.It only works when i keep the whole url like abc.com/images/a.png . i have sent he image like this: { 'picture':picture.url } This is the code for template that i am using for email template: <img src="{{picture}}" alt="image" width="200" height="200" > Am i missing something? as it only works when i keep the whole url? -
Is there any way to disable Update (UpdateView) and Delete (DeleteView) functionality after an elapsed time period?
What I wish to achieve is to "disable" the possibility for a user to update or delete a record after a set period of time. In my application, a user creates a delivery booking slot, as part of which they specify a delivery date delivery_date. Requirement: A user should not be able to update/delete a booking slot within 7 days of the delivery_date How would I go about this? models.py from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User class Customer(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=20,null=True) def __str__(self): return self.name # Create your models here. class Booking(models.Model): customer_name = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True) username = models.ForeignKey(User,on_delete=models.CASCADE) qty_plts = models.PositiveSmallIntegerField(default=1) cbm = models.PositiveSmallIntegerField(default=1) created_date = models.DateTimeField(default=timezone.now()) delivery_date = models.DateField(null=True) delivery_time = models.TimeField(null=True) booking_number = models.CharField(max_length=50,unique=True) def __str__(self): return self.booking_number def save(self, **kwargs): if not self.booking_number: self.booking_number = f"{self.delivery_date:%Y%m%d}{self.delivery_time:%H%M}" super().save(**kwargs) def get_absolute_url(self): return reverse('bookmyslot:detail',kwargs={'pk':self.pk}) views.py from django.shortcuts import render # Create your views here. from .models import Booking,Customer from .forms import BookingForm from django.urls import reverse,reverse_lazy from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import (ListView,DetailView,CreateView,UpdateView,DeleteView,TemplateView) class AboutView(TemplateView): template_name = 'about.html' class HomeView(TemplateView): template_name = 'index.html' class BookingCreate(LoginRequiredMixin,CreateView): login_url = '/login' redirect_field_name = 'bookmyslot/booking_detail.html' model … -
KeyError in Safari, but it works in Firefox
Please help solve the problem! I am writing an online store in Django, it was necessary to split it into retail/wholesale with keeping one base. At one point safari started giving me KeyError, but in Firefox everything continues to work according to the logic. What could be the reason? Error looks like: "KeyError at /cart/retail/ 'price' Request Method: GET Request URL: http://127.0.0.1:8000/cart/retail/ Django Version: 3.2.7 Exception Type: KeyError Exception Value: 'price' Exception Location: /Users/vitbashy/Desktop/Projects/dekor-keramika/dekor_keramika/cart/**cart.py**, line 69, in __iter__ Python Executable: /Users/vitbashy/Desktop/Projects/dekor-keramika/venv/bin/python Python Version: 3.9.6" cart.py: def add_retail(self, product, quantity=1, update_quantity=False): # Add a product to cart or update its quantity product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = { 'quantity': 0, 'price': str(product.price_retail) } if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): # Updating the cart session self.session[settings.CART_SESSION_ID] = self.cart # Mark the session as "modified" to make sure it is saved self.session.modified = True def remove(self, product): # Removing an item from the cart product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): """ Search for items in the shopping cart and retrieve products from the database. """ product_ids = self.cart.keys() # Receive product items and add them to cart … -
Limit forms foreign key to a choices in related model
I am working on creating a form but stuck at this issue. I have several businesses in the Business Model. Each Business has its own Service in Services Model. The User is tied to only one Business. Both Business, Service have a relationship. My Challenge I have a Service Request Form. When I present this Service Request Model Form, I want to show only services for One Business, that the customer/user belongs to. Please help me how this is possible. I thought it would be like "Instance = Business". I understood its not that simple. For example: Business1 has "Cars" and "Motor Bikes" as Services and Business2 has "nails" and "Hair Spa" as services. If a user from Business1 logged in and opened Service Request Form, She/He should see only "Cars" and "Motor Bikes" in service selection drop down. ''' # class Service(models.Model): class Business(models.Model): name = models.CharField(max_length=25) description = models.CharField(max_length=100) active = models.BooleanField(default=True) class BusinessUser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name='business') class Services(models.Model): business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name='business_services') name = models.CharField(max_length=15) active = models.BooleanField(default=True) class ServiceRequest(models.Model): business = models.ForeignKey(Business, on_delete=models.DO_NOTHING) service = models.ForeignKey(Service, on_delete=models.DO_NOTHING, blank=True) requester_name = models.CharField(max_length=15) class ServiceRequestForm(forms.ModelForm): class Meta: model = ServiceRequest fields … -
Local variable 'cid' referenced before assignment
Im trying to add a payment method. I also add Getway and Get Success Message. Now I want to show success message with cid and name in my template page. When I want to get context data, I got This Error. ** Local variable 'cid' referenced before assignment. ** My code: class CheckoutSuccessView(View): model = Transaction template_name = 'success.html' def get(self, request, *args, **kwargs): # return render(request, self.template_name,{'transaction':transaction}) return HttpResponse('nothing to see') def post(self, request, *args, **kwargs): data = self.request.POST try: Transaction.objects.create( name = data['value_a'], cid = data['value_b'], tran_id=data['tran_id'], val_id=data['val_id'], amount=data['amount'], card_type=data['card_type'], card_no=data['card_no'], ... ... ) messages.success(request,'Payment Successfull') name = data['value_a'], cid = data['value_b'], except: messages.success(request,'Something Went Wrong') context = { 'cid': cid, 'name' : name } return render(request, 'success.html', context) -
How to display all celery tasks in django template
I have a django web application that uses celery to run tasks. I want to display all the tasks that are in queue and tasks that are currently running in a django template. I looked at this link. But I am not sure how to get this into the django views. This is my views.py file def views_tasks(request): # get the list of tasks here and send it to the context context = {} return render(request, 'tasks.html',context=context) How do I go about doing this? Thanks -
keyerror in drf serializer
I have a serializer like this : class LocationSerializer(serializers.Serializer): lat = serializers.DecimalField(max_digits=9, decimal_places=6), lng = serializers.DecimalField(max_digits=9, decimal_places=6), term = serializers.CharField(max_length=100) in views.py : @api_view(['POST']) def get_prefer_locations(request): serilizer = LocationSerializer(data=request.data) if serilizer.is_valid(): print(request.data) location_obj=Location(serilizer.data['lat'],serilizer.data['lng'],serilizer.data['term']) address = location_obj.convert_latandlong_to_address() and this is the Location class that i have defined : class Location: def __init__(self, latitude,longitude,term): self.lat = latitude, self.lng=longitude, self.term=term def convert_latandlong_to_address(self): geolocator = Nominatim(user_agent="geoapiExercises") location = geolocator.reverse(self.latitude+","+self.longitude) address = location.raw['address'] return address when i printed request.data in terminal i got this : {'lat': '29.623411959216355', 'lng': '52.49860312690429', 'term': 'cafe'} but i got this error : File "/home/admin1/mizbanproject/location/preferlocation/api/views.py", line 15, in get_prefer_locations location_obj = Location(serilizer.data['lat'],serilizer.data['lng'],serilizer.data['term']) KeyError: 'lat' and this is the json i am sending via postman: { "lat":"29.623411959216355", "lng":"52.49860312690429", "term":"cafe" } -
Testing HTML Templates/Paths to make sure they load properly
I'm currently using this code that I found on a separate post from Stack Overflow, but when I run it, it throws the error that pattern has no child regex. class UrlsTest(test.SimpleTestCase): def test_responses(self, allowed_http_codes=[200, 302, 405], credentials={}, logout_url="logout", default_kwargs={}, quiet=False): """ Test all pattern in root urlconf and included ones. Do GET requests only. A pattern is skipped if any of the conditions applies: - pattern has no name in urlconf - pattern expects any positinal parameters - pattern expects keyword parameters that are not specified in @default_kwargs If response code is not in @allowed_http_codes, fail the test. if @credentials dict is specified (e.g. username and password), login before run tests. If @logout_url is specified, then check if we accidentally logged out the client while testing, and login again Specify @default_kwargs to be used for patterns that expect keyword parameters, e.g. if you specify default_kwargs={'username': 'testuser'}, then for pattern url(r'^accounts/(?P<username>[\.\w-]+)/$' the url /accounts/testuser/ will be tested. If @quiet=False, print all the urls checked. If status code of the response is not 200, print the status code. """ module = importlib.import_module(settings.ROOT_URLCONF) if credentials: self.client.login(**credentials) def check_urls(urlpatterns, prefix=''): for pattern in urlpatterns: if hasattr(pattern, 'url_patterns'): # this is an included urlconf … -
Django CreateView form can't submit
My views: class AddSuiteView(CreateView): model = TestSuite form_class = TestSuiteForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) my_TestCase = TestCase.objects.all() context['my_testcase'] = my_TestCase return context def get_success_url(self): return reverse("integratedTest:testSuite") My form.py: class TestSuiteForm(forms.ModelForm): class Meta: model = TestSuite fields = ( 'name', 'test_case_list', 'created_by' ) My model is: class TestSuite(models.Model): name = models.CharField(max_length=200) test_case_list = models.CharField(max_length=200, validators=[validate_comma_separated_integer_list], default = "1") created_by = models.CharField(max_length=200, default = "anyone") create_datetime = models.DateTimeField("TestSuite created on", auto_now = True) My html is a bit complex: <form method="post"> {% csrf_token %} <script src="https://code.jquery.com/jquery-3.5.0.min.js"></script> <h1 class="addsuite">Create Test Suite:</h1> <p> <label for="id_name">Name:</label> <input type="text" id="id_name" name="name" required><br><br> </p> <p> <label for="id_test_case_list_select_l">test_case_list(double click to add):</label><br><br> <select size=10 name="test_case_list_select_l" id="id_test_case_list_select_l" class="multiselect" multiple="multiple" > {%for case in my_testcase %} <option value="{{case.name}}" >{{case.name}}</option> {%endfor %} </select> <br><br> <label for="id_test_case_list_select_r" >test case selected(double click to remove):</label><br> <select size=10 name="test_case_list_select_r" id="id_test_case_list_select_r" class="multiselect" multiple="multiple" > </select> <input type="hidden" id="id_test_case_list" name="test_case_list" value=""> <p>&#8679; <input type="button" id="addTestcaseByOne" value="++" onclick="addTestcaseByOne"> </p> <p>&#8681; <input type="button" id="decreaseTestcaseByOne" value="--" onclick="decreaseTestcaseByOne"> </p> <br><br> </p> <p> <label for="id_created_by">created_by:</label> <input type="text" id="id_created_by" name="created_by" "><br><br> </p> <input type="submit" value="Save"> </form> <script> $(document).ready(function() { $("#id_test_case_list_select_l").dblclick(function() { var selectedItem = $('#id_test_case_list_select_l').find(":selected").text() $('#id_test_case_list_select_r').append ('<option value= ' + selectedItem + '"*1">'+selectedItem+'*1</option>') var old_val = $('#id_test_case_list').val() //alert("old_val" + old_val) var new_val … -
Is there a function that updates var value in django views.py?
Good day, I am very new to django and programming in general. Is there a function that updates variable values based on user input? I would like to write a function that displays output to html using HttpResponse and waits for user input... on my views.py, I have the following: def getResponse(request): userMessage = request.GET.get('userMessage'); return HttpResponse("Good to see you. May I know your name?") name=input(userMessage) return HttpResponse("Good to know you", name, ". I can tell you your age if you tell me which year you were born") year=input(userMessage) age = ((datetime.date.today().year) - year) return HttpResponse("You are", age "old") My Html is looking like this: <div id="userInput"> <form id="user_Input" method="post"> {% csrf_token %} <input type="text" name="userMessage" id="textInput" placeholder="Type your message..."> <input type="submit" id="buttonInput" name="" value="Send"> </form> </div> </div> <script type="text/javascript"> function getUserResponse(){ var userText =$('#textInput').val(); var userHTML = "<p class='userText'>User: <span>"+userText+"</span></p>"; $('#textInput').val(""); $('#pal').append(userHTML); $.get('/qpal/getResponse',{userMessage:userText}).done(function(data){ var returnedMessage = "<p class='botText'> Pal: <span>"+ data +"</span></p>"; $('#pal').append(returnedMessage); }) } $('#buttonInput').click(function(e){ e.preventDefault(); getUserResponse(); }) </script> The html works, however it is only displaying the first HttpResponse value everytime like shown in the picturescreenshot. In pure python environment the code will work perfectly using only print and input and I am trying to make it … -
is it possible to customize django 3 nav_sidebar menu as a custom group?
I'd like to customize the left sidebar with my own caption and models list. The default nav_sidebar is: myapp A - model A.1 - model A.2 myapp B - model B.1 - model B.2 Is it possible to have this following instead? Custom name - model A.1 - model B.1 I'd appreciate any feedback -
UnboundLocalError at /register/ local variable 'form_value' referenced before assignment
I'm trying to get into it the register page but i cant views.py def registerPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method == 'POST': form_value = CreateUserForm(request.POST) if form_value.is_valid(): form_value.save() user = form_value.cleaned_data.get('username') messages.success(request, 'Account was create for {}'.format(user)) return redirect('login') context = {'form_key':form_value} return render(request, 'accounts/register.html', context) Traceback File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\le\Desktop\django-course\Django(02-09-21)\crm1\accounts\views.py", line 26, in registerPage context = {'form_key':form_value} UnboundLocalError: local variable 'form_value' referenced before assignment Maybe have problem with indentation, please help me -
How to change queryset to dataframe in an environment where pandas is not installed or how to run code without pandas
I'm running the code in an environment where pandas cannot be installed. What do I need to fix to make the code below work in an environment without pandas ? (This is the code that ran successfully when tested in the environment where pandas is installed.) def download_supporting(request): locale.setlocale(locale.LC_ALL, 'ko_KR.UTF-8') supportings = Supporting.objects.filter(is_deleted='0').order_by('register_date') \ .annotate(register_date_str=Cast('register_date', CharField())) \ .values_list(register_date_str', 'name', 'sex', 'age', 'memo') #supportings = pd.DataFrame.from_records(supportings) #supportings = supportings.rename(columns={0: 'register_date_str', # 1: 'name', # 2: 'sex', # 3: 'age', # 4: 'memo'}) ----> Commented out to run without pandas. output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() merge_format = workbook.add_format({'bold': True, 'border': 1, 'align': 'center', 'valign': 'vcenter', 'text_wrap': True}) for supporting in supportings[0].unique(): ----> 'tuple' object has no attribute 'unique' u = supportings.loc[supportings[0] == supporting].index.values + 1 if len(u) < 2: pass # do not merge cells if there is only one supporting day else: worksheet.merge_range(u[0], 0, u[-1], 0, supportings.loc[u[0], 'Day'], merge_format) workbook.close() output.seek(0) supportings.set_index(supportings.columns[:-1].tolist()).to_excel('supporting.xlsx') -
How can I successful POST a Choice that is linked to a Question in a Poll's API in Django?
I am creating a survey / voting api, I can successfully POST question but I am getting the following error Choice() got an unexpected keyword argument 'question' when I try to create a choice that is linked to a question, I can't figure it out. These are the models from django.db import models import datetime from django.utils import timezone # Модели для опоросов class Question(models.Model): poll_question = models.CharField(max_length=255, blank=False) title = models.CharField(max_length=255, blank=True) start_date = models.DateTimeField('date published', blank=False) def __str__(self): return self.poll_question def published_not_longage(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.start_date <= now #Модель для Выбора class Choice(models.Model): poll_question = models.ForeignKey(Question, on_delete=models.CASCADE) poll_question_choice = models.CharField(max_length=255) votes = models.IntegerField(default=0) The choices serializer class ChoiceSerializer(serializers.Serializer): poll_question_choice = serializers.CharField(max_length=255) def create(self, validated_data): return Choice.objects.create(**validated_data) #The choices view - The error is arising when I pass in the question instance in the serializer.save() method. @api_view(['POST']) def choice_details(request, pk): question = Question.objects.get(pk=pk) # question = get_object_or_404(Question, pk=pk) serializer = ChoiceSerializer(data=request.data) if serializer.is_valid(): poll_question_choice = serializer.save(question=question) return Response(ChoiceSerializer(poll_question_choice).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Reverse query name clash on Django Abstract base classes
I am constructing Django model of files and I want to use an abstract base class for generic attributes and have it inherited by my specific models just like this. class File(models.Model): options = (("published", "Published"), ("draft", "Draft")) name = models.CharField(max_length=255) folder = models.ForeignKey(Folder, on_delete=models.CASCADE, blank=True, null=True, related_name="resource_file") status = models.CharField(max_length=10, choices=options, default="draft") tags = models.CharField(max_length=10) assignee = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True, related_name="+", ) dateCreated = models.DateTimeField(default=timezone.now) dateUpdated = models.DateTimeField(default=timezone.now) class Meta: abstract = True def __str__(self): return self.name class QuillFile(File): content = models.TextField(blank=True, null=True) def upload_to(instance, filename): return "posts/{filename}".format(filename=filename) class UploadedFile(File): file = models.FileField(upload_to=upload_to, blank=True, default="") but I when I run makemigrations I got this error that says: Reverse query name for 'classrooms.UploadedFile.folder' clashes with reverse query name for 'classrooms.QuillFile.folder'. HINT: Add or change a related_name argument to the definition for 'classrooms.UploadedFile.folder' or 'classrooms.QuillFile.folder'. I tried changing and doing what's on the hint and put the assignee field on the children model and have them different related_name but I still got an error. Help. -
PackagesNotFoundError: The following packages are not available from current channels: - manage
This is my first question here. I'm new to Python, Django and Anaconda. I am trying to follow this tutorial but I keep running into hiccups. I found a similar answer to my question and I'm willing to admit that I could be misunderstanding something due to my lack of experience. I am using PyCharm and I'm installing the necessary packages (as needed for the tutorial) via the gui and I'm using the terminal inside PyCharm. At this part of the tutorial where you're supposed to run the server of the project, I keep getting this error: PackagesNotFoundError: The following packages are not available from current channels: - manage Whenever I go to install from conda forge or pip install in the terminal, I am met with the same errors. Like I said, I found a similar post on here, but it is not the solution I need. I'm also not exactly sure what I'm doing wrong. I've installed and updated python and django, and everything requested in the tutorial. PackagesNotFoundError: The following packages are not available from current channels: Thank you in advance for anyone who helps me. -
Converting/ Parsing HTML to Word in a Django Project
I want to add the option to convert my HTML with information in to a word document. I have the PDF with some CSS: <h1> {{ info.businessName }}<br /> <small style="color: rgb(187, 187, 184); margin: 0px 0px 0px 0px" >Business Plan <br /> Prepared {{ info.date_posted|date:"F Y" }} </small> </h1> Here is the views.py def order_word(request, info_id): info = get_object_or_404(Info, id=info_id) html = render_to_string('businessplan/word.html', {'info': info}) response = HttpResponse(content_type='application/word') response['Content-Disposition'] = 'attachment; filename="{}-Business Plan.pdf"'.format(info.businessName) return response Here is the URL.py path('<str:info_id>/word/', order_word, name='order_word'), Here is the link to download the word: <a href="{% url 'businessplan:order_word' form.instance.id %}"> <button type="button" class="btn btn-primary"> Download Word </button> </a> -
Uncaught ReferenceError: jQuery is not defined Django jQuery CDN
I am building a Django webapp and want to use a JS extension that creates a weekly schedule link. I have placed this extension in the static directory of my project and imported jQuery and the extension in the of my base.html as so: <!-- jquery --> <script src="https://code.jquery.com/jquery-3.3.1.min.js" defer></script> <!-- jQuery schedule display (includes css and js) --> <link rel="stylesheet" href="{% static 'Dynamic-Weekly-Scheduler-jQuery-Schedule/dist/jquery.schedule.css' %}"> <script src="{% static 'Dynamic-Weekly-Scheduler-jQuery-Schedule/dist/jquery.schedule.js' %}"></script> Yet, when I attempt to pass data into this plugin as so: <script type="text/javascript"> console.log({{schedule_data}}) $("schedule").jqs({{schedule_data}}) </script> I get an error in jquery.schedule.js: Uncaught ReferenceError: jQuery is not defined referring to the end of this file that is: $.fn[pluginName] = function (options) { var ret = false; var args = Array.prototype.slice.call(arguments); var loop = this.each(function () { if (!$.data(this, 'plugin_' + pluginName)) { $.data(this, 'plugin_' + pluginName, new Plugin(this, options)); } else if ($.isFunction(Plugin.prototype[options])) { ret = $.data(this, 'plugin_' + pluginName)[options](args); } }); if (ret) { return ret; } return loop; }; })(jQuery, window, document); What am I doing wrong? Should I not be using jQuery CDN? Note that jQuery isn't defined elsewhere in the jquery.schedule.js document. Thank you -
TemplateDoesNotExist at / index.html in Docker | react with django
Why my react build folder doesn't serve after run python manage.py collectstatic command in Dockerfile? I have tried for a long time to dockerized my whole project but I did fail to collect static files. Where I miss please have a look into it. ***This is my backend/Dockerfile inside django project *** FROM python:3.9.5-slim ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apt-get update && apt-get install build-essential python-dev -y COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt && pip3 install uwsgi WORKDIR /django COPY . . CMD ['RUN', 'python', 'manage.py', 'collectstatic', '--noinput'] EXPOSE 8000 CMD ["uwsgi", "--http", ":9090", "--wsgi-file", "IMS/wsgi.py", "--master", "--processes", "4", "--threads", "2"] And this is my frontend/Dockerfile inside my react folder FROM node:13.12.0-alpine WORKDIR /react COPY . . RUN npm install RUN npm run build EXPOSE 3000 And finally, this is my docker-compose.yml file where I setup 3 services version: "3.3" services: backend: build: context: ./backend/ command: gunicorn IMS.wsgi --bind 0.0.0.0:8000 container_name: ims-backend restart: always ports: - "8000:8000" networks: - ims-network ims-postgres: image: "postgres:14beta2-alpine3.14" restart: always container_name: ims-postgres hostname: emrdsaws.czlz2b677ytu.ap-south-1.rds.amazonaws.com environment: - POSTGRES_PASSWORD=zkf!%uW_?&UG%4 - POSTGRES_DB=imsrds - POSTGRES_USER=dbrdsubuntume12 ports: - 5432 frontend: build: context: ./frontend/ volumes: - react_build:/react/build expose: - 3000 stdin_open: true nginx: image: nginx:latest … -
axios get request depending on user data fails
I've setup an auth system with nuxtjs & django. However i do not understand nuxtjs completely <template> <div> {{ this.$auth.$storage.state.user.email }} </div> </template> <script> import axios from 'axios'; export default { } axios.get('/api/v1/is-success-or-not?email='+this.$auth.$storage.state.user.email) .then((response) => { if(response.data === "True") { console.log("Player is success") $nuxt.$router.push('/schedule') } }) axios.get('failureornot?email='+this.$auth.$storage.state.user.email) .then((response) => { if(response.data > 3) { console.log("failure") $nuxt.$router.push('/failure') } }) </script> This is my code I've the email that shows up with {{ this.$auth.$storage.state.user.email }} but when i try to adapt the get request depending on the user, i get this error Cannot read properties of undefined (reading '$auth') I do not understand because $auth is obviously define if i can print the value thanks for your help ! -
Django - Sqlite column names different from model field name
I've had a model with a field named enclosure_id. I changed the field name to enclosure_name in the model and everywhere in the code, since that seemed more appropriate to the content. Now the respective column in the db is called enclosure_name_id I do not understand how this name is created. And I'm not able to get rid of this. I've deleted the database (I'm still at a testing phase) and all migrations, it's always regenerated as enclosure_name_id. Nowhere in my entire code is there an occurence of enclosure_name_id. If anyone could help me out, this would be great. Best regards, Gero -
How to serialize multiple models in on serializer with Django?
I try to combine multiple serializers into 1 so I don't have to do multiple fetch on the front end for the same page. Seems that I must use SerializerMethodField. My views is quite simple : @api_view(['GET']) def get_user_profile_by_name(request, name): try: user_profile = UserProfile.objects.get(display_name=name.lower()) serializer = UserProfileSerializer(user_profile, many=False) return Response(serializer.data) except ObjectDoesNotExist: message = {'detail': 'User does not exist or account has been suspended'} return Response(message, status=status.HTTP_400_BAD_REQUEST) As this can be accessed by Anonymous user, I can't use request.user All models I want to access inside UserProfileSerializer are related to UserProfile. So I dont really know how to setup my serializer. ( I have more serializer to combine but I limited this to one serializer inside the serializer for the example ) class UserProfilePicture(serializers.ModelSerializer): class Meta: model = UserProfilePicture fields = '__all__' class UserProfileSerializer(serializers.ModelSerializer): profile_picture = serializers.SerializerMethodField(read_only=True) class Meta: model = UserProfile fields = '__all__' def get_profile_picture(self, obj): # What to do here ? I struggle to understand how to acces " user_profile " object from UserProfileSerializer in order to query the right UserProfilePicture object and return the data combined inside UserProfileSerializer. -
django can't import anything from django allauth
So i have my django project running inside a docker container i have included this in my requirements.py file django-allauth==0.45.0 and this in my settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'main.apps.MainConfig', 'rest_framework', 'django.contrib.humanize', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', ] and this in my urls.py and it's running perfectly urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path("accounts/", include("allauth.socialaccount.providers.google.urls")), path("accounts/", include("allauth.socialaccount.providers.facebook.urls")) ] in my signals.py file this is what's not working, it's this line: from allauth.account.views import LoginView, allauth.account.views is underlined in red and i didn't get any error in the terminal but in the problems section i have Import "allauth.account.utils" could not be resolved -
In Django template, how can we access column from other child from same parent
I have Stocks as a parent table, Advice and Indexmapper as child table, from view I am returning Advice queryset nad in template, I want to access Indexmapper.index_name from Advice queryset. model.py class Stocks(models.Model): ticker = models.CharField(max_length=30, primary_key=True, unique=True) company_name = models.CharField(max_length=100, blank=True, null=True) sector = models.CharField(max_length=50, blank=True, null=True) class Meta: db_table = 'stocks' class Advice(models.Model): ticker = models.ForeignKey(Stocks, db_column='ticker', related_name='advices', on_delete=models.CASCADE) advice_date = models.DateTimeField(blank=True, null=True) high20 = models.FloatField(blank=True, null=True) class Meta: db_table = 'advice' unique_together=(('ticker','advice_date'),) class IndexMapper(models.Model): index_name = models.TextField(blank=True, null=True) ticker = models.ForeignKey(Stocks, db_column='ticker',on_delete=models.CASCADE, related_name='indexmap', blank=True, null=True) class Meta: db_table = 'indexmapper' unique_together=(('index_name','ticker'),) view.py ifund = IndexMapper.objects.filter(index_name='NIFTY 50') filter_stock = all_stocks_obj.filter(indexmap__in=ifund) result = Advice.objects.filter(ticker__in=filter_stock) return render(request, 'screeners.html',{'result':result}) in template I want to access IndexMapper.index_name. I tried like this but not working {{result.ticker.indexmap.index_name}}