Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid integrity errors occuring because of concurrent creations/updates?
So let's say there's a model A which looks like this: class A(model): name = char(unique=True) When a user tries to create a new A, a view will check whether the name is already taken. Like that: name_taken = A.objects.get(name=name_passed_by_user) if name_taken: return "Name exists!" # Creating A here It used to work well, but as the system grew there started to appear concurrent attempts at creating A's with the same name. And sometimes multiple requests pass the "name exists check" in the same few milliseconds, resulting in integrity errors, since the name field has to be UNIQUE, and multiple requests to create a certain name pass the check. The current solution is a lot of "try: except IntegrityError:" wraps around creation parts, despite the prior check. Is there a way to avoid that? Because there are a lot of models with UNIQUE constraints like that, thus a lot of ugly "try: except IntegrityError:" wraps. Is it possible to lock as to not prevent from SELECTing, but lock as to prevent from SELECTing FOR UPDATE? Or maybe there's a more proper solution? I'm certain it's a common problem with usernames and other fields/columns like them, and there must be a … -
How to Log Out from Keycloak from Django Code
Can not log out from keycloak IDP from inside of Django app code. All stackoverflow answers did not work fo me (most are for older version of the components involved), the same goes for the keycloak documentation. Recently another programmer implemented keycloak-based athentication for our Django-based website. Works fine for auth. The app is build by docker, three containers: the website on port 8000, keycloak db (postgres image), keycloak (jboss/keycloak image) on port 8080. Now I have to add "Logout" functionality to it, meaning singing out of keycloak from my Django code, and redirect the user back to the keycloak login screen. Django 2.2 Python 3.5 keycloak 7 social-auth-app-django 3.1.0 social-auth-core 3.2.0 settings.py SOCIAL_AUTH_KEYCLOAK_KEY = '<some keycloak key>' SOCIAL_AUTH_KEYCLOAK_SECRET = 'some keycloak secret' SOCIAL_AUTH_KEYCLOAK_PUBLIC_KEY = 'some public key' SOCIAL_AUTH_KEYCLOAK_AUTHORIZATION_URL = 'http://<some ip>:8080/auth/realms/<some realm>/protocol/openid-connect/auth' SOCIAL_AUTH_KEYCLOAK_ACCESS_TOKEN_URL = 'http://<some ip>:8080/auth/realms/<some realm>/protocol/openid-connect/token' SOCIAL_AUTH_STRATEGY = 'social_django.strategy.DjangoStrategy' SOCIAL_AUTH_STORAGE = 'social_django.models.DjangoStorage' SOCIAL_AUTH_KEYCLOAK_ID_KEY = 'email' SOCIAL_AUTH_POSTGRES_JSONFIELD = True SOCIAL_AUTH_URL_NAMESPACE = 'social' LOGIN_REDIRECT_URL = 'http://<website ip>:8000/' LOGOUT_REDIRECT_URL = 'http://<website ip>:8000/' SOCIAL_AUTH_POSTGRES_JSONFIELD = True SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.mail.mail_validation', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.debug.debug', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'social_core.pipeline.debug.debug', ) docker-compose.yml version: '3' services: web: restart: unless-stopped container_name: web-container build: context: . dockerfile: Dockerfile.dev ports: - "8000:8000" environment: PRODUCTION: 'false' … -
Django Admin Area "TextField" replacement. Issue with greek characters
I have replaced the standard Django "TextField" field with TinyMCE, CKEditor and Froala. When I type a greek word inside the editors (all of them) in the Admin Area, the result in the frontend app is HTML codes. For example, I type my name Αδριανός and I see <p>&Alpha;&delta;&rho;&iota;&alpha;&nu;ό&sigmaf;</p> I use Postgres with encoding=UTF8, Collate=English_United States.1253, CType=English_United States.1253 -
django opened file type to python opened file type
I have a django app that asks the user to upload an image. I get the image from html django. This image I pass to the python script as a parameter. I did a lot of stuff with this image (like using the PIL libraries), the class of the parameter is: 'django.core.files.uploadedfile.InMemoryUploadedFile' But the problem comes when I try to use one function that ask for the predeterminate type of .open() of python, that is: '_io.BufferedReader' Concretely, the function I'm using is: block_blob_service.create_blob_from_stream() (a Microsoft Azure function) So my question is, can I convert from django opened file type to python opened file type? It may be without saving the file and opening again. And, if by any chance, somebody has worked with this library, I've also tried block_blob_service.create_blob_from_bytes() and it's not working (to convert from django to bytes I've just done img = django_input.read() (I get a Bytes type) and block_blob_service.create_blob_from_path(), is not an option, because I can't get the path of the file, nor I don't want to save the image and get a new path. -
How to pass blank=false behavior to model form validation in django?
I have this model: Class MyModel(Model): other_field = CharField(max_length=200, null=True) my_field = BooleanField(null=True) and have this modelform class MyModelForm(ModelForm) class Meta: model = MyModel fields = ('my_field', ) my view: def my_view(request): template_name = 'my_template.html' context = {} if request.POST: my_model_form = MyModelForm(request.POST) if my_model_form.is_valid(): my_model_form.save() return redirect('other_url') else: my_model_form = MyModelForm() return render(request, template_name, context) in template I have: <form method="post" novalidate> <div> {% csrf_token %} {% form.as_p %} </div> <button>Save changes</button> </form> What I expect is that because in my_field I do not have blank=True`` and as a result it isblank=False, and I havenovalidate, I should not be able to save the form. But I see no validation error even if I leave my_field blank. However,other_field``` can not be left blank. -
how to use collapse in dynamic content when retrieving from database?
i have a bootstrap card that contains data retrieved from the database where this card has a card header that includes a link that is used to collapse extra data (hide/show) inside each card. what in my opinion is a logic is to get the id of each card and make the link open the selected card and not as a static card. the problem is that when i click the link nothing happen and there is now error. urls.py path("displaydata/<int:id>/",displaydata,name = "displaydata") views.py def displaydata(request,id): c = cursor.execute('SELECT ID,Nickname_,Date_of_Birth FROM Person_ WHERE ID = id ') print("c ===>",c) while True: result = c.fetchone() if result == Nonedjan: break print("result ===>", result) return redirect("search") return render(request,"displaydata.html",{"c":c}) pictureCard.html <div class="container"> <div class="row justify-content-center"> {% for obj in object_list %} <div class="col-xs-12 col-sm-6 col-md-6 col-lg-4 col-xl-3 mb-5"> <div class="p-2 my-flex-item"> <div class="card innercardzoom"> <div class="inner"> <img src="{% static '/img/card/1.png'%}" class="card-img-top" alt="..."> </div> <h5 class="card-header"> <a class="collapsed d-block" data-toggle="collapse" href="{% url 'displaydata' obj.0 %}" aria-expanded="true" data-target = "#table-collapsed" caller-id ="" aria-controls="collapse-collapsed" id="heading-collapsed"> <i class="fa fa-chevron-down pull-right"></i> details <script type="text/javascript"> $(document).on('click','.collapsed d-block',function(){ $('#heading-collapsed').attr('caller-id',$(this).attr('id')); }); </script> </a> displaydata.html {% for row in c %} <div id="table-collapsed" class="collapse" aria-labelledby="heading-collapsed"> <table class="card-body table-sm table table-hover text-right"> <tbody> … -
Highlight only the row of the specific player
I am developing a game using python and django templates. In the first step, each player enters his/her name(they are playing on different laptops). In the second step, a value. After that, they get the whole input displayed as a dataframe, sorted by their values. Since they should not know about the names of the others, I was thinking of dropping the name collumn using df1 = df.drop(['Position'], axis=1) However, the players should still know which value they inserted, which is why I want to highlight their specific row. Means Player A sees only his row in green, Player B sees only his row in green etc. The highlight would be based on df.style.apply(lambda x: ['background: lightgreen' if x.name == ????? else '' for i in x], axis=1) with x is the amount of players. However, I am not able to connect the specific entered name to the highlight functions I create a form field using django template and python code class Welcome(Page): form_model = 'player' form_fields = ['name'] The entered Name is then saved in the variable self.player.name. -
django - how to download uploaded files through a link
I am uploading a file and saving it on a folder outside the media folder. I want to add a download link in a template to be able to download the file directly. i am not sure what to add in the url,if i shoud add something i tried this in the template it says url not found <a href="{{data.tar_gif.url}}"> Download File</a> views.py def uploaddata(request): if request.user.is_authenticated: if request.method == 'POST': form = uploadform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('file_list') else: form = uploadmetaform() return render(request, 'uploaddata.html', { 'form': form }) else: return render(request, 'home.html') html page <tbody> {% for data in dataset %} <tr> <td>{{data.path_id}}</td> <td>{{ data.tar_gif }}</td> <td> <a href="{{data.document.url}}"> Download File</a> </td> </tr> {% endfor %} </tbody> -
How to change the AJAX - Views workflow in terms of url mapping
I have a working AJAX function and a working views function (to make API calls). But I don't get them work together. I guess that something is wrong with my web applications workflow / sequence of actions. So now the problem is as follows: When i visit http://127.0.0.1:8000/ everything shows up as intended and the team_id gets assigned correctly to the javascript variable when i click any team in the sidebar. When i visit http://127.0.0.1:8000/dashboard/ I get a TypeError, because the views function doesn't know about the required team_id for the API call (because so far nobody selected a team). Thus, the API return is a empty dic which ends up in a TypeError and the page doesn't render. The goal is that a user lands on http://127.0.0.1:8000/dashboard/ and clicks different teams in the sidebar without a page_refresh to update the dashboard accordingly to the fetched data. But to be able to select a team at all, he needs a rendered frontend.. Currently I have the following url mapping structure: from dasocc_app import views from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^$', views.render_landing_page, name='landing_page'), url(r'admin/', admin.site.urls), url(r'about/', views.render_about), url(r'dashboard/', views.team_update, name='team'), url(r'dasocc_app/', include('dasocc_app.urls')) ] This … -
Why migration is not working after pulling from git?
I'm working collaboratively with some members on a Django project. They're working on Windows whereas I'm working on Ubuntu. My problem is, every time I pulled from git and apply python manage.py migrate, and suggest me to enter python manage.py makemigrations --merge. Followed by the suggestion,entered python manage.py migrate, But it showed the following errors: django.db.utils.ProgrammingError: column "first_name" of relation "account_appuser" does not exist django.db.utils.ProgrammingError: column "login_id_id" of relation "account_appuser" does not exist For 1st error, from the migrations file, I delete those addfield operations and for 2nd error,from the migrations file, I delete removefield operations Now, I have to check every migrations file where this kind of problem occurred. On the other hand, other team member didn't face such kind of problem, they only apply python manage.py makemigrations --merge and python manage.py migrate. Is this happening because of different Operating systems? and any alternative solution for this problem. I am new on this site, So please help me by suggestion.Thanks -
Docker Image `httpd` with libapache2-mod-wsgi-py3
I'm currently creating a Dockerfile with a base image httpd:2 And I manually installed libapache2-mod-wsgi-py3 is there a way I can use mod-wsgi for my Django Application on another container? -
creating custom middleware not working in django?
Here I am trying to update user's last time visit by using the custom middleware. But this is not working.It is not updating the last_visit time in the database. What am i doing wrong here ? models.py class Staff(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='staff') name = models.CharField(max_length=255, blank=True, null=True) last_visit = models.DateTimeField(default=now(), blank=True) views.py class CheckUserLastVisitMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: Staff.objects.filter(pk=request.user.pk).update(last_visit=now()) response = self.get_response(request) return response settings.py MIDDLEWARE = [ 'organization.views.CheckUserLastVisitMiddleware', -
Isn't the html of the form Django displays on the screen?
Django shows you forms when you do basic coding, right? Where is the html of the automatically generated form in windows? So instead of looking for a template folder, once the developer writes the url or views code, he finds the location of the skeleton-only html that Django shows. In my opinion, it looks like it's built somewhere like an "anaconda/envs" contains a separate virtual environment, but I can't find it. Please help. Thank you for reading. work hard. End. nothing. unneccessary. it's maybe path? -
Manipulate Django ManyToManyField() according to category selected in the same model
I have these two models, first having category and second having size related to particular category class MasterCategory(models.Model): category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class MasterSizes(models.Model): category_name = models.ForeignKey(MasterCategory,on_delete=models.CASCADE) category_size = models.CharField(max_length=2) def __str__(self): return self.category_size This is product model where I want to fetch sizes related to selcted category AND let user select multiple sizes at a time. class Product(models.Model): category_name = models.ForeignKey(MasterCategory,on_delete=models.CASCADE) # subcategory_name = models. product_brand = models.CharField(max_length=50) product_title = models.CharField(max_length=50) product_summary = models.CharField(max_length=200) product_description = models.TextField() original_price = models.FloatField() # discount_rate =models.IntegerField(null=True, blank=True) related_size = MasterSizes.objects.filter(category_name=category_name) available_sizes = models.ManyToManyField(related_size,related_name='category_sizes') discount_price = models.FloatField() product_image = models.ImageField() product_size = models.ForeignKey(MasterSizes, on_delete=models.CASCADE) favourite = models.BooleanField(default=False) def __str__(self): return self.product_title How do I filter the ManyToManyField() with the selected category related sizes only ** Right Now** It shows all the sizes in available_sizes But I want to get sizes only related to category selected. -
sending mail before 3 days of the end date and should display those details in html page
sending mail before 3 days of the end date and should display those details in html page .for example if the end_date is 05/10/2019 then i need all details of the promotion of date 02/10/2019 in html page def index1(request): dests = promotion.objects.filter(end_date=date.today()) print(dests) return render(request, 'proindex.html', {'dests': dests}) def email(request): dests = promotion.objects.all() for j in dests: date = j.end_date - datetime.timedelta(days=3) if date == date.today(): print(j.email) print("sent") email_sen = j.email email_user = '@gmail.com' server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(email_user, 'password') message = 'hello' server.sendmail(email_user, email_sen, message) return HttpResponse('Mail sent successfully') -
Design django Relation to save data easily later
I have 2 csv's according to which I have to design database. first one is And my 2nd csv is And My django model code till now is class Restaurant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(null=True, upload_to='Restaurant') RestaurantName = models.CharField(max_length=50, null=False, blank=False) Location = models.TextField(max_length=100, null=False) Logo = models.ImageField(null=True, upload_to='Logo') NumberOfTables=models.IntegerField(default=0) Availability=models.CharField(max_length=100 , choices=Availability_CHOICES ) def __str__(self): return str(self.RestaurantName) class Ingredient(models.Model): restaurant = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255, unique=True) def __str__(self): return str(self.name) class Categories(models.Model): restaurant = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255, unique=True) def __str__(self): return str(self.name) class ArticlesOptionsChoices(models.Model): articleoption = models.ForeignKey(User, on_delete=models.CASCADE) optionname = models.CharField(max_length=255) choice = models.CharField(max_length=255) def __str__(self): try: return str('optionname={0}, choice={1}'.format(self.optionname, self.choice)) except: return str(self.optionname) class ArticlesOptions(models.Model): restaurant = models.ForeignKey(User, on_delete=models.CASCADE) name = models.ManyToManyField(ArticlesOptionsChoices,max_length=255) min = models.IntegerField() max = models.IntegerField() choice=models.ForeignKey(ArticlesOptionsChoices, on_delete=models.CASCADE , related_name='user_choice_option') choice_price=models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return str(self.name) class Articles(models.Model): restaurant = models.ForeignKey(User, on_delete=models.CASCADE) articlename = models.CharField(max_length=50, null=False, blank=False) price = models.DecimalField(max_digits=10, decimal_places=2) category = models.ForeignKey(Categories, on_delete=models.CASCADE) pickuptax = models.FloatField(null=True, blank=True, default=None) dineintax=models.FloatField(null=True, blank=True, default=None) description = models.CharField(max_length=500, null=False) ingredient = models.ManyToManyField(Ingredient) #done articleoption = models.ForeignKey(ArticlesOptions , on_delete=models.CASCADE) def __str__(self): return str(self.articlename) I am assuming a restaurant as a User. So Real issue is now how I will manage Article Options into first … -
Unable to import Modules in Python for Django Oscar
I have installed Django AND Oscar by running the commands in given order: virtualenv eshop_env eshop_env/Scripts/Activate pip install django-oscar django-admin.py startproject eshop cd eshop manage.py migrate The settings.py file in eshop directory has these two lines a the top: import os from oscar.default import * The os module is importe without any error. However, there is a red wavy line under from. I am using Visual Studio Code. When I hover over the line, it says unable to import oscar.default. The same error appears on all my import statement involving django and oscar. This also results in the follwing error in Command line after i run the migrate command: ModuleNotFoundError: No module named 'oscar.default' I tried running pip install oscar.default pip install oscar but both of them show an error. However, I was able to successfully run the pip install django-oscar command again. But, he error about the module does not change. What am I doing wrong? This is my project directory structure: D:\Python Websites\Example\eshop\ D:\Python Websites\Example\eshop_env\ D:\Python Websites\Example\eshop\manage.py D:\Python Websites\Example\eshop\eshop\settings.py, urls.py etc. The import error occurs with all other modules as well: from django.apps import apps from django.urls import include, path # > Django-2.0 from django.contrib import admin from … -
How do I set user access in django [duplicate]
This question already has an answer here: How to restrict access to pages based on user type in Django 4 answers I would like to ask the idea/way to have two different user access in django. For example, the admin is able to view all the pages. But if user of the system should only be able to view 1 page out of 4 pages. I have no idea how to start to implement this. -
How can I use Ajax to trigger views.py function?
Whenever a user selects a team within the sidebar of my dashboard, the corresponding team_id is assigned to a variable (that works). Now I would like the dashboard to update accordingly by fetching the new dashboard data for the selected team via an API (that works as well, but not for the assigned team_id). Where I run into issues is to use the assigned variable team_id for the API requests. The application is built on Django, hence I use view functions to fetch the API data. Now the key questions is, how to use the team_id variable for the API requests to get the correct data in return (replacing the id '72' in below example with the js variable)? Furthermore, do I then need to use a success function for Ajax additionally to the views function that will render the frontend? This is my code so far: views.py def team_update(request): response = requests.get('http://www.api-football.com/demo/api/v2/teams/team/72') team_data = response.json() teams = team_data.get('api', {}).get('teams', []) if teams and len(teams) == 1: teams = teams[0] return render(request, 'index.html', { 'name': teams['name'], 'country': teams['country'], 'founded': teams['founded'], 'logo': teams['logo'], 'venue_capacity': teams['venue_capacity'], }) js: $('ul.subbar li a').on('click', function(e) { // Start function when user clicks on a team … -
How to create a model instance object in Django without a form
New to django here. I am following this documentation link to create an instance of a model https://docs.djangoproject.com/en/2.2/ref/models/instances/#creating-objects and I am missing something. Here is my code #models.py class Book(models.Model): title = models.CharField(max_length=100) @classmethod def create(cls, title): print('print title:') print(title) book = cls(title=title) # do something with the book return book #forms.py book = Book.create("Pride and Prejudice") print('printing DJANGO--------------') print(book) #console output print title: Pride and Prejudice printing DJANGO-------------- Book object (None) I have literally copied the code from the tutorial and haven't changed a thing. What am I doing wrong? Thanks -
No known parent package
I made an app called calc in the project wolverine. I tried this code on urls page of calc app from django.urls import path from . import views urlspattern = [ path('',views.home, name= 'home')] Then I got an ImportError File "c:\Users\Anmol\projects\wolverine\calc\urls.py", line 3, in from . import views ImportError: attempted relative import with no known parent package -
string formatting in Html
I am creating a template in HTML {% for product in products %} <tr> <td>{{ product.id }}</td> <td>{{ product.product_name }}</td> {% for i in quantities %} {% if forloop.counter == forloop.parentloop.counter %} <td id="q1">{{ i }}</td> {% endif %} {% endfor %} {% endfor %} How can I assign a different id to each item in quantities? Can I use .format just like we do in python? -
Self not defined?
I have a login view that checks if login users are either a client or pilot and redirect them appropriately but i keep getting self not defined error. Any help will be appreciated. views.py def signin (request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request,user) messages.success(request, 'You are now logged in') if user.role == 'client': def ef (self): return redirect(reverse('dashboard', kwargs={"pk": self.pk})) else: return redirect(reverse('pilot_dashboard', kwargs={"pk": self.pk})) else: messages.error(request, 'Invalid Credentials') return redirect ('login') else: return render (request, 'accounts/signin.html') -
Django or Spring. Which is better for a system analyzing huge data?
I have to develop a system for data analysis and showing the report. Size of data is huge and increasing continuously. Data analytics and Machine learning algorithm will be used. Which framework will be better for me ? DJango or Spring ? -
how to create a validation on detailview class?
i'm trying to show the Post Details only for the User who wrote this post this is view class PostDetailView(PermissionRequiredMixin,DetailView): model = Post this is the form class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content'] my model class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) how can i check on my view if the user is the one who wrote the post ?