Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make inner join on parent field in Django
For data models shown as below, given the product_name, how shall I do a query with Django ORM to get objects containing "distance, city name, price" sorted by distance, price? ### models.py ### class Province(models.Model): name = models.CharField() class City(models.Model): name = models.CharField() distance = models.IntegerField() province = models.ForeignKey(Province) class Price(models.Model): product_name = models.CharField() province = models.ForeignKey(Province) price = models.IntegerField() Same price apply to all cities within a province -
django rest Error: Missing required positional argument in creating objects
I have these serializer classes and I'm trying to create doctor and user together class UserSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = '__all__' extra_kwargs = { 'password': {'write_only': True} } def create(self, validated_data): print(validated_data) user = User( email=self.validated_data['email'], first_name = self.validated_data['first_name'], last_name=self.validated_data['last_name'], phone_number=self.validated_data['phone_number'], social_id=self.validated_data['social_id'], gender=self.validated_data['gender'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords do not match.'}) user.set_password(password) user.save() return user class DoctorSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Doctor fields = '__all__' def create(self, validated_data): user_data = validated_data.pop('user') print(user_data) user = UserSerializer.create(**user_data) doctor = Doctor( user=user, mc_code=self.validated_data['mc_code'] ) doctor.save() return doctor and I send these json data to these serializers { "user": { "email": "test@test.com", "first_name": "john", "last_name": "doe", "phone_number": "12345678901", "social_id": "1234567890", "password": "password", "password2": "password" }, "mc_code": 123448 } But it gives me this error: Exception Type: TypeError Exception Value: create() got an unexpected keyword argument 'password2' this create() is the create function for UserSerializer I read docs but I couldn't solve the problem. What am I doing wrong? view function just in case @api_view(['POST', ]) @permission_classes(()) def doctor_registration_view(request): if request.method == 'POST': serializer = DoctorSerializer(data=request.data) data = {} if serializer.is_valid(): doctor = serializer.save() else: … -
Django order events by calendar date instead of date posted
I have a newsletter home page that has an events calendar on the side. Sometimes events come up and I need to insert them between two other events. Is there a way I can do this automatically in Django? I know how to order by date posted - for things like blog posts - but I don't see anywhere in the docs how to do this by actual calendar date. This is the code from my view: class HomeView(ListView): model = NewsLetter template_name = 'home.html' def events(self): return Event.objects.all() class PastEventView(ListView): model = PastEvent template_name = 'events.html' ordering = ['event_date'] The past events is alright, but I don't know how to code the order by for the events function under the HomeView class. Any help here would be greatly appreciated. -
how to redirect to a page with pk
i have this function def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('/profile') else: form = EditProfileForm(instance=request.user) args = {'form': form} return render(request, 'store/edit_profile.html', args) i want it to redirect to this function def view_profile(request, pk): data = cartData(request) cartItems = data['cartItems'] shippingAddress = ShippingAddress.objects.get(id=pk) # orderItem = OrderItem.objects.get(id=pk) args = {'user': request.user, 'cartItems': cartItems, 'shippingAddress': shippingAddress} # 'orderItem': orderItem return render(request, 'store/profile.html', args) the urls path('profile/<str:pk>/', views.view_profile, name="view_profile"), path('profile/edit', views.edit_profile, name='edit_profile'), i want the first function to redirect to the second but i got 'Page not found' i know the problem with the pk. so i want it to redirect to profile/id. is there a way to solve it? -
How can i write this if statement?
i have some problems with my if statement. {% for user in users %} {% if tournament.tournament_name != user.user_tournament %} {% else %} <p>{{ user.user_first_name }} {{ user.user_last_name }}</p> {% endif %} {% endfor %} class TournamentUsers(models.Model): user_first_name = models.CharField(max_length=256) user_last_name = models.CharField(max_length=256) user_tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user_last_name + ' ' + self.user_first_name class Tournament(models.Model): data = models.DateField(null=True) tournament_name = models.CharField(max_length=256, null=True) tournament_creator = models.ForeignKey(Judges, on_delete=models.SET_NULL, null=True) tournament_info = models.TextField(max_length=10000) def __str__(self): return self.tournament_name I would like to write something in the form of an entry to a particular tournament where the user after clicking on the "join" button is moved to a sheet where the user is asked to enter their name and choose which tournament they want to join. Is it possible to write a conditional instruction that checks if the name of a given tournament is equal to the name of the tournament that the user has chosen and using it to list the users assigned to the given tournament. -
Django post request looping on same route when using more than 1 replica on Kubernetes cluster
I'm new to kubernetes and was trying to deploy a django app in a shared kubernetes cluster on Kubesail. I was pulling a docker image to run as a container on the cluster. Everything worked as expected until I increased the number of replicas to 2 instead of 1. When I made it 2, my post requests started looping. Meaning, If I'm trying to login into my application, I was again taken back to the login page despite entering the right credentials. Also no user session was created making my app completely inaccessible since all the routes require login. When I made the replicas revert back to 1, everything was normal and app was functioning as expected. Can someone explain why is it so? or can maybe tell what I did wrong? -
How to connect to external MySQL without using models.py in Django
I have my report dashboard that I'm developing using Django and I want to connect it to my MySQL database without using models.py or migrations. Basically, here's what I've done so far. views.py import configparser config = configparser.ConfigParser() config.read('db.ini') def getConnection(): host = config['ord']['host'] port = config['ord']['port'] database = config['ord']['database'] password = config['ord']['password'] user = config['ord']['user'] connection = pymssql.connect(host=host, user=user, password=password, database=database) cursor = connection.cursor() print("Connection Succesfull") return cursor def fill_weight(request): try: sql = u """ SELECT * FROM fill_weight; """ sql =sql.encode('utf-8') cursor.execute(sql) cursor.fetchall() db.ini [oof_ord] host = localhost port = 3306 database = xxxxxxxxxxx user = xxxxxxxxxxx password = xxxxxxxxxxx default-character-set = utf8 The reason why I want to do this is because I don't have the official database that I'm going to use for this system and I want to easily access it by putting it's database credentials to my db.ini and access it to show the data without doing any migrations. Is there anyone that can help me ? -
CSRF verification fails when uploading file in admin inline
In django 2.2.12 I have a simple TabularInline, where I add comments to my main model. As soon as I try to add a file to my comment I get a CSRF error. class Material(models.Model): name= models.CharField(max_length=80) class Comment(BaseModel): material = models.ForeignKey(Material, on_delete=models.SET_NULL, blank=True,null=True,related_name = "comments") comment = models.TextField(null=True, blank=True) document = models.FileField(upload_to='docs/', blank=True, null=True) Admin.py class CommTab(admin.TabularInline): model = Comment extra = 0 class MatAdmin(admin.ModelAdmin): inlines = (CommTab,) If I save it without a file there is no problem. The source code of the page seems to be fine (csrf token is in the form). -
URL Tags to link from another installed app in Django
Running Django 3.0.7 on Python 3.8 I am logging into a Django project in an app: SupplierPortal and am trying to link a Nav button to CashMgmnt. Here is that href in base.py: <li ><a href="{% url 'CashMgmt:customer-detail' pk=id %}">Cash Management</a></li> Here is the urls.py: urlpatterns = [ path('customer/customerdetail/<int:pk>', views.AppCustomerCstDetailView.as_view(), name='customer-detail'), ] Here is the views.py: class AppCustomerCstDetailView(generic.DetailView): model = AppCustomerCst paginate_by = 10 def get_absolute_url(self): return reverse('customer-detail', args=[str(self.id)]) When loading I'm getting the following error: Reverse for 'customer-detail' with no arguments not found. 1 pattern(s) tried: ['customer/customerdetail/(?P<pk>[0-9]+)$'] -
Django-Plotly-Dash multiple users/browser tabs causing mixing of data on plots
I am creating an app in Django that uses Dash and Plotly components. To test some functionality, I dumbed the app down to a page that has a dropdown where a user chooses “latitude” or “longitude” and then the script calls an ISS location API that plots the latitude or longitude of the ISS depending on what the user chooses. This is a live plot that gets updated using dcc.Interval every 3 seconds. This works great, until I open two instances of the app in my browser. If the first browser tab has “latitude” and the second browser tab has “longitude” the plots will mix the data and bounce back and forth plotting both values. Has anybody ever run into this? I have been playing with clientside callbacks and some other things but I am not sure how to get it to not have this bug anymore. I will include the code and what the plot behavior looks like below. data = deque(maxlen=30) timeStamp = deque(maxlen=30) liveOut = DjangoDash("LiveOutput") liveOut.layout = html.Div([ dcc.Dropdown(id='graph-indicator', style={'display': 'block'}, options=[ {'label':"latitude", 'value':"latitude"}, {'label':"longitude", 'value':"longitude"}, ],), dcc.Graph(id='graph', style={'width':'49%', 'display': 'inline-block'}), html.Div(style={'width':'1%', 'display': 'inline-block'}), html.Div(id='hidden-div', style={'display':'none'}), dcc.Interval( id='graph-update', interval=3000, n_intervals=0 ), ]) @liveOut.callback( Output('hidden-div','value'), [Input('graph-indicator','value')],) def … -
Deploy a Django project to AWS EB using Docker and nginx
Currently, I try to deploy a Django project to AWS EB but I'm facing a lot of problems. I could dockerize the project and deploy it on the AWS elastic beanstalk. But when I try to access the site I always see: 502 Bad Gateway. Locally, the project runs smoothly. I am not really into nginx and I have no idea how to solve this problem. This is my project structure: Project structure This is my Dockerfile: # Creating image based on official python3 image FROM python:3 MAINTAINER Jaron Bardenhagen # Sets dumping log messages directly to stream instead of buffering ENV PYTHONUNBUFFERED 1 # Creating and putting configurations RUN mkdir /config ADD config/app /config/ # Installing all python dependencies RUN pip install -r /config/requirements.txt # Open port 8000 to outside world EXPOSE 8000 # When container starts, this script will be executed. # Note that it is NOT executed during building CMD ["sh", "/config/on-container-start.sh"] # Creating and putting application inside container # and setting it to working directory (meaning it is going to be default) RUN mkdir /app WORKDIR /app ADD app /app/ This is my docker-compose file: # File structure version version: '3' services: db: image: postgres environment: … -
Can't run django server in ATOM
I'm trying to run server in atom but I can't! https://i.stack.imgur.com/1OnMY.png -
Django rest framework, migrating from session authentication to token authentication
So this is a generic question, in our django project we have been using session authentication all along. Now for a few reasons, we are planning to move to token based authentication for our project. What are all the things that i should consider while doing this move? I know that we have to add rest_framework.authtoken to our installed apps and change the authentication in REST_FRAMEWORK in settings file. Are there any other steps that i should consider while making this move -
How do I display only some objects in django?
I have a basic blog app, where you can write blogs from the django admin panel. I want to display only ten blogs per page(on the public homepage) and then display the next ten blogs in the next page and so on and display a page number at the bottom of the page, like stackoverflow does on the questions page. It displays 15 questions and then shows which page you're currently on. I am new to django and don't know if any function is available for this purpose. I tried searching on google and stackoverflow, but cannot find any relevant answer. -
Django Model Manager Circular Import issues
Having looked at Django models - Circular-Import-Issue and several other issues reported: slightly different Still having no luck with the following: We have three models: User / Organisation / Actor all within the same app. The user model has the following attributes: class CustomUser(AbstractBaseUser, PermissionsMixin): """ Description: Class holding data about people. People can be members of organisations. Methods: """ id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) first_name = models.CharField( max_length=75, help_text='Enter First Name', verbose_name="First Name" ) # GivenName: IfcLabel middle_name = models.CharField( max_length=75, help_text='Enter Middle Name', blank=True, verbose_name="Middle Names" ) # MiddleNames: IfcLabel actor = models.OneToOneField( Actor, on_delete=models.CASCADE, help_text="Actor ID", verbose_name='Actor ID', null=True, editable=False ) member_of = models.ManyToManyField( Actor, help_text="User is member of which department?", verbose_name='Organisation ID', related_name='user_organisation' ) The Organisation model has the following attributes: id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) identifier = models.CharField( max_length=10, verbose_name='Organisation Code', help_text='Organisation identifier', default='NULL', blank=True, null=True ) name = models.CharField( max_length=75, help_text='Organisation Name', verbose_name="Organisation Name") # actor = models.OneToOneField( actor.Actor, on_delete=models.CASCADE, help_text="Actor ID", verbose_name='Actor ID', null=True, editable=False, ) # Sets up the parent-child relationship between organisations, departments and sub-departments etc. # Departments are modelled as organisations, which have parent_organisation = models.ForeignKey( Actor, on_delete=models.CASCADE, null=True, blank=True, related_name='parent' ) and finally the Actor … -
How to change the existing autofiled id to custom Integer primary key in django - Sqlite3?
We didn't decide any primary key before creating the database and Django created a custom autoincrement primary key called 'id'. We have 20 tables with this primary key. Now, I want to migrate from this auto-increment 'id' primary key to a custom integer primary key without auto-increment. Also, I would like to keep the name of the new primary key as 'id' itself. What is the shortest and easier way of migrating without changing the existing id? Will this work? If I change the SQLite database (remove auto increment) CREATE TABLE "users" (`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT, `name` varchar ( 5 ) NOT NULL, `place` varchar ( 5 ) NOT NULL); Add this line in my model id = models.BigIntegerField(primary_key=True) After this, I can use makemigrations and migrate ? DB used: SQLite3 Thank you in Advance. -
Is Django many to many really necessary?
I have been learning to use Django over the last year and Python is not my native programming language. Normally, when I want to create a many to many relationship, I would create 3 tables, one of which contained two foreign keys to each of the other two tables. For this reason, I find the Django manytomany field very unnatural. Does this many to many field create a third table in the database to store the relationship ? If this is the case, then using a many to many field will stop the class structure from directly representing the table structure. What I am wondering is if there is a reason I should be using this manytomany field or could I get away with using 3 classes to represent a many to many relationship ? Thanks Mark -
searching for encrypted data fields like email django
I am authenticating my user using django email and password . Now I have encrypted my email using pip packedge django-cryptography==1.0. and now when I authenticate user like self.user = authenticate( email='myemail@gmail.com', password='mypass') its giving error Unsupported lookup 'exact' for EncryptedEmailField or join on the field not permitted, perhaps you meant exact or iexact? Is there any work around for it ? Or any way to keep data in db encrypted and use it for authentication . -
Django Celery Task
views.py class ConfirmOrderView(View): def get(self,request): cart=Cart.objects.get(client=request.user.id) products_cart=CartProducts.objects.filter(cart=cart) total_price = sum([product_cart.product.price * product_cart.quantity for product_cart in products_cart]) return render(request, "Products/order.html",{"products_cart":products_cart, "total_price":total_price}) def post(self,request): email_task(request).delay() task.py @app.task def email_task(request): total_price = request.POST.get("totalprice") send_mail( "Total price of your purchases", f"Total price of your purchases is {total_price} zł", "radziszewski.aleksander@gmail.com", [f"{request.user.email}"], fail_silently=False) return render(request,"Products/check_email.html") And I 've got error "AttributeError: 'HttpResponse' object has no attribute 'delay'".Any ideas? -
Set-Cookie Firewall issue
I am a junior dev trying to understand a cookie problem that arose at work. Here is the situation: At the start of the day, all but one development servers failed to accept login via google AuthO. Upon inspection, this was due to cookie issues (Chrome now only delivers cookies with cross-site requests if they are set with SameSite=None and Secure). I found the blocked cookie using Network tool, then added the arguments SameSite='None' and Secure to a set_cookie() function. This was part of Django middleware code that I believe was responsible for issuing a response to successful AuthO. One caveat is that it also has the param httpOnly=true. This fix worked; the error disappeared and I successfully received a session cookie. Today, however, I was told by devOps that the issue was caused by a 'nameserver being moved, causing a timeout', and that a 'firewall fix' resolved the problem. Please help me understand: 1. How does a firewall issue cause this cookie behavior? 2. Are there security concerns with my fix as I read that the Secure tag is noneffective if over HTTP? -
Django PasswordResetDoneView displayed but email not send
I use Django authentication and try to use a new email service. EVen if PasswordResetDoneView is well displayed and other email are sent (send_mail function), mail with link is never received How can it be exokaned and how to resolve this? I have use another eamil services like SendGrid and it works... -
I'm trying to deploy Django via Apache WSGI and It's not going well
I am losing hope with this, I've been trying for weeks but with no success. I'm trying to run a Django project on a windows server accessable via external HTTPS traffic. I've succesfully managed to get Django to serve over http interally using waitress on port 8000, all the static files work correctly and the app runs fine. However, when I try to then move it to Apache I just keep hitting dead end after dead end. I've got this in my Apache vhost.conf <VirtaulHost *:8000> ServerName localhost LoadFile "C:/python37/python37.dll" WSGIPassAuthorization On LoadModule wsgi_module "c:/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/python37" WSGIScriptAlias / "C:/AZPortal/AZPortal/AZConsole/AZConsole/wsgi.py" WSGIPythonPath "C:/AZPortal/AZPortal/AZConsole/" <Directory "C:/AZPortal/AZPortal/AZConsole/AZConsole/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:/AZPortal/AZPortal/AZConsole/staticfiles/" <Directory "C:/AZPortal/AZPortal/AZConsole/staticfiles/"> Require all granted </Directory> </Virtaulhost> As it stands, I just want to be able to see it being hosted by Apache, I'm sure I'd be able to work the rest out after that, but I can't even get that working, please, this is a desperate plea for any advice of help! -
How to access multiple files stored in a file field in django?
We can save multiple files in one filefield, using multiple attribute in HTML input tag and using request.FILES.getlist() and for loop in views. This works properly, but the question is: When we save several files in one filefield of an object, how can we access all of them in templates? I tried the same as the code below but it did not work: {% for foo in obj.filefield %} {{ foo }} {% endfor %} -
Django, accessing nested Many To Many field
I have the following models schema: class Site(models.Model): name = models.CharField(max_length=255) location = models.OneToOneField(GeoLocation, on_delete=models.PROTECT, related_name=RelatedNames.ADDRESS, blank=True, null=True) account = models.ForeignKey(Account, on_delete=models.PROTECT, related_name=RelatedNames.ACCOUNT_SITES) _type = models.IntegerField(choices=SiteTypeChoices.CHOICES) primary_email = models.EmailField(null=True, blank=True) objects = models.Manager() def __str__(self): return self.name def get_site_address(self): return str(self.location) class SiteScore(models.Model): site = models.ForeignKey(Site, on_delete=models.CASCADE, related_name=RelatedNames.SITE_SCORES) date = models.DateTimeField(default=timezone.now) score = models.IntegerField(default=0) score_type = models.IntegerField(choices=SiteScoreChoices.CHOICES, null=True, blank=True) class CustomUser(AbstractUser) username = None email = models.EmailField(_(Fields.EMAIL_ADDRESS), unique=True) accessed_sites = models.ManyToManyField(Site, related_name=RelatedNames.USERS) USERNAME_FIELD = Fields.EMAIL REQUIRED_FIELDS = [] I'm trying to filter out the site scores by date and by the user connected to the sites: worst_scores = SiteScore.objects.filter(date__date=today, site__users=self.request.user).order_by('-score') But this raises this error: The QuerySet value for an exact lookup must be limited to one result using slicing. -
django rest framework api endpoint to direct to foreignkey data
I have two models which are each in a different app. Stock model references Financials model through a foreignkey relationship as shown below. with the current Stock Viewset, also displayed below, I am able to access the individual stock through localhost:8000/stocks/aapl, but I would like to extend that url to include the financials foreign key data such as localhost:8000/stocks/aapl/financials/balance-sheet/. how can I do this ? Stock model class Stock(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) ticker = models.CharField(max_length=10, unique=True, primary_key=True) slug = models.SlugField(default="", editable=False) financials = models.OneToOneField( Financials, on_delete=models.CASCADE, default=None ) Financial Model class Financials(models.Model): # ticker = models.ForeignKey( # Stock, on_delete=models.CASCADE, related_name="balance_sheets" # ) balance_sheet = models.ForeignKey( BalanceSheet, on_delete=models.CASCADE, related_name="balance_sheets" ) income_statement = models.ForeignKey( IncomeStatement, on_delete=models.CASCADE, related_name="income_statements" ) cashflows_statement = models.ForeignKey( CashflowsStatement, on_delete=models.CASCADE, related_name="cashflows_statements", default=None, ) stocks.views.py class StockViewSet(viewsets.ModelViewSet): queryset = Stock.objects.all() serializer_class = StockSerializer lookup_url_kwarg = "ticker" lookup_field = "ticker__iexact"