Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
saving multiple images with different dimensions from a single ImageField in django models
How can I save multiple images with dimensions(eg: 10x10, 20x20, 30x30) into the "/media/" folder using a single models.ImageField() in django models? Thanks, Nitesh -
How to adapt java POJO generator for Django model with custom methods?
I am done with this tutorial which shows how to use textX to write a java POJO. I am thinking of adapting this to write Django model classes. The issue is when I have to add custom model methods to the Django model class. And then if I subsequently change the DSL, the generated model class will definitely remove the custom model methods. How to I cater for custom model methods if using textX to generate Django model classes? -
how to select html id which is assigned to Django variable in java script
I have an ID in html. This id is assigned to Django variable which contain ads ID. I want to add this ads ID to favorite list using local storage (cookies). Now, this ID is inside a loop and for every single ads will take different ID. The question is how to select the specific ID when the user click on that specific ID icons. Here is my code: {% for item in result %} <span id="favouriteBtn" style="color:#ccc" title="add this post to favorite list"> &#9734; </span> {% endfor %} THE ID SHOULD BE THIS WAY: id={{item.id}} Here is portion of javascript function: $('#favouriteBtn').click(function(){ currentAddFav(); I want to set the ID as : id={{item.id}} and be able to select specific id which has been clicked by the user. How can i do that? -
What is the best way to generate PDF from HTML (in bulk) and download all in zip file using Python(Django) or JavaScript?
For my site, I am looking for a solution that convert dynamic HTML pages to PDF. Actually, I've multiple reports to generate form HTML and I want it to be done on server-side and to be done in background(if possible), after that all the reports are downloaded in a single compressed file where all the reports are generated separately according to the template(HTML). -
Django Admin: How to Access to Logged-in User for Using It in Custom 'list_display' Field?
I want to create a hyperlink (custom field in display_list) and I have to use logged-in User's id as a part of query parameters in the link. Is there any solution for this? -
Android studio - Localhost connection File not found?
So I have been trying to make an authentication feature on my app where the users can login. I am trying to send JSON objects to my Django REST API so tha my users can get tokens. However, whenever after I press login with a valid user's credentials (me), my logcat throws a file not found exception to http://192.168.0.18:8000/token-auth/ even if I can access it in my browser. I am running my Django REST API through XAMPP in my macbook pro. My Android emulator is running in my Desktop. I was able to similar thing with my ReactJS app in my macbook pro where I can retrieve data from my Django REST API. I already placed <uses-permission android:name="android.permission.INTERNET" /> in my manifest.xml and it took care of my permission issue. Below are my codes: login.java public class Login extends AppCompatActivity { Button LoginButton; EditText uUserName, uPassWord; WSAdapter.SendAPIRequests AuthHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn); LoginButton = (Button) findViewById(R.id.LoginButton); uUserName = (EditText) findViewById(R.id.LoginUserBox); uPassWord = (EditText) findViewById(R.id.LoginPassBox); //AuthHelper = new WSAdapter().new SendDeviceDetails(); // Moves user to the main page after validation LoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // gets the username and … -
Social account adapter for allauth not working
I am trying to implement my own social adapter for AllAuth. However, it seems as if it doesn't recognize the adapter. I checked this by calling a print statement within the adapter class, but it does not execute. Here's what I have in my settings.py: SOCIALACCOUNT_ADAPTER = 'oauth.adapters.SocialAccountAdapter' Inside, oauth is a file named adapters and inside this file is a class called SocialAccountAdapter and looks like this: class SocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): if sociallogin.is_existing: return if 'email' not in sociallogin.account.extra_data: return try: email = sociallogin.account.extra_data['email'].lower() email_address = EmailAddress.objects.get(email__iexact=email) except EmailAddress.DoesNotExist: return account = User.objects.get(email=email).socialaccount_set.first() messages.error(request, "A " + account.provider.capitalize() + " account already exists associated to " + email_address.email + ". Log in with that instead, and connect your " + sociallogin.account.provider.capitalize() + " account through your profile page to link them together.") raise ImmediateHttpResponse(redirect('/accounts/login')) I have an email that I signed up with no social sign up, let's call it example@example.com Afterwards, I try to sign up with Facebook which also uses example@example.com as its email. I get an error that looks like this: DoesNotExist at /facebook/login/callback/ User matching query does not exist. Why doesn't my adapter work? -
Want to connect mongodb docker service with my django application
I want to create two docker services one is mongodb service another one is web service build using django. And i need that web-service (django app) which need to be connected to that mongodb docker service. but i dont know how to connect with mongodb docker service in my django application which is also a service running in a same docker swarm .`This is my docker-compose.yml: version: '3' services: mongo: image: mongo:latest command: mongod --storageEngine wiredTiger ports: - "27017:27017" restart: always environment: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: example web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" links: - mongo depends_on: - mongo Here i tried with mongoengine in settings.py of django application but failed MONGO_DATABASE_NAME = "reg_task21" MONGO_HOST = "mongo" mongoengine.connect(db=MONGO_DATABASE_NAME, host=MONGO_HOST,port=27017) -
Custom Attributes in Form Django
I want to add some custom attributes to field company_monthly_payment. My Generic View class CompanyCreateView(LoginRequiredMixin, generic.CreateView): model = Company fields = ['company_name', 'company_monthly_payment'] Custom Attribute before and after input field company_monthly_payment <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text">$</span> </div> <input type="text" class="form-control" aria-label="Amount (to the nearest dollar)"> <div class="input-group-append"> <span class="input-group-text">.00</span> </div> </div> Even i want to add aria-label to input field. Even i dont want to hardcore html code inside template -
Navbar Active won't change when clicking to another page
Navbar is being buggy. I wish to have the activate tab change as a user goes through the different pages. I am using a base template so I don't want to reproduce the navbar html/css for every single page so I believe javascript is the answer to my issue here. I've attempted to use some Jquery from another question, it unfortunately created a separate problem, I am not well versed with Jquery so I found it very difficult to fix the issue. This is the HTML <div class="container-fluid"> <a class="navbar-brand" href="#"><img src="{% static 'images/sidespacer.png' %}"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"><a class="nav-link" href="/Spaces">Home</a></li> <li class="nav-item"><a class="nav-link" href="/Spaces/space">Spaces</a></li> <li class="nav-item"><a class="nav-link" href="/Spaces/pricing">Prices</a></li> <li class="nav-item"><a class="nav-link" href="/Spaces/howitworks">How it Works</a></li> <li class="nav-item"><a class="nav-link" href="#">Contact</a></li> {% if user.is_authenticated %} <li class="nav-item"><a class="nav-link" href="{% url 'logout' %}">Log out {{user.username}}</a></li> {% else %} <li class="nav-item"><a class="nav-link" href="{% url 'signup' %}">Sign Up</a></li> <li class="nav-item"><a class="nav-link" href="{% url 'login' %}">Login</a></li> {% endif %} </ul> </div> </div> </nav> This is the current Jquery $(document).ready(function() { $( ".nav-item" ).bind( "click", function(event) { event.preventDefault(); var clickedItem = $( this ); $( ".nav-item" ).each( function() { $( this ).removeClass( "active" … -
user profile system data base design with multiple users and a admin dashboard
i'm new to database design.i want to design a data base for a notes taking app which has a user profile system with multiple users and a admin dashboard who keeps track of all users.help me creating a schema design for this data base for these and also for login ,sign up and i'm trying to design a notes taking app and consider there are future version requirements like sharing the notes and notifying a user if a notes is shared with him and the user should be able to manage his profile with in the system -
Django 2.1 unable to detect my new models during makemigrations
I've been searching on how to fix this. These are the things that i tried before posting this question. Unfortunately none of them worked. Added the app name (myapp) in setting's INSTALLED_APPS list, it Didn't work. Tried adding just the app name, but it didn't work as well. So now I'm using the full dotted path (myapp.settings.MyappConfig) just to be safe. Deleted __pycache__/*.pyc When I run $ python manage.py showmigrations, i can see that "myapp" is recognized but there's no migration. I've placed all my models in a folder to organize it. See my folder structure below. What am I missing here? This is so frustrating, please help me. Thanks in advance! mysite |__myapp | |__ models | | |__ project.py | | | |___apps.py | |__mysite |__ settings.py -
NameError at /Signup/ name 'all_users' is not defined
from django.http import HttpResponse from .models import signUp from django .template import loader def index(request): template = loader.get_template("Signup/signup.html") context = { 'all_users': all_users, } return HttpResponse(template.render(context, request)) -
Model-First approach options in Python ORMs(and Code-First)
I have a project that contains work with complex excel file(bank balance sheet), db and web interface. Naturally I would like to design diagram visually to autogenerate sql(Model-First approach in Entity framework), but I was rather surprised and frustrated not to find design surface options in python ORMs. Is it the case and I left with Code-First option only? That will take a lot of time and effort in my case. I will need to visualise my data structure anyway somehow(at least on paper). In my case it's all about fast development and proof of consept. If Django orm and SQLalchemy lack design surface(I hope I'm wrong), what do Python programmers do usually in my case? If they always start with classes that's ok(maybe), but please let me know, because I need to know for sure that Model-first is not used in Python, so my stupid anxiety will go away. -
Should a shopping cart id be tied to a user id?
I want to create a shopping cart app that is tied to the user id. Mainly because if the user logs out, the items in the cart won't be deleted. This is my first Django project so I'm not 100% sure if this is a good idea as the tutorials I'm following all use sessions for the carts, so it would be great if someone could give me some feedback. Here is my models.py: from django.db import models from django.conf import settings from menulistapp.models import menulist User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request): try: cart_obj = Cart.objects.get(id=request.user.id) new_obj = False except Cart.DoesNotExist: new_obj = True cart_obj = Cart.objects.create(user=request.user) cart_obj.id = request.user.id return cart_obj class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ManyToManyField(menulist, blank=True) total = models.DecimalField(default=0.0, max_digits=10, decimal_places=1) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) Here's my views: def cart_home(request): template = "cartapp/home.html" cart_id = request.user.id cart_obj = Cart.objects.new_or_get(request) context = { "x": request.user, } return render(request, template, context) -
The QuerySet value for an exact lookup must be limited to one result using slicing
I am trying to generate a queryset using one to many rlationship via foreign key.I am trying to obtain profile instance from current logged in user, then getting profile following, after than, i will extract post as well as comment. The associating models are:- #models.py from django.contrib.auth.models import User #this is how profile of a sample user, say MAX looks like class Profile(models.Model): Follwers=models.IntegerField(default='0') user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) bio=models.TextField(max_length=120,blank=True) location=models.CharField(max_length=30,blank=True) birth_date=models.DateField(null=True,blank=True) verified=models.BooleanField(default=False) ProfilePic=models.ImageField(upload_to='UserAvatar',blank=True,null=True) def __str__(self): return self.user.username @receiver(post_save,sender=User) def update_user_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class FollowingProfiles(models.Model): Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) ProfileName=models.CharField(max_length=120,blank=True,null=True) def __str__(self): return self.ProfileName class post(models.Model): Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) Picture=models.ImageField(upload_to='PostMedia',blank=True,null=True) DatePosted=models.DateTimeField(default=timezone.now) Content=models.TextField(blank=True,null=True) def __str__(self): return self.Profile.user.username class comment(models.Model): post=models.ForeignKey(post,on_delete=models.CASCADE) Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) Content=models.CharField(max_length=120,null=False,blank=False,default='it is sapora') def __str__(self): return self.Profile.user.username #views.py def feed(request): if request.user.is_authenticated: profile=Profile.objects.filter(user=request.user) userfollowing=FollowingProfiles.objects.filter(Profile=profile) for following in userfollowing: username=following.ProfileName useraccount=User.objects.filter(username=username) mprofile=Profile.objects.filter(user=useraccount) Post=post.objects.filter(Profile=mprofile) comment=comment.objects.filter(post=Post) final_post_queryset=final_post_queryset+Post final_comment_queryset=final_comment_queryset+comment return render(request,'feed/feed.html',{'final_comment_queryset':final_comment_queryset,'final_post_queryset':final_post_queryset}) else: return redirect('signup') It produces following error:- The QuerySet value for an exact lookup must be limited to one result using slicing. -
Django : SQLite Database is Locked when I build like feature on my home page
I am implementing Like functionality in Web application. Idea is Simple to List number of Post(Blogs) on Home page and Add a Like Button to each post(Blog). It works fine when I build it with normal <form action='{% url target %}' method='POST'> But when I implemented this with AJAX call It only allows me to like or dislike a particular post(blog) a single time.i.e One I liked a Post for first time it works, also when I dislike the same Post It works fine, But when I again Like that Post it throws an django.db.utils.OperationalError: database is locked like_section.html <form id="like-form{{ post.id }}"> {% csrf_token %} <button type="submit" id="{{ post.id }}btn" name="like" value="{{ post.id }}" class="btn upvote">Like</button> <script type="text/javascript"> {% for like in post.likes.all %} {% if like != user %} dislikingPost("{{ post.id }}btn"); {% else %} likingPost("{{ post.id }}btn"); {% endif %} {% endfor %} $(document).ready(function(event){ $(document).on('click', '#{{ post.id }}btn', function(event){ event.preventDefault(); pk = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url "like_post" %}', data: { 'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, success:function(response){ $('#like-form{{ post.id }}').html(response['form']) // $('#{{ post.id }}btn').style.color = 'green'; }, error: function(er, e){ console.log(er.responseText); } }); }); }); </script> </form> views.py: def like_post(request): all_posts = Posts.objects.all() … -
I want to learn Anaconda (Python) + Django, Database web development using Oracle DB
I have installed Python 3.7 using Anaconda 2018.12 and Django, want to learn Database Web Development using Oracle DB ( 11g and/or 12c ), please help where I can found the references/resource guidance/tutorials etc. which guide step-by-step from setup/configure onward. also recommend an IDE. regards -
Django Remove Login Alert Message AllAuth
I am using AllAuth with Django to make a logjn form. The issue is that I am trying to remove the error message in my login form that spawns from the form|crispy field, so that it only appears using the code at the bottom outside the form. Is this possible? Login.HTML <form class="login" method="POST" action="{% url 'account_login' %}" style="list-style-type: none;"> {% csrf_token %} {{ form|crispy }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button class="primaryAction btn btn-primary shadow mt-2" style="width: 100%;" type="submit">{% trans "Sign In" %}</button> </form> // Added Error Message to Custom location {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="container-fluid messages moveInTop"> <div class="alert alert-error alert-danger card"> {{ error|escape }} </div> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="container-fluid messages moveInTop" style="width: 28rem; z-index: 100; position: fixed; bottom: 10%; opacity: .95; left: 60.2%;"> <div class="alert alert-error alert-danger messages card"> {{ error|escape }} </div> </div> {% endfor %} {% endif %} -
Django AJAX returns undefined instead of the variables
So I have a simple Django script which I've found online for an AJAX function that runs a Python script and gets the output via stdout. views.py from django.shortcuts import render def index(request): return render(request,'homepage/page.html') homepage/page.html <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>test</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript"> $(function() { $('#clickme').click(function(){ alert('Im going to start processing'); $.ajax({ url: "static/homepage/js/external_func.py", type: "POST", datatype:"json", data: {'key':'value','key2':'value2'}, success: function(response){ console.log(response.keys); console.log(response.message); } }); }); }); </script> </head> <body> <button id="clickme"> click me </button> </body> </html> So you can see my url is linked to external_func.py which runs after the button is clicked. The script then returns a json. external_func.py import sys import json import cgi fs = cgi.FieldStorage() sys.stdout.write("Content-Type: application/json") sys.stdout.write("\n") sys.stdout.write("\n") result = {} result['success'] = True result['message'] = "The command Completed Successfully" result['keys'] = ",".join(fs.keys()) d = {} for k in fs.keys(): d[k] = fs.getvalue(k) result['data'] = d sys.stdout.write(json.dumps(result, indent=1)) sys.stdout.write("\n") sys.stdout.close() However, when I run the server and clicked on the button, the console shows undefined for both values, meaning response.keys and response.message is undefined. Now, when I instead switch the code to console.log(response) in homepage/page.html. The console prints out the entire external_func.py code in text. I couldn't find a solution … -
Django-Auth-LDAP with MemberUid
I am trying to configure django-auth-ldap to work with a very old LDAP schema that I have inherited. I am running into 2 issues with querying for LDAP groups. First, my LDAP schema uses the memberUid attribute rather than member attribute. Second, my LDAP schema has an uppercase OU that seems to be tripping-up django-auth-ldap. My django-auth-ldap setup is fairly straightforward, mostly taken directly from the official documentation. Here are a few significant lines. Note the uppercase 'G' in my OU. AUTH_LDAP_GROUP_SEARCH = LDAPSearch('ou=Group,dc=school,dc=edu', ldap.SCOPE_SUBTREE,'(objectClass=groupOfNames)',) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr='cn') AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_staff":"cn=org-staff,ou=Group,dc=school,dc=edu" } Here is a snipper of my ldap dump. cn: cn=org-staff,ou=Group,dc=school,dc=edu objectClass: posixGroup objectClass: top cn: org-staff gidNumber: 999 memberUid: someuser And here is a particularly telling line from my syslog. Dec 27 22:56:47 server slapd[45950]: conn=1467 op=4 CMP dn="cn=org-staff,ou=group,dc=school,dc=edu" attr="member" Dec 27 22:56:47 server slapd[45950]: conn=1467 op=4 RESULT tag=111 err=16 text= LDAP error 16 is LDAP_NO_SUCH_ATTRIBUTE, which makes sense in this case given that the query is looking for the member attribute but my group does not have any such attribute. The second issue here is that for some reason the 'G' in my OU is not capitalized in the query. Is there any way to make … -
Is Django framework vulnerable to local file inclusion(LFI) and remote file inclusion(RFI)?
Like in php, include() method and allow_url_include can be vulnerable to lfi and rfi Does django's include is vulnerable to lfi and rfi? -
Overriding settings in Django when used by the models
We are using Django for Speedy Net and Speedy Match (currently Django 1.11.17, we can't upgrade to a newer version of Django because of one of our requirements, django-modeltranslation). Some of our settings are used by the models. For example: class USER_SETTINGS(object): MIN_USERNAME_LENGTH = 6 MAX_USERNAME_LENGTH = 40 MIN_SLUG_LENGTH = 6 MAX_SLUG_LENGTH = 200 # Users can register from age 0 to 180, but can't be kept on the site after age 250. MIN_AGE_ALLOWED_IN_MODEL = 0 # In years. MAX_AGE_ALLOWED_IN_MODEL = 250 # In years. MIN_AGE_ALLOWED_IN_FORMS = 0 # In years. MAX_AGE_ALLOWED_IN_FORMS = 180 # In years. MIN_PASSWORD_LENGTH = 8 MAX_PASSWORD_LENGTH = 120 MAX_NUMBER_OF_FRIENDS_ALLOWED = 800 PASSWORD_VALIDATORS = [ { 'NAME': 'speedy.core.accounts.validators.PasswordMinLengthValidator', }, { 'NAME': 'speedy.core.accounts.validators.PasswordMaxLengthValidator', }, ] (which is defined in https://github.com/speedy-net/speedy-net/blob/uri_merge_with_master_2018-12-26_a/speedy/net/settings/global_settings.py). And then in the models I use: from django.conf import settings as django_settings class User(ValidateUserPasswordMixin, PermissionsMixin, Entity, AbstractBaseUser): settings = django_settings.USER_SETTINGS (and then use attributes of settings, such as settings.MIN_SLUG_LENGTH, in the class). The problem is, when I try to override such settings in tests (you can see my question & answer on Can I define classes in Django settings, and how can I override such settings in tests?), User.settings remains the same and is not overridden … -
How to remove "something ptr": when I render form with formset_factory?
When I render the site at the end of each form appear the string "Human ptr:"... how can I delete it? (Human is class where Player derives from) I have a form made with modelformset_factory rendered like this: team_area.html {% extends 'base_layout.html' %} {% block content %} <h1>Area Squadra</h1> <form method="post" action=""> {% csrf_token %} {{ player_formset.management_form }} {% for player_form in player_formset %} {% for field in player_form %} {{ field.label_tag }} {{ field }} {% endfor %} <br> {% endfor %} <input type="submit" value="Aggiorna"> </form> {% endblock %} And the view is managed by: views.py from django.shortcuts import render, redirect from skeleton.models import Player from django.contrib.auth.decorators import login_required from .forms import PlayerForm from django.forms import modelformset_factory from django.http import HttpResponseNotFound # Create your views here. @login_required(login_url="/accounts/login/") def team_area(request): if request.user.team != None: PlayerFormSet = modelformset_factory(Player, form=PlayerForm, extra=1, can_delete=True,) if request.method == "POST": player_formset = PlayerFormSet( request.POST, request.FILES, queryset=Player.objects.all().filter(team=request.user.team),) for player_form in player_formset: if player_form.is_valid(): player = player_form.save(commit=False) player.team = request.user.team #if player.first_name != '' and player.last_name != '': # player.save() if player_formset.is_valid(): player_formset.save() return redirect('team_area:home') else: player_formset = PlayerFormSet(queryset=Player.objects.all().filter(team=request.user.team)) return render(request, 'team_area/team_area.html', {'player_formset': player_formset}) else: return render(request, 'team_area/empty_page.html') I expect to remove Human ptr: possibly without css or … -
problem with customize code samples in api documentation
I am trying to add swift code samples to the auto-generated api documentation in my django-rest-framework project. The docs say I must subclass DocumentationRenderer and add the languages I want as well as create the templates for them. But it does not tell me what to do with the subclassed Renderer. from rest_framework.renderers import DocumentationRenderer class CustomRenderer(DocumentationRenderer): languages = ['ruby', 'go'] So I created "CustomRenderer" in my file under core/serializers.py great, now what? Where do I reference this class so I can actually apply it? https://www.django-rest-framework.org/topics/documenting-your-api/#customising-code-samples