Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django , unable to start on local:host
I am using dj4e in pythonanywhere.com , I am trying to start the project but it gives an error saying that port 8000 is already in use. I tried to run from another port but nothing. In dj4e's document, it says I cannot use "runserver" command in virtualenv. Could somebody help me running the local server, please? -
How to use External authentication in django app
I creating an app in which the authentication is done via web services of another app. But as I m trying to understand how things will work, I m trying to figure out how I can store each user data and posts to them if I m not using Django auth and then linking the models via forgien keys. -
How to check for string in list of dicts in jinja templating?
I have a modal inside of a Django app that opens with dynamic data. This data is a list of dicts, that has the form: [{"name": <name>, "ip": <ip>}]. One host at a time can be configured for special treatment, so there is a template variable elevated_host. I am trying to write a template where, if the elevated_host is in targets, I show a div, however I haven't been able to get it. Things I have tried: {% if elevated_host and elevated_host in targets|map(attribute='name') %} TemplateSyntaxError: Invalid filter: 'map' {% if elevated_host and elevated_host in [t.name for t in targets] %} TemplateSyntaxError: Could not parse the remainder: '[t.name' from '[t.name' I also tried writing and loading a custom filter but it always returned true. According to requirements.txt, we are using Jina2=2.7.2. How would I go about checking if this elevated_host string is in the name field of a list of dictionaries? -
Swapping the source of an image based on a boolean value
Here's my models: class Product(models.Model): title = models.CharField(max_length=120) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to='products') thumbnail = models.BooleanField(default=False) html template: {% if product.productimage_set.all %} {% for image in product.productimage_set.all %} {% if image.thumbnail %} <img src="{{ image.image.url }}"> {% endif %} {% endfor %} {% else %} <img src="image template when no image at all"> {% endif %} What I am trying to achieve is to use the image that has a "thumbnail" field equal to true by default, but if a Product have an image but none with "thumbnail" equal to true, it should use any image with foreign key that is matching this product, but if a product doesn't have any image then just use a template image. I have tried using {% else %} after checking if image is a thumbnail, but If a product have more than one image, then it would show them all. -
Why is text in django form validator not translated?
I import translation with from django.utils.translation import gettext as _ and have this Form definition class SearchSubstance(forms.Form): search_string = forms.CharField(max_length=100, validators=[validators.MinLengthValidator(4), too_much_compounds_validator]) with this custom validator def too_much_compounds_validator(query): raise ValidationError(_("translate this")) now the error message of MinLengthValidator is nicely translated (in Dutch) but somehow "translate this" is not translated. What am I doing wrong? -
django.db.utils.ProgrammingError: can't adapt type 'User' only in Postgres
I have this really odd error that I can't seem to figure out. I have solved how to fix it but it could be a weird error for others so I am posting anyways. I have this view function that allows users to invite team members to their team. @login_required def invite_team_member(request): if request.method == "POST": form = forms.InviteTeamMemberForm(request.POST, team=request.user.profile.team) if form.is_valid(): user = form.clean_username_or_email() try: models.TeamInvite.objects.create(from_user=request.user, to_user=user, team=request.user.profile.team) message = _("User successfully invited") except IntegrityError: message = _("This user has already been invited to your team") except ValidationError as e: if e.code == "team_full": message = _("Your team is full, no further users can be invited") else: raise e return render( request, "tracker/tracker_home/invite_team_member.html", {"invite_team_member_form": form, "message": message}, ) else: form = forms.InviteTeamMemberForm(team=request.user.profile.team) return render(request, "tracker/tracker_home/invite_team_member.html", {"invite_team_member_form": form}) Users enter a username or email into a form and the form determines whether it is valid to invite a user with that username or email. class InviteTeamMemberForm(forms.Form): username_or_email = forms.CharField(label=_("Username or Email")) def __init__(self, *args, **kwargs): self.team: models.Team = kwargs.pop("team") super().__init__(*args, **kwargs) def clean_username_or_email(self): data = self.cleaned_data["username_or_email"] try: user = User.objects.get(Q(username__iexact=data) | Q(email__iexact=data)) if user.profile.team == self.team: raise ValidationError(_("This user cannot be invited since they are already on this team")) return … -
Django: Get list item content from a list of hyperlinks
I'm stuck with a list of anchor tags and getting their content to views.py. Background: I have a input form for addresses. If the entered/submitted address is not specific as needed, for example because there are two cities with the same name, then I want to display a list of the potential addresses. Therefore, I have prepared a list of the potential target addresses also with an anchor tag. html page: <ul> <form action="{% url 'analytics' %}" method="GET"> {% for item in list_addresses %} <li><a href="{% url 'analytics' %}" name="pot_address" >{{ item.post_code }}</a></li> {% endfor %} </form> </ul> My urls.py: urlpatterns = [ path('', views.home, name = 'home'), path('/analytics', views.analytics, name = 'analytics'), ] Now I want to pass the address (content of the list item in html) to my views.py file. The views.py file looks like this: def analytics(request): if request.method == 'GET': pot_adress = request.GET['pot_address'] After having this address in views.py I want to use it to fetch specific data from a database. Could somebody help me with this issue? -
MIME type ('text/html') is not a supported stylesheet MIME type with react-django heroku deploy
I've been getting the error "MIME type ('text/html') is not a supported stylesheet MIME type" on my django+react deploy on Heroku. This is mostly because django can't find the staticfiles from react. Setting staticfiles dir in settings.py should have solved the problem, but it didn't: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'build/static'), ) -
Django-filter filtering Charfield with choices
Is there a way I can make Django-filter to filter condition with multiple check boxes instead of a drop down menu. What I would like is Django-filter to filter condition with multiple choices instead of just one. Is that possible? class Product(models.Model): options = ( ("Brand_new", "Brand New"), ("like_new", "Like New"), ("Used", "Used"), ("very_used", "Very New"), ("fair", "Fair Condition"), ) Owner = ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) category = ForeignKey( Category, blank=True, default=None, on_delete=models.CASCADE) subcategory = models.ForeignKey( SubCategory, related_name="product", unique=True, on_delete=models.CASCADE) Product_name = models.CharField(max_length=50, null=True, blank=True) Image = models.ImageField(max_length=50, null=True, blank=True, upload_to="users/") Short_des = models.CharField(max_length=50, null=True, blank=True) Description = models.TextField(max_length=500, null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) condition = models.CharField( choices=options, max_length=50, null=True, blank=True) in_stock = models.BooleanField(default=True) is_active = models.BooleanField(default=True) location = models.CharField(max_length=50, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) -
ModuleNotFoundError: No module named 'final_project'
I have been working on a django project and building a website. However, i found that my main useful directory was located deep within layers of other directories. I felt that i could simply cut the main project directory out and paste in the directory containing my .git folder. I did so and couldn't run the server with python manage.py runserver. So, I rolled back those changes with Ctrl+V and restructured the folders in old way. But now, i get the error: ModuleNotFoundError: No module named 'final_project' The funny thing here is i ran the sever within the final_project folder! Here is a snap of the problem: enter image description here enter image description here -
How do I go about something like this in Django? A random code sharing system to access certain features
Let’s say I want to generate random codes per session for users. These codes can be shared to other users of the web app, to establish some ability to interact with each other on the web app(maybe to access a particular feature , for example, an project assignment comparison feature for school). How best do I do this? Do I associate each user with this random code in the DB, and for every session, I replace that code? So if I send that code to a user, and the user uses that code to try & access some service, there’ll be an endpoint which checks to see if that code is in the DB and grants access to that service? Is there a better workaround? -
How to create and update a foreign key object in Django via Ajax
I have a model Poller and Vote with foreign key. Now in my template I render the VoteForm as follows: <form method="post" action="" id="vote-form"> {% csrf_token %} <div id="vote-choice-one" class="vote-choice-div"> {{ vote_form.poller_choice_one_vote.label }} {{ vote_form.poller_choice_one_vote }} </div> [...] </form> VoteForm class VoteForm(ModelForm): poller_choice_one_vote = forms.BooleanField(widget=forms.CheckboxInput(attrs={ 'required': False, 'hidden': True })) poller_choice_two_vote = forms.BooleanField(widget=forms.CheckboxInput(attrs={ 'required': False, 'hidden': True })) class Meta: model = Vote fields = ['poller_choice_one_vote', 'poller_choice_two_vote'] Now once the user clicks on the choice_one_vote field in the template I want ajax to update the database async. Now I'm stuck at processing the desired outcome via the view into the database. Also I am not quiet sure if this is the most straightforward approach especially in terms of rendering the form and using the ajax since I couldn't make it happen with $('#vote-choice-one').on('check' Ajax // AJAX for posting function create_vote() { console.log("create post is working!") // sanity check console.log($('#vote-choice-one').val()) $.ajax({ url : "submit-vote/", // the endpoint headers: {'X-CSRFToken': csrftoken}, // add csrf token type : "POST", // http method data : { vote : $('#vote-choice-one').val() }, // data sent with the post request // handle a successful response success : function(json) { console.log("success"); // another sanity check }, // handle … -
Why does the Variable give a TypeError but the Function does not?
Can someone explain why this code works: first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) def full_name(self): return self.first_name + ' ' + self.last_name def __str__(self): return self.full_name() But this code doesn't: first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) full_name = first_name + ' ' + last_name def __str__(self): return self.full_name Why does only one of with the without a function give me a TypeError? Don't they do the same thing? -
Is it okay to use models from one Django app in another?
folks. I have a simple Django project. There's an app that receives data, processes it, and stores it in a DB. Of course, I'd like to show this data. To me, it looks more like a separate Django app. But then comes the question: What should I do with models? It looks really stupid to copy it but at the same time, it's kinda wrong to use models from one app in another. -
I am having application error when launching my app from heroku , from the logs i found out it it is the Procfile
As i said above the Procfile is the problem Project name is Purchase_Site This is my Profile : web: gunicorn Purchase_Site.wsgi --log-file - The log says : ModuleNotFoundError: No module named 'Purchase_Site' The whole log : 2021-09-14T18:45:52.279255+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 67, in run 2021-09-14T18:45:52.279366+00:00 app[web.1]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() 2021-09-14T18:45:52.279390+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 231, in run 2021-09-14T18:45:52.279537+00:00 app[web.1]: super().run() 2021-09-14T18:45:52.279549+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 72, in run 2021-09-14T18:45:52.279657+00:00 app[web.1]: Arbiter(self).run() 2021-09-14T18:45:52.279669+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 229, in run 2021-09-14T18:45:52.279932+00:00 app[web.1]: self.halt(reason=inst.reason, exit_status=inst.exit_status) 2021-09-14T18:45:52.279947+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 342, in halt 2021-09-14T18:45:52.280193+00:00 app[web.1]: self.stop() 2021-09-14T18:45:52.280207+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 393, in stop 2021-09-14T18:45:52.281978+00:00 app[web.1]: time.sleep(0.1) 2021-09-14T18:45:52.281995+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 242, in handle_chld 2021-09-14T18:45:52.282177+00:00 app[web.1]: self.reap_workers() 2021-09-14T18:45:52.282191+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 525, in reap_workers 2021-09-14T18:45:52.282412+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2021-09-14T18:45:52.282485+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2021-09-14T18:45:52.424348+00:00 heroku[web.1]: Process exited with status 1 2021-09-14T18:45:52.471038+00:00 heroku[web.1]: State changed from starting to crashed 2021-09-14T18:45:57.000000+00:00 app[api]: Build succeeded 2021-09-14T18:46:08.354861+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=site-buy.herokuapp.com request_id=49f86d09-f07f-41f3-8eaf-2c73ebeb3bb6 fw d="116.68.86.78" dyno= connect= service= status=503 bytes= protocol=https 2021-09-14T19:00:04.000000+00:00 app[api]: Build started by user heygivemeahifi@gmail.com 2021-09-14T19:00:34.340351+00:00 app[api]: Release v17 created by user heygivemeahifi@gmail.com 2021-09-14T19:00:34.340351+00:00 app[api]: Deploy 17d90df9 by user heygivemeahifi@gmail.com 2021-09-14T19:00:34.577324+00:00 heroku[web.1]: State … -
How to run a function at regular intervals?
I have a DashboardData model. I get some info from this form and according to the given answers, I run a function by using form answers as parameters. I want to run this function like functions.myFunction(n_user, n_password, n_url, n_port, db_password) with user's DashboardData values every 15 minutes. How can I run a function with parameters How can I rerun it at regular intervals? This is my form model: class DashboardData(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True) # request.user n_username = models.CharField(max_length=250) n_password = models.CharField(max_length=250) n_url = models.CharField(max_length=250) n_port = models.IntegerField() period = models.CharField(max_length=250) db_password = models.CharField(max_length=250, null=True) And this is my function: class myFunction(): def __init__(self, n_user, n_password, n_url, n_port, db_password): self.zaman = datetime.now().strftime("%Y-%m-%d") self.location = a_url self.static_fields = {} self.index_name = "vulns-" + self.zaman self.download_all(n_user, n_password, n_url, n_port, db_password) self.send_it() I tried to use apscheduler app but I cannot run it. -
How to Feed User a Django Background Task Response
I created a web application using django that utilizes a FedEx API so that a user can create shipments through my website. The response of this FedEx API call is in xml format that contains a lot of data such as; was the request a success or failure, error messages, error codes, tracking number (if successful) etc. I am using django background tasks to make these API calls and once a process finishes I am unable to retrieve the response from the API call. I was thinking to maybe store the xml response in a file and feed it to the user but before I do that I wanted to find out if there is a better way. I also would like to know the best practice for API responses in general, like does the user need to see the entire response and if so how can I display it to them in the best way possible. -
Would Python and Django fit my needs for my first project?
This is my first post here. Been using this site for ages and you guys have always helped out! I'm sorry if I ask something that has been answered numerous times before but when I searched I couldn't find anything. THe thing is that I'm planning a personal project. I have 10 years of detailed personal financial data and want to build a app/web interface to view this data more visually. I'm also planning on uploading new data each month and would like to be able to analyze that data in an "Power BI"-manner. I'm doing this to develop my, currently basic, skills in the area. More or less as a hobby project. Was thinking that Python and Django would be a good fit for this project. Mostly since I have some (kinda little) experience using these. Can you guys advice me towards another language or am I able to pull this of using Python and Django? Feel free to comment anything I missed and need to edit. I'm still in the learning process :) Cheers! -
Proper way to write a python loop and if else
I have a check statement like - for k in data: for l in prevValues: if k['name'] == l: return Response(status=status.HTTP_400_BAD_REQUEST) else: serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) I know this is wrong, I want to first complete the check block then come out of it, and then, at last, execute the save statement. What may be the proper way of writing this? My code till if statement works fine. -
How to display images using their path in Django
I have created a image folder in static directory. It contain all images. The images path along with some other information is fetched from MYSQL database using python. Images folder with python function that will fetch data from database. Python fetches data from database and stores in dict. Here's example of data store in database Image path is stored in database as a string in charfield It gets passed to html which convert dict to javascript object. [The image contain 3 obj which stores data of products at 0,1 and 2 and it is added in a string literal stored in javascript variable][4] Error that is shown in console -
Cannot upload big image files to Django project
I'm a beginner trying to make my first Django project. I'm using ubuntu local server on Windows 10 (WSL), i set up basic web server Nginx -> Gunicorn -> Django. In my django app i have a custom user with profile photo: class MyUser(AbstractBaseUser, PermissionsMixin): .... profile_image = models.ImageField(upload_to='users/%Y/%m/%d/', null=True, blank=True) .... with project settings: MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') Using django admin site i can upload image, image successfully stores in image folder and shows up on user page, but only if image size is less than 70-80kB. If image size is bigger than that, every time when I'm trying to upload image using Django Admin Site or user form, web page gets stuck on loading, and after a moment i get message "127.0.0.1 didn’t send any data. ERR_EMPTY_RESPONSE", with no error message from the server. What am i doing wrong? -
Accessing token from jQuery Ajax call securely for TokenAuthentication DRF
I have gone through every forum, and I am not able to find an answer to this. I did find great examples of getting Token using the command line, but not from the jQuery Ajax call. My application (multi-user docker hosted) extensively uses jQuery Ajax call from separate .js files. During the development: I stored the generated token in the session (at the login), Then access the token from the session in : def get_context_data(self, **kwargs): for each view, and then stored at the template using a variable. Then use it when I do API calls using Ajax in the separate js files (below). $.ajax({ url: '/work/api-stream-item-process-vote/' + contentid + '/', contentType: 'application/json', cache: false, processData: false, headers: {'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val(), "Authorization": "Token " + token}, type:"PATCH", data: JSON.stringify({ 'key':key, 'sel_image':contentid, }), success: function(data){ consolemsg("Successfully updated the vote information!") //stream_reload_vote_info(key,contentid,data['total_rating'],data['voted']) }, error:function(xhr, errmsg, err){ show_message("An error occured! Please contact administrator for help!!!",ERROR) } }); Question: How do I securely accomplish this? Is there a full implementation of this using Django + Ajax I can refer to? -
How to force django test to create sqlite database in file (not in memory)
I've tried changing test database name: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', 'TEST': { 'NAME': BASE_DIR / 'mytestdatabase', }, } } I've also tried running test with: python manage.py test --keepdb Nothing works. It seems to keep working in memory. I need django to generate the sqlite file to search it using a DBMS like DBeaver and see what are my tests actually doing inside the DB. -
Django REST Framework: how to make a APIView/Serializer browserable?
Using serializers.HyperlinkedModelSerializer with viewsets.ModelViewSet works fine for CRUD, as described in the docs. Unfortunately this requires a Model which I don't have on the login endpoint. Relevant code snippets: # Serializer class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField(min_length=8, max_length=50) # View class Login(APIView): permission_classes = [permissions.AllowAny] def post(self, request: Request, *args, **kwargs): # Some logic using LoginSerializer # urls.py urlpatterns = [ path('v1/login', Login.as_view()) ] Any idea? Thanks in advance! -
Using filter in list
I am building a Blog App and I am trying to access first posts of all the users in last 2 days, So i am using solution for accessing first posts. when i use filter of last 2 days then the first post method is not working. So i thought "I should use filter in another query" models.py class BlogPost(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30, default='') body = models.CharField(max_length=30, default='') date = models.DateTimeField(auto_now_add=True) views.py def first_posts(request): time = timezone.now() - timedelta(days=2) posts = [user.blogpost_set.first() for user in User.objects.prefetch_related( 'blogpost_set')].filter(blogpost__date__gte=time) context = {'posts':posts} But it showed 'list' object has no attribute 'filter' I also tried using :- ALL_POSTS = [] for post in posts: ALL_POSTS.append(post).filter(post__date=time) But it showed 'NoneType' object has no attribute 'filter I will really appreciate your Help. Thank You