Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Website creation, should I use existing services?
I have some experience with website creation in Django and Wordpress. And I would like to make my first website and deploy it to a webserver. I prefer creating a site from zero, so I know what is where and what should I edit to make changes and so on. So I prefer Django over Wordpress, because I have not so deep-image of the site movements and I'm not very good in php. But when I look at people that knows Django, or other frameworks and despite it their sites are created in Wordpress, I'm little bit confused. Is it because Wordpress is fine-tuned by professionals and makes all that security stuffs for you, so it easier or why? -
Django: forms how to safe gaurd hidden fields from any malicious user modifying
I want to have a form with hidden field and whose value will be initialized. forms.py class SampleForm(forms.Form): email = forms.EmailField(widget=forms.HiddenInput()) otp = forms.CharField(widget=forms.HiddenInput(),help_text='Please Enter valid OTP sent to your Email', label='Otp', max_length=6) in the views.py form= SampleForm(initial={'email': someemail} I want to have email as hidden. When the form is submitted, i will need the email so that i can verify the otp sent to mail and otp entered by user. I heard that some malicious user try to modify the hidden field it when you don't want them to. So what is the best way to save from such situations. -
Django model_mommy model instance isn't saved in Ajax test
I'm trying to test an django ajax view that saves a field. Here's the test: def test_ajax_save_draft(self): sub = mommy.make(QuestSubmission, quest=self.quest2) draft_comment = "Test draft comment" # Send some draft data via the ajax view, which should save it. ajax_data = { 'comment': draft_comment, 'submission_id': sub.id, } self.client.post( reverse('quests:ajax_save_draft'), data=ajax_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest', ) self.assertEqual(draft_comment, sub.draft_text) # sub.draft_text = None, as if the ajax view was never called! And here's the view: @login_required def ajax_save_draft(request): if request.is_ajax() and request.POST: submission_comment = request.POST.get('comment') submission_id = request.POST.get('submission_id') sub = get_object_or_404(QuestSubmission, pk=submission_id) sub.draft_text = submission_comment sub.save() response_data = {} response_data['result'] = 'Draft saved' return HttpResponse( json.dumps(response_data), content_type="application/json" ) else: raise Http404 When I run the test, I get into the if block, and it can retrieve the comment and submission object, but when it returns to the test at the end, it's like it never happened. What am I doing wrong here? -
Django drf_yasg swagger - apiview - how to define POST input param
I am trying to using drf_yasg - swagger to achieve this kind of call: curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json' --header 'X-CSRFToken: sM48rRw0j1YHB2mMA9L7c7QPkwBfikHqA3TlNRg2lWtVdO23IHtzgOUjIOoPcZPf' -d 'username=testingdata&password=mypassword' 'http://localhost:8000/api/another' I have attempted this way, but noticed its a query param not a POST input param. x_param = openapi.Parameter('x', openapi.IN_QUERY, description="x param", type=openapi.TYPE_STRING) @swagger_auto_schema(method='post', manual_parameters=[x_param]) @api_view(['POST']) def another_view(request): x_param = request.POST['x'] logging.debug("x_param = %s", x_param) return Response("I'm OK", status=status.HTTP_200_OK) I believe it should be something to change in this value openapi.IN_QUERY. The question is how to create an API using the following apiview method with drf_yasg to create POST input parameters ? -
django how to redirect url after remove item from cart redirect url
this is my url where I want to redirect after post : path('edit/<int:blerje_id>/produkti/add/', views.add_choice, name="add_choice"), url remove: path('clear/<int:prod_id>/', views.clear, name='clear'), this is my view: def clear(request,prod_id): prod= get_object_or_404(Prod, id=prod_id) prod.delete() return redirect('polls:add_choice', blerje_id=blerje.pk) name 'blerje' is not defined -
TypeError: __init__() missing 1 required positional argument: 'on_delete' (Django Filer, Python3, Django 2)
I need to add the required argument: "on_delete = models.CASCADE" to the following code. Otherwise, I get the following TypeError: TypeError: init() missing 1 required positional argument: 'on_delete'. How and where should I do this? Any help is much appreciated. class FilerFileField(models.ForeignKey): default_form_class = AdminFileFormField default_model_class = File def __init__(self, **kwargs): # We hard-code the `to` argument for ForeignKey.__init__ dfl = get_model_label(self.default_model_class) if "to" in kwargs.keys(): # pragma: no cover old_to = get_model_label(kwargs.pop("to")) if old_to != dfl: msg = "%s can only be a ForeignKey to %s; %s passed" % ( self.__class__.__name__, dfl, old_to ) warnings.warn(msg, SyntaxWarning) kwargs['to'] = dfl super(FilerFileField, self).__init__(**kwargs) def formfield(self, **kwargs): # This is a fairly standard way to set up some defaults # while letting the caller override them. defaults = { 'form_class': self.default_form_class, } try: defaults['rel'] = self.remote_field except AttributeError: defaults['rel'] = self.rel defaults.update(kwargs) return super(FilerFileField, self).formfield(**defaults) -
drf-yasg - api_view post - query param - MultiValueDictKeyError
In drf-yasg, I am trying to achieve something simple that I have been doing in django-rest-swagger (now deprecated). x_param = openapi.Parameter('x', openapi.IN_QUERY, description="x param", type=openapi.TYPE_STRING) @swagger_auto_schema(method='post', manual_parameters=[x_param]) @api_view(['POST']) def another_view(request): x_param = request.POST['x'] logging.debug("x_param = %s", x_param) return Response("I'm OK", status=status.HTTP_200_OK) However, when I try to read the param with x_param = request.POST['x'] It causes this error: MultiValueDictKeyError at /another 'x' As I am migrating Django 1.11 -> 2.2, I'd like to stick to reading param this way (request.POST['x']). Firstly, I'd like to understand what is the problem reading the param and how to solve it. Secondly, if I can stick with request.POST['x'] and what modifications needs to be done for this (as I dont want to break any current API in this migration) By the way, I'ved seen this post, is there anyway to do similar for this issue. https://medium.com/@arjunsinghy96/customised-api-documentation-for-django-rest-framework-projects-using-drf-yasg-d6db9ba5cff3 -
How to create a http url for a json file?
I am an andrroid developer. I need to use some json files created using django in my app as database. For that I need to get a url. But the whole django is in another computer. How do I get a url to access the files on that computer from the android device? I get it that we need to be on the same network. But how? What kind of network? -
Django: Gzip and Whitenoise not compressing
I have a Django app with whitenoise for static files. But when I test the app with Google Lighthouse I get asked to enable text compression for my static .js and .css files. I read a lot of related posts but couldn´t find an answer. Settings MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', 'django_user_agents.middleware.UserAgentMiddleware', ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' When testing in Lighthouse, this files are requested to be compressed. They come from the Static folder and I understand they should be compressed when I run Manage.py collectstatic …css/bootstrap.min.css(afternoon-wildwood-39943.herokuapp.com) …js/jquery-3.2.1.min.js(afternoon-wildwood-39943.herokuapp.com) …js/bootstrap-table.min.js(afternoon-wildwood-39943.herokuapp.com) …css/Fran%20Style.css(afternoon-wildwood-39943.herokuapp.com) …js/popper.min.js(afternoon-wildwood-39943.herokuapp.com) Debug setting I read that maybe debug should be set to False to make it work. The example above was done with Debug = True. DEBUG = bool(os.environ.get('DJANGO_DEBUG', True)) The app works fine in this case, but if If turn debug to False, I get and error 500 page. I´m hosting in Heroku. You can try an example in: http://afternoon-wildwood-39943.herokuapp.com/website/ Any clues? Thanks in advance! -
Django: Where do define var (init or dispatch)
I want to add self.analytics which I can access from several other methods within the Class. Would you rather define that in dispatch as in the example or in the __init__? class Index(LoginRequiredMixin, TemplateView): template_name = 'admin/dashboard/index.html' def dispatch(self, *args, **kwargs): self.analytics = EventAnalytics(self.organizers) return super().dispatch(*args, **kwargs) -
Why does my asyncio code work sometimes but not others?
I am running this code every 5 minutes and sometimes it works and other times it does not work. I'm running it inside a django web app. I'm using the code to sync between an API and a database. Code loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) class Command(BaseCommand): help = 'Updates the local database with Unbelievabot status' token = settings.UNBELIEVABOT_TOKEN client = Client(token) guild = Guild(settings.GUILD_ID) # loop = asyncio.get_event_loop() #asyncio.get_event_loop() def sync_unby_with_grid(self): # Grab all users with a discord ID users_with_discord = SocialAccount.objects.filter(provider='discord').values('user_id', 'uid') # Filter out results against leaderboard with total if users_with_discord: discord_ids_with_balance = Unbelievabot_Leaderboard.objects.filter( user_id__in=[x['uid'] for x in users_with_discord]) # Build mapping to update each user for x in users_with_discord: for y in discord_ids_with_balance: if y.user_id == x['uid']: BankAccount.objects.filter(user=x['user_id']).update(unbelievabot_points=y.total) return def handle(self, *args, **options): board = loop.run_until_complete(Command.client.get_leaderboard(Command.guild)) board_json = asyncio.run(board) for r in board_json: Unbelievabot_Leaderboard.objects.update_or_create(user_id=r['user_id'], defaults={ 'rank': r['rank'], 'cash': r['cash'], 'bank': r['bank'], 'total': r['total'] }) self.sync_unby_with_grid() self.stdout.write(self.style.SUCCESS('Successfully Updated Database for "%s" accounts' % len(board_json))) Here is the traceback (unsuccessful run): {'user_id': '342424242', 'cash': 291674, 'bank': 0, 'total': 291674, 'found': True} self._body = await self.content.read() File "/home/user/.virtualenvs/thegrid_v1/lib/python3.7/site-packages/aiohttp/streams.py", line 359, in read block = await self.readany() File "/home/user/.virtualenvs/thegrid_v1/lib/python3.7/site-packages/aiohttp/streams.py", line 381, in readany await self._wait('readany') File "/home/user/.virtualenvs/thegrid_v1/lib/python3.7/site-packages/aiohttp/streams.py", line 296, in _wait … -
django how to redirect url after create post on the same edit post
This is my url where I want to redirect after post. path('edit//produkti/add/', views.add_choice, name="add_choice"), This is my view. def add_poll(request): if request.method == "POST": form = PollForm(request.POST) if form.is_valid(): new_blerje = form.save(commit=False) new_blerje.pub_date = datetime.datetime.now() new_blerje.owner = request.user new_blerje.save() messages.success( request, 'Fatura u krijua me sukses, kliko butonin me poshte per te shtuar produktet!', extra_tags='alert alert-success alert-dismissible fade show' ) return redirect('polls:edit',) else: form = PollForm() context = {'form': form} return render(request, 'polls/add_poll.html', context) -
Django REST Framework: DRY way to specify viewmodels
I would like to have a clear way for declaring a viewmodel for my Django REST endpoints, which the incoming requests must adhere to and which would take care of the validation. I mean something like viewmodels in Spring or other Java projects. The most primitive way is just to work with the request.data (or request.POST) dictionary-like object, but in this case all the validation is hardcoded to the view layer. A little better approach would be to use serializers, but using them is still quite verbose and in the end you get back a dict, unless you implement the .create() method witch makes the code even more verbose. Here is my current approach: class MyView(APIView): def post(self, request, format=None): serializer= MySerializer(data=request.data) serializer.is_valid(raise_exception=True) what_i_actually_need = serializer.validated_data ... return Response('Something') Is there a more DRY way to do it? -
how to use the django rest-auth views with custom html templates instead of browserable APIs
I am using django rest-auth and allauth for a login/logout and registration on my website. These are very easy to use and work well. however, the browseable APIs are ugly for production. I want to fully customize my login view but still have the underlying rest-auth logic in place. I was not able to find helpful tutorials on how to do this. I found this: https://wsvincent.com/django-user-authentication-tutorial-login-and-logout/ which is exactly what I want to do but with rest-auth rather than the build-in user authentication system that django offers. How can I do this? is there a default .html files that I can override? details this is my app's urls.py: urlpatterns = [ path('users/', include('users.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), ] the above have default views, I would like to overwrite their templates. -
Issue signing up new users in Django
I have the following signup flow in an app using Django 1.11- accounts/views.py: from .forms import UserForm def sign_up(request): if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): user = form.save() return redirect('index') else: form = UserForm() return render(request, 'signup.html', {'form': form}) accounts/forms.py: from django.forms import ModelForm from django.contrib.auth.models import User class UserForm(ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password'] It does appear to "register" a new user, in that it creates a new user in the database. The issue is I cannot login with that newly created user, the username/pw combo does not match. Going into the database I see the newly created users, but the password is in plain text: "password". But the first user I created through the command line, python manage.py createsuperuser has a salted hash as the password like pasdfhjasf8234jk324hgsdfa8df89asdf987 and I can login correctly using the password I made for it, ie "password". How do I save new users using my ModelForm where Django knows to correctly store the password as a salted hash? Thank you -
AttributeError: 'NoneType' object has no attribute 'Command'
I have upgraded django on my project, when i am running any command like "python manage.py runserver" It shows an error like "AttributeError: 'NoneType' object has no attribute 'Command'" Is there any issue in Django or In code?? Django Pro\Django_Project-master\Dpro> python manage.py migrate Traceback (most recent call last): File "manage.py", line 16, in execute_from_command_line(sys.argv) File "C:\Users\Ga\Django Pro\Django_Project-master\Dpro\env\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Ga\Django Pro\Django_Project-master\Dpro\env\lib\site-packages\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Ga\Django Pro\Django_Project-master\Dpro\env\lib\site-packages\django\core\management__init__.py", line 224, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\Ga\Django Pro\Django_Project-master\Dpro\env\lib\site-packages\django\core\management__init__.py", line 37, in load_command_class return module.Command() AttributeError: 'NoneType' object has no attribute 'Command' -
can I use restfull framework for Django to use api
I want to use tomtom web api for routing : https://developer.tomtom.com every time I search how to use an API with django I get the restfull framework isn't that for building an API? If I can use it to work with an existing API if yes I want to know how? Or the requests library for python would be enough? -
How to fix django-dynamic-formset with FormWizard not sending multiple forms data through POST
I'm currently trying to write an application in Django which is asking for multiple form inputs to create instances of a model; I'm trying to get information about a students grades. As typically the number of grades vary, I'm trying to use a dynamic form to allow the user to add as many fields as they need. As the form is spread across multiple pages due to its length (for other details, not related to the grades) I'm using a FormWizard solution to retain data across a session. The issue I'm getting is when I submit the form, all the data from the previous pages is sucessfully submitted, but only one of the forms is submitted on the grades page. I've tried various methods suggested on SO but cannot find an answer which works - if anyone can shed some light I'd greatly appreciate it! views.py: class SFFormWizard(SessionWizardView): template_name = "template.html" file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT,"docs")) def done(self, form_list, **kwargs): form_data = process_form_data(form_list) return render_to_response("done.html",{"form_data":form_data}) forms.py: GCSEGradeFormSet = modelformset_factory(GCSECourses, exclude=("student",),extra=1,can_delete=True) models.py: class GCSECourses(models.Model): CCHOICES = (("completed","Completed"),("predicted","Predicted")) GCHOICES = (("gcse","GCSE"),("alevel","A-Level")) class Meta: verbose_name = 'GCSE Courses Taken' verbose_name_plural = verbose_name name = models.ForeignKey(GCSESubject,verbose_name="Subject Name",on_delete=models.CASCADE) student = models.ForeignKey(Applicant,on_delete=models.CASCADE) grade = models.ForeignKey(GCSEGrade,on_delete=models.CASCADE) completed = models.CharField("Grade … -
why always error SyntaxError: 'return' outside function
i'm setting camera.py for my face recognition using python3, opencv and flask i have tried remove space or add space remove tabs, but always error. def get_frame(self): while True: # pdb.set_trace() success, img = self.video.read(1024) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) frame=vs.read() faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] ret, jpeg = cv2.imencode('.jpg', img) return jpeg.tobytes() i wanna fix it and no more error so i can stary my main.py without error, thanks :) -
How to set some meta attributes based on a class name in Django?
i want to streamline creation of identical views/filtersets/younameit in Django. At this point i have structures like this: class SerializerBase(serializers.HyperlinkedModelSerializer): class Meta: abstract = True fields = standard_fields extra_kwargs = { 'url': {'lookup_field': 'slug'}, } class TraitSerializerShort(SerializerBase): class Meta(SerializerBase.Meta): model = Trait What i want to do is make Meta take name of subclass, remove Serializer part and use that as model name. Is there any way to do that? It does not look that bad here, but filterset code becomes insanely big just coz everything is reiterated over and over again. -
Django React build files not found in Docker but it found without docker
I am learning docker and dockerizing my Django-react app! It is working now great except an issue and that is the bundle.js file are not getting Django when i run the project through dockcer But bundle.js files are found if run the project without docker! I guess, docker bundle the javascript in a different directory, that is why it is not getting if run with docker! this is my settings.py file STATICFILES_DIRS = [ os.path.join(os.path.join(BASE_DIR, os.pardir), 'dist'), ] and my Dockerfile is given below: FROM node:8 WORKDIR /app COPY . ./ RUN yarn RUN yarn build # Pull base image FROM python:3 # Set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory, we can name it whatever we want WORKDIR /djangobackend # Install dependencies # Copy requirement file from the docker workdir we defined named djangodocker COPY requirements.txt /djangobackend/ RUN pip install -r requirements.txt # Copy project COPY . /djangobackend/ and docker-compose.yml is given below: version: '3.2' services: db: image: postgres:10.1-alpine volumes: - postgres_data:/var/lib/postgresql/data/ web: build: . command: python /djangobackend/backend/manage.py runserver 0.0.0.0:8000 volumes: - .:/djangobackend ports: - 8000:8000 depends_on: - db volumes: postgres_data: Please know my problem carefully: If I run my app without docker like … -
Django list of objects doesn't render properly when using a form on the same page
I have developed a very simple Django app about music bands and their members (complete code: https://drive.google.com/file/d/1MwaC-_PchU6eBrwO01OaDivIF52S0L1D/view?usp=sharing). I used just the simple SQLlite3 database for my objects. I would appreciate help with rendering object lists when they need to be shown together with forms. They do render properly in templates that show just them, but not when a form is used on the same page with an object list. What I want is to display, say, a list of bands from the database in the middle column. It shows them properly when I render just that (i.e. when I click the Bands link). However, when I click Add band in the right-hand column and hope the list to remain in the middle column, it suddenly shrinks as if there were no Band objects in the database. In learning Django, I used the official Django tutorial, as well as the one provided by Mozilla (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website), but could not figure out what I'm doing wrong. The code below shows the relevant parts of the code. The link above takes you to the complete code (zipped), where the relevant HTML templates are included as well. I used Python 3.7, Django 2.2, and PyCharm … -
Django List Serializer bulk update failing with 'QuerySet' object has no attribute 'pk'
I am trying to do bulk update with ListSerializer in Viewset. My Bulk create works fine but not PUT. Here is my Serializer, ListSerizlier and my View. django=2.0.0 Serializer class SampleListSerializer(serializers.ListSerializer): pass class SampleSerializer(serializers.ModelSerializer): class Meta: list_serializer_class = SampleListSerializer model = Sample fields = ['id', 'name', 'last_name' ] Here is my ViewSet: class SampleViewSet(viewsets.ModelViewSet): serializer_class = SampleSerializer queryset = Sample.objects.all() def get_serializer(self, *args, **kwargs): if "data" in kwargs: data = kwargs["data"] # check if many is required if isinstance(data, list): kwargs["many"] = True return super(SampleViewSet, self).get_serializer(*args, **kwargs) def put(self, request): sorted(request.data, key=lambda o: o["id"]) instances = Sample.objects.filter(id__in=[o["id"] for o in request.data]).order_by("id") try: with transaction.atomic(): ss = SampleSerializer(data=request.data, instance=instances, many=True) if ss.is_valid(raise_exception=True): s = ss.save() return Response(ss.data) return Response(status=status.HTTP_400_BAD_REQUEST) except Exception as e: print(f"In exception {e}") return Response(status=status.HTTP_400_BAD_REQUEST) def create(self, request, *args, **kwargs): return super().create(request, *args, **kwargs) I am getting 'QuerySet' object has no attribute 'pk' at ss.is_valid(). Can someone suggest where my mistake is? or what's wrong? -
Django: how to view raw sql response upon a query
In Django if i want to see the raw sql in debug mode i can check using in django shell from django.db import connections User.objects.all() print(connections['default'].queries[-1]['sql']) Similarly can we see the raw response of that sql. Like In the above case the sql query may return the raw results in csv, tab delimited format. From then django may create the model objects array. -
How to trouble shoot the lag in the Django live server?
I have a small protein database. You can see the codes here. Say a user searches for their proteins of interests from the database. They can add the sequences to the cart. Also, they can upload their custom data to the database using session. If the user clear the session their custom data will be remove. The purpose is to do additional analysis in the database (say pairwise alignments). The problem is when a user want to clear session. After clearing the session still the html page shows the data. After ~60 seconds the session clears. I use anonymous sessions in the script. The database works perfectly well locally. I couldn't figure out where the problem is. I tried both SQLite3 as well as PostgreSQL for the database. Still the problem persists. """ Django settings for database project. Generated by 'django-admin startproject' using Django 2.2.5. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os, socket # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used …