Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Two dependent conditions in exclude DJANGO
I want to check whether the current user already has the same movie id in his personal list or not. If he has it then I want to exclude that movie from my trending list. I want it to be something like this. views.py trending = list(Movies.objects.exclude(mid in mymovies WHERE uid = request.user.id)) -
Django "No Patterns" / Circular Import Error
I've scoured all of the issues I can find about this error and tried all of the solutions, yet none (save one; more on that later) worked for me. Every time I start up my app, I get the following error: django.core.exceptions.ImproperlyConfigured: The included URLconf 'gamerank.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I've checked my files for circular imports, and cannot find any at all. voting/urls.py only imports voting/views.py voting/views.py imports voting/models.py, voting/helpers.py, and voting/forms.py voting/models.py imports from libraries only voting/helpers.py imports from libraries only voting/forms.py imports from voting/models.py (which does not import from voting/forms.py) This answer works for me, but I cannot access any of my application after that (because I just commented out the routes), so it's not really a solution in my case. Here are some of my files: voting/urls.py from django.urls import path from . import views app_name = 'voting' urlpatterns = [ path('', views.index, name="index"), # auth routes path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register") ] gamerank/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', … -
Is it possible to map all static files or url routes of a website?
I want to make a few static files available in my server, but I don't want people to access it unless they know the exact URL. This is meant to work like a game, solve a puzzle and move to the next phase by finding out the URL. Surely there are several similar games in the web. What I'm worried is if someone could just avoid the puzzle by "mapping" all the static files in a server. Is that possible? [Assuming the puzzle solution would lead to a static file served] I would like to extend the same question for URL routes, is it possible to discover all the url routes of a website? For example I have mysite.com and mysite.com/hidden/solution.html if there are no links to the second URL, can someone get this information? [Except bruteforcing] I'm hosting this page using AWS lightsail (django and apache). Is there something I can/need to do in the django/apache side to prevent this? -
Pycharm Django CSS not updating after adding git repo
I am creating a website and I was designing it without a repository set up originally. Now, I have it in a git repo and suddenly, when I try to refresh the page (with dev tools open and cache disabled) my CSS and HTML changes have no affect. I have to stop the server, close the webpage, then re-run the server and open it again to see changes. Anyone experienced this? Not sure what gives. -
inserting to SqlLite takes too long by django
hello i have 26 file (each ~100MB) i try to inserting by this view : def index(request): url = '../xaa' count = 0 line_num = 1660792 start = time.time() for lines in fileinput.input([url]): user = ast.literal_eval(lines) T.objects.create(a=user['a'], b=user['b'], c=user['c']) count += 1 percent = (100 * count) / line_num print(f"{percent}%") end = time.time() print(f"Time : {end - start}%") response = HttpResponse('Done') return response but it's take too long (3.5 day for a file) how can i do it faster ? -
Django Forms: field_order fails to work in forms.py
My field_order variable fails to correctly set the order. I'm trying to reorganize the form so that the bottom two fields are at the top of the form, as illustrated here: Here is my class from forms.py. I set the field_order in class Meta, but it doesn't re-arrange my form and I don't know why? I do not get any errors when I run my code either. class changeLockForm(forms.Form): def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(changeLockForm, self).__init__(*args, **kwargs) self.fields['roomLoc'] = forms.ModelChoiceField(queryset=Models.Room.objects.filter(owner=None) | Models.Room.objects.filter(owner=user), label='Room Location') self.fields['lockName'] = forms.ModelChoiceField(queryset=Models.Lock.objects.filter(owner=None) | Models.Lock.objects.filter(owner=user), label="Current Lock Name") newNameBool = forms.BooleanField(required=False, label='Change Name? Y/N',) newLockName = forms.CharField(required=False, min_length=2, max_length=20, label='New Lock Name', disabled=True) state = forms.BooleanField(required=False, label='LOCKED/UNLOCKED') code1 = forms.IntegerField(initial=1000, min_value=1000, max_value=9999, label='First Code') code2 = forms.IntegerField(initial=1000, min_value=1000, max_value=9999, label='Second Code') code3 = forms.IntegerField(initial=1000, min_value=1000, max_value=9999, label='Third Code') code4 = forms.IntegerField(initial=1000, min_value=1000, max_value=9999, label='Fourth Code') class Meta: model = Models.Lock fields = ['lockName','newNameBool','newLockName','roomLoc', 'state', 'code1', 'code2', 'code3', 'code4'] field_order = ['lockName', 'newNameBool', 'newLockName', 'roomLoc', 'state', 'code1', 'code2', 'code3', 'code4'] -
Heroku How to use django 1.11
this question have been asked, but my question is different. File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/admin/widgets.py", line 151 '%s=%s' % (k, v) for k, v in params.items(), I can solve this problem in my computer , but i don't know how to solve it on heroku django version:1.11 python:3.8.9 -
Django: Using the django-admin-sortable2 to manually order ManyToManyFields
models.py class Photo(models.Model): ... class Meta: ordering = ['id'] class Album(models.Model): title = models.CharField(max_length=100) photos = models.ManyToManyField(Photo,related_name="photos",blank=True) published = models.BooleanField(default=False) class Meta: ordering = ['title'] class AlbumToPhoto(models.Model): album = models.ForeignKey(Album,related_name="album_order",blank=True,on_delete=models.PROTECT) photo = models.ForeignKey(Photo,related_name="photos_order",blank=True,on_delete=models.PROTECT) photo_order = models.PositiveIntegerField(default=0) class Meta: ordering = ('photo_order',) admin.py from django.contrib import admin from adminsortable2.admin import SortableInlineAdminMixin from .models import Photo, Album class PhotoInline(SortableInlineAdminMixin, admin.TabularInline): # We don't use the Button model but rather the juction model specified on Panel. model = Album.photos.through # Register your models here. class PhotoAdmin(admin.ModelAdmin): list_display = ("title","index") class AlbumAdmin(admin.ModelAdmin): list_display = ("title","published") filter_horizontal = ("photos",) inlines = (PhotoInline,) admin.site.register(Photo, PhotoAdmin) admin.site.register(Album, AlbumAdmin) I have downloaded the package, django-admin-sortable2, and I followed this in their docs. However, I have this error: Model photos.models.Album_photos requires a list or tuple 'ordering' in its Meta class I am confused because both have Meta classes. Is it an error on my part or on theirs? Should I switch packages? -
RetrieveAPIView responding 404 - django rest
My RetrieveUpdateDestroyView keeps responding me with a list of objects from it's model serializer. And when I try to change the url, it keeps giving me a 404 error. I've already tried everything, don't know what is happening. This is my view.py class PersonListCreateAPIView(generics.ListCreateAPIView): serializer_class = PersonSerializer lookup_field = 'uuid' def perform_create(self, serializer): serializer.save(contact_of=self.request.user.get_team) def get_queryset(self): ''' This view should return a list of all the Person objects for the currently authenticated user team. ''' user = self.request.user return Person.objects.filter(contact_of=user.get_team) class PersonRetrieveUpdateDestroyAPIView(generics.RetrieveAPIView): serializer_class = PersonSerializer lookup_field = 'uuid' def get_queryset(self): user = self.request.user return Person.objects.filter(contact_of=user.get_team) This is my urls.py app_name = 'people' urlpatterns = [ # api/people/<uuid> path( route='<uuid:uuid>/', view=PersonRetrieveUpdateDestroyAPIView.as_view(), name='retrieve_update_destroy', ), # api/people/ path( route='', view=PersonListCreateAPIView.as_view(), name='list_create', ), ] Any help? -
Reading whitespace in heading of csv file using pandas
I need to read the heading from csv that have white between them, I need help to fix it. I try differnet way like delimiter = ' ' and delim_whitespace = True. Here is how I'm write the code: df = pd.read_csv( d, dtype = 'str', usecols=[ 'Owner First Name', 'Owner Last Name', 'StreetNumber', 'StreetName', 'State', 'Zip Code', 'Bdrms', 'Legal Description', 'Sq Ftg', 'Address', 'Orig Ln Amt', 'Prop Value' ], names=[ 'Owner_FirstName', 'Owner_LastName', 'StreetNumber', 'StreetName', 'State', 'ZipCode', 'Bdrms', 'Legal_Description', 'Sq_Ftg', 'Address', 'Orig_Ln_Amt', 'Prop_Value' ], skipinitialspace=True ) -
Passing an additional field through a model form without adding it to the model
I'm trying to figure out how to add a field to a model form without adding the field to the model itself. I just need to pass in this extra field to the view it returns. My django project has a page where the user uploads a text file which gets saved to the DB (the file upload form is the model form). It then returns a page where the important content from the text file is displayed. I want to add a dropdown on the same page as the file upload form that allows the user to select an option for how the content should be displayed when it returns the next page. I don't want this dropdown to be part of the model for the text file as I don't need to save it to the db. I'm having trouble figuring out how to pass this option into the view without adding it to the model itself. Upload form: <form method="POST" enctype="multipart/form-data" id="text-upload-form"> {% csrf_token %} {{ form.as_p }} <label for="display-type">Display type</label> <select id="display-type" name="display-type" form="text-upload-form"> <option value="highlighted">Highlighted display</option> <option value="dark">Dark display</option> </select> <button type="submit" class="save btn btn-default">Save</button> Views.py def parser(request): if request.method =='POST': text_upload = TextFileForm(request.POST, request.FILES) … -
Django user delete privilege role
Is possible to give roles/group to admin users to delete only the users they created? For example: admin1 created user1, user2 admin2 created user3, user4 admin1 should only have permissions to delete user1 and user2 and not have any access to user3 and user4. -
Django and jQuery: jQuery not working, but receiving no errors
I cannot figure out why my jQuery script isn't working. I've read through a bunch of stackOverflows but haven't been able to fix this issue. I have a form, and when a checkbox is checked, I want to enable a form field with the id div_id_newLockName. If the checkbox is unchecked, I want the form field to be disabled and greyed out. The checkbox has id div_id_newNameBool I have written code that I think should work, but it doesn't. I'm not receiving any errors though, which makes troubleshooting difficult. I'm hoping a second set of eyes can help. A picture of what the form looks like can be found here: In this picture, the "change name?" checkbox corresponds with div_id_newNameBool, and the "Lock Name" char field is what I want to toggle enable or disable. base.html (contains jQuery script) <!doctype html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <style> <!-- unimportant css stuff --> </style> <body class="w3-content" style="max-width:1200px"> <!-- !PAGE CONTENT! --> {% block content %}{% endblock %} <!-- End page content --> </div> <script> $(document).ready(function(){ if ($("#div_id_newNameBool").is(':checked')){ $("#div_id_newLockName").prop("disabled", false); } else { $("#div_id_newLockName").prop("disabled", true); alert("DISABLED"); } }); </script> </body> </html> HTML page for form {% extends "homepg/base.html" %} {% load crispy_forms_tags … -
How to get reference to object in django-restframework APIView
I am trying to fill a chart.js chart with historical values from my database of a Team object. Currently I have a regular django view which loads the template of the team, and a specific django rest-framework APIView that returns json response for the chart's labels and data, which sits inside of the template rendered by the initial django view. I need reference to the current team to be accessible in the APIView, but not sure how to do that. urls.py: path('team/<slug:slug>/', views.team_view, name='team_view'), path('teamChart', views.TeamChartData.as_view()), views.py: def team_view(request, slug): user = request.user team = Team.objects.get(slug=slug) ... return render(request=request, template_name='team_view.html', context={'team':team, 'form':form, 'userTeam': userTeam}) class TeamChartData(APIView): # authenticate user authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def get(self,request, format=None, *args, **kwargs): labels = ['hi'] chartLabel = "" chartdata = [1] data ={ "labels":labels, "chartLabel":chartLabel, "chartdata":chartdata, 'user':request.user.username, } return Response(data) teamChart.js var endpoint = '/teamChart'; $.ajax({ method: "GET", url: endpoint, success: function(data) { drawLineGraph(data, 'teamChart'); console.log("drawing"); }, error: function(error_data) { console.log(error_data); } }) function drawLineGraph(data, id) { .... } I've got the chart working for a user's account, but in the APIView I can reference the user from the request being made. I can't access the specific team page from that … -
Adding textarea in formset - django
I have a message form and a formset that includes questions for this message. I would like to add textareas in the form, instead of input field. - I am not sure why there are not many examples out there. The models looks like this: class Message(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) message_title = models.CharField(blank=True, null=True, max_length=255) message_introduction = models.TextField() def __str__(self): return self.message_title class Meta: db_table = 'messages' and: class Message_question(models.Model): message = models.ForeignKey(Message, related_name="message_questions", on_delete=models.CASCADE) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) message_question = models.TextField() def __str__(self): return self.message_question class Meta: db_table = 'message_questions' And the forms look like this: class MessageForm(forms.ModelForm): class Meta: model = Message fields = [ 'message_title', 'message_introduction', ] labels = { 'message_title': 'message_title', 'message_introduction': 'message_introduction', } widgets = {'created_at': forms.HiddenInput(),'updated_at': forms.HiddenInput()} class Message_questionForm(forms.ModelForm): class Meta: model = Message_question fields = ['message_question', ] widgets = { 'message_question': forms.TextInput(attrs={'class': 'formset-field', 'rows': 4}), } Is it doable and if yes, what element of the above code shoudl I change please ? -
Choose the correct option. ValidationError Django python
how to change validation from pk to name field in input forms? models class Service(models.Model): name = models.CharField(max_length=150, db_index=True, unique=True) def __str__(self): return self.name forms class SettingDeviceAddForm(forms.ModelForm): class Meta: model = Device fields = ['name'] that is, in the form, you need to enter a name and check the name field, and I enter the name, and the check goes along the pk field. how to change the default pk field to name html form -
I have a TypeError (Object … is not JSON serializable) when I try to set a session value (Django). Why?
I have this strange TypeError raised : "Object of type Product is not JSON serializable" when I try to set a session value in a view (in basket app). The error occurs with request.session['Hello'] = 'foo'. However, this error does not occur elsewhere. For instance, in store app, in views.py, the following request.session['Hello World'] = 'Alloy' works very well. Do you know why ? Basket app / views.py (it bugs) from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from . basket import Basket from store.models import Product from discount.forms import UserDiscountForm def basket_summary(request): basket = Basket(request) context = {'basket':basket} request.session['Hello'] = 'foo' return render(request,"store/basket_summary.html",context) store app / views.py (it works well) from django.shortcuts import get_object_or_404, render from requests.sessions import session from .models import Category, Product def home(request): print('----------// HOME PAGE //----------') request.session['Hello World'] = 'Alloy' context = {} return render(request, 'store/home.html', context) Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/basket/ Django Version: 3.2 Python Version: 3.9.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store', 'account', 'basket', 'orders', 'payment', 'contact', 'address', 'discount', 'shipping'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Utilisateur\Documents\Environments\monoi_django_virtualenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Utilisateur\Documents\Environments\monoi_django_virtualenv\lib\site-packages\django\utils\deprecation.py", line … -
Django check if superuser in class-based view
I am converting my project from function-based view to class-based view. In a view function, I can check if a user is a superuser using request.user.is_superuser() function. I can check if a user is logged in by inheriting LoginRequiredMixin in a View class, I want to know if there is any similar way that can be used for checking if the user is a superuser in a View class. I want a Django app only accessible by the superusers of the site. -
Embeding videos in a a Django project?
Using Django-embed-video 1.4.0, we can easily embed YouTube videos into Django projects. However it doesn't seem to work if the video is from any source but YouTube. The embed video code is different for every website and whenever I enter a code from a site like TikTok, CNN, or Facebook, it says "URL could not be recognized." YouTube Video CNN Video Is there a way to modify the URL so that Django-embed-video recognizes the URL? Or is there another way to create a django website that can show embedded videos from a source other then youtube? models.py from django.db import models # Create your models here. from embed_video.fields import EmbedVideoField class Item(models.Model): video = EmbedVideoField() -
HTML checkbox prepended to textbox and their sizes
Here my HTML code <div class="input-group mb3"> <div class="input-group-prepend"> <div class="input-group-text"> {% if item.complete == True %} <input type="checkbox", value="clicked", name="c{{item.id}}" checked> {% else %} <input type="checkbox", value="clicked", name="c{{item.id}}"> {% endif %} </div> </div> <input type="text" value="{{item.text}}" class="form-control"> </div> I prepended checkboxes before the textboxes, yet their sizes is not same as you see. Do I have to change their height(maybe width) values in order to make them equal or do I miss something else? By the way I am using CSS(I am a newbie to HTML, do not be harsh please :D ). Could it be relevant with that or it' s sources? Thanks! -
RadioSelect field not proper shown
I put RadioSelect field to my form and in Chromium my choices are in the left side of form not like labels and other fields in center, how can I fix it? Please any sygesstions. In FF it's looks also different, it's positioned to the left side. template {% extends 'school/index.html' %} {% load crispy_forms_tags %} {% load crispy_forms_field %} {% block content %} <form method="post" align='center' autocomplete="off" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btnSubmit">submit</button> </form> {% endblock %} form.py from django import forms from django.contrib.auth.models import User from django.core.validators import MinLengthValidator from django.utils.translation import gettext_lazy as _ class UserSignUpForm(forms.ModelForm): who = forms.ChoiceField( choices=[('student', 'Student'), ('teacher', 'Teacher')], required=True, widget=forms.RadioSelect(attrs={'style':'max-width: 20em; margin:auto; padding:300;', 'autocomplete':'off'}) ) password = forms.CharField( label="Password", validators=[MinLengthValidator(8, message="Minimum 8 characters")], widget=forms.PasswordInput(attrs={'style':'max-width: 20em; margin:auto', 'autocomplete':'off'})) confirm_password = forms.CharField( label="Confirm password", validators=[MinLengthValidator(8, message="Minimum 8 characters"), ], widget=forms.PasswordInput(attrs={'style':'max-width: 20em; margin:auto', 'autocomplete':'off'})) class Meta: model = User fields = ('who', "username", 'first_name', 'last_name', "password", ) help_texts = {"username": None} widgets = { 'username': forms.TextInput(attrs={'style':'max-width: 20em; margin:auto'}), 'first_name': forms.TextInput(attrs={'style':'max-width: 20em; margin:auto'}), 'last_name': forms.TextInput(attrs={'style':'max-width: 20em; margin:auto'}), } def clean(self): cleaned_data = super(UserSignUpForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: msg = _(f'Password and confirm password does not … -
I can't seek videos with django channels
I have a website and I could seek the videos but after I set up Django channels the videos don't seek, and I tried to solve this problem so I figured out when the server run with Starting ASGI/Channels the videos didn't do that, I have just one question Is this problem will continue with production or not? My asgi.p import os import django from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'site.settings') django.setup() application = get_asgi_application() -
How to upload geojson file in django postgresql
I would like to import a geojson file (Edge) in my postgresql database. I have a form for uploading the file. My problem is how to handle foreigns keys network, target, source and roadtype. Source and target must be Node instance. the file will be download inside the network page(pk). models.py class Edge(models.Model): param1 = models.FloatField(null=True, blank=True) param2 = models.FloatField(null=True, blank=True) param3 = models.FloatField(null=True, blank=True) speed = models.FloatField(null=True) length = models.FloatField(null=False) lanes = models.SmallIntegerField(null=True) geometry = models.LineStringField(null=True) name = models.CharField('Edge Name', max_length=200, blank=False) road_type = models.ForeignKey(RoadType, related_name='edges_road_type', on_delete=models.CASCADE) target = models.ForeignKey(Node, related_name='edges_target',on_delete=models.CASCADE) source = models.ForeignKey(Node, related_name='edges_source',on_delete=models.CASCADE) network = models.ForeignKey(RoadNetWork, related_name='edges_network', on_delete=models.CASCADE) my geojson file is like that { "type": "FeatureCollection", "features": [{ "type": "Feature", "properties": { "id": 1, "name": "Out 1 - E", "lanes": 1, "length": 4.0, "speed": 50.0, "source": 1, "target": 2, "param1": 3000.0, "road_type": 2 }, I try this.It's too slow. Could you please help me def upload_edge(request, pk): template = "networks/edge.html" network = RoadNetWork.objects.get(id=pk) if request.method == 'POST': form = EdgeForm(request.POST, request.FILES) if form.is_valid(): datafile = request.FILES['my_file'] objects = json.load(datafile) for object in objects['features']: objet_type = object['geometry']['type'] if objet_type == 'LineString': properties = object['properties'] geometry = object['geometry'] point1 = geometry['coordinates'][0] point2 = geometry['coordinates'][1] location = GEOSGeometry( LineString(geometry['coordinates'])) … -
How to change default page in paginator?
I changed default page like this (For this example I hardcored the number 3 as logic which I have in this function does not affect paginator) def test(request): paginator = Paginator(objects, 2) num = 3 page = paginator.get_page(number=num) return render(request,'personal.html', {'page':page,'paginator':paginator}) But now I can't go on other pages, it always returns page number 3. Is it possible to correct? Here is paginator {% if page.has_other_pages %} <nav> <ul class="pagination"> {% if page.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page.previous_page_number }}">&laquo; Previous</a> </li> {% else %} <li class="page-item disabled"> <span class="page-link">&laquo; Previous</span> </li> {% endif %} {% for i in page.paginator.page_range %} {% if page.number == i %} <li class="page-item active"> <span class="page-link">{{ i }} <span class="sr-only">(current)</span> </span> </li> {% else %} <li class="page-item"> <a class="page-link" href="?page={{ i }}">{{ i }}</a> </li> {% endif %} {% endfor %} {% if page.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ page.next_page_number }}">Next &raquo;</a> </li> {% else %} <li class="page-item disabled"> <span class="page-link">Next &raquo;</span> </li> {% endif %} </ul> </nav> {% endif %} And in another html I call it ... {% include 'paginator.html' with items=page paginator=paginator%} ... -
Display images manually that user has uploaded yet Python
How I display all the images manually that user has uploaded yet in Django show that I can create a Profile gallery