Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do you pass a variable that contains a 2D array from a python file into the django views file as a context for a specific view?
The time table displayed below will be stored in a 2D array in a variable called dayPlan: "return dayPlan" Now I need to access this variable within this the views file: the path for this file is: django_project-->blog-->views.py This is my import statement in my views file: from django_project.Outer_Code.TimeTable import timeTable This is where I am trying to access the timetable variable: variable accessing This is the structure of my files: Main directories Where the views file exists: Views file Where the variable I am trying to access exists: Variable location I have tried many different import statements in order to access the class which contains the variable 'dayPlan' so that I can use it in the website, but I keep getting this error: from django_project.Outer_Code.TimeTable import timeTable ModuleNotFoudError: No module named 'django.project.Outer_Code' Any help in fixing this error will be useful. -
Django debug toolbar not appearing when using with nginx server
I am using django debug toolbar in server. When i use virtualenv it shows the debug toolbar. But when using gunicorn and nginx, it doesn't show the debug toolbar. Is it because of reverse proxy? INTERNAL_IP=[my device ip address] and Debug=True. It works with virtualenv but not with nginx. -
Running Django server without IDE
I want to run my django server without running PyCharm or any other IDE. I've tried to run this using command 'python manage.py runserver' in projekt folder cmd which generated errors. Do I have to configure something to run server without IDE? -
How to create new log file for each new order in django?
I am developing a new eCommerce website using Django. I want to create a new log file for each new order so that I can track any error till payment confirmation. Is it possible to create a new log file for each new order?How can we do that? Please help me, guys. -
Unable to access Django development server from windows host machine
Im currently running Centos 8 on my virtual machine and I created a django application on this virtual machine. I am only able to access the Django application within the virtual machine by typing 127.0.0.1:8000 in the firefox search bar but this does not work on my windows host computer. -
Asynchronous tasks or Multiprocessing in Django
I have a function that accepts a request from a client. Based on the request, it makes a request to another API. Once the response is received, it finally returns a response to the client. class View(APIView): #receives request def post(self, request, pk, *args, **kwargs): makeRequest() #make request to other API #Do something after request ... #return response to client after response from API has been received return Response(status=status.HTTP_HTTP_200_OK) This approach has several issues as response time is made longer and any unpredictable activity from the API being consumed could further affect the response time. The solution in mind is receiving the request and having the function making the request run separately as a response is returned to the client. class View(APIView): #receives request def post(self, request, pk, *args, **kwargs): makeRequest() #make request to other API separately and do something with response later return Response(status=status.HTTP_202_ACCEPTED) #return accepted response to client How can this be achieved? -
Python Crash Course Learning Log Public tag
can anyone help me with this issue, i have already finish all the project and lm only fixing some modification from the book Python Crash Course 2nd edition , lm currently working the last part of the project which is adding the public status for the post, can anyone give me some pointers , logic or recommendation on how to fix this problem. any topic that’s public is visible to unauthenticated users as well. well. please see the pictures i attach. thank you. VIEWS def new_topic(request): """Add new Topic""" if request.method != "POST": form = TopicForms() else: """process the submitted data""" form = TopicForms(data=request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user if request.POST["public"]: new_topic.public = True new_topic.save() return redirect("learning_logs:topics") #display blank or invalid form context = {'form': form } return render(request, "learning_logs/new_topic.html", context) forms class TopicForms(forms.ModelForm): class Meta: model = Topic fields = ['text', 'public'] labels = {'text': '', 'public': 'Public'} model class Topic(models.Model): """A topic user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) public = models.BooleanField(default=False) def __str__(self): """Return a string representation of the model.""" return self.text strong texttemplate {% extends "learning_logs/base.html" %} {% block page_header %} <h1>Topics</h1> {% endblock page_header %} … -
how to exclude choices field values in django models?
form Depending from the user group of the logged in user, some story_status values should be remove if logged in user is not belong from certain group.i have a producer group, if logged in user is not belong form producer group then i want to remove the choices field value footage ready from the story_status. my code is not excluding the values models.py class Article(models.Model): STORY_STATUS = { ('story not done', 'story not done'), ('story finish', 'story finish'), ('Copy Editor Done', 'Copy Editor Done'), ('footage ready', 'footage ready') } title = models.CharField(max_length=255, help_text="Short title") story_status = models.CharField(choices=STORY_STATUS) output.html class ArticleForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(ArticleForm, self).__init__(*args, **kwargs) if not self.user.groups.filter(name__iexact='producer').exists(): self.queryset = Article.objects.exclude(story_status='footage ready') class Meta: model = Article fields = [ 'title', 'story_status' ] -
It posibble to have Django admin interface of mongodb?
In my project, I have two database (mariadb and mongodb). I want to create new admin interface to basic CRUD mongo's data . It possible to have two django admin interface into the same project? and what library I should work with mongodb? -
failed to create process while creating new project in django
I have installed a fresh python 3.7 and django 3.1.2 but when i tried to create a new project it showed me this error i tried doing everything but nothing solved this so far. C:\Users\Ahmed>django-admin startproject theapp failed to create process. -
sql server login with django/python/django Rest framework
I have an sql server database with already SQL LOGIN users , is there any way i can connect Django user model to those SQL LOGINS (i dont want to create any user model database as i already have it in my sql server) or any idea so i can login to sql server with django login? -
Django Admin custom list filter different model
I'm using Django 2.1 and I need to add a list filter on model(#1) admin page referencing a field from a different model(#2)(which has a foreign key referencing the current model(#1) These are my 2 models: class ParentProduct(models.Model): parent_id = models.CharField(max_length=255, validators=[ParentIDValidator]) name = models.CharField(max_length=255, validators=[ProductNameValidator]) parent_slug = models.SlugField(max_length=255) parent_brand = models.ForeignKey(Brand, related_name='parent_brand_product', blank=False, on_delete=models.CASCADE) ... class ParentProductCategory(models.Model): parent_product = models.ForeignKey(ParentProduct, related_name='parent_product_pro_category', on_delete=models.CASCADE) category = models.ForeignKey(Category, related_name='parent_category_pro_category', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) Here is my admin class for model 'ParentProduct': class ParentProductAdmin(admin.ModelAdmin): resource_class = ParentProductResource form = ParentProductForm class Media: pass change_list_template = 'admin/products/parent_product_change_list.html' actions = [deactivate_selected_products, approve_selected_products] list_display = [ 'parent_id', 'name', 'parent_brand', 'product_hsn', 'gst', 'product_image', 'status' ] inlines = [ ParentProductCategoryAdmin ] list_filter = [ParentBrandFilter, 'status'] Here is the ParentBrandFilter: class ParentBrandFilter(AutocompleteFilter): title = 'Brand' field_name = 'parent_brand' This works correctly because the field 'parent_brand' exists on my model 'ParentProduct'. How do I get the same autocomplete type list filter for the field category which is actually inside the 'ParentProductCategory' model. Note: 'ParentProductCategory' -> 'ParentProduct' is a many-to-one mapping. Note #2: Django admin add custom filter. I tried going through this question but couldn't get through with the approach and also my requirement is different. I … -
Unable to parse Formdata in django
I convert the JSON object to FormData. The JSON object has an array of objects , which format is not readble by django backend. Here's the example of my Formdata. Unable to parse the client_stage array in django irn_no: 12345 client_ref_number: 0000077918IN01 / RecID 85403089 application_number: 201827002702 priority_date: 2015-7-01 application_type: PCT National Phase forum: 27 client_stage[0][c_client]: 94566 client_stage[0][c_office]: 93466 client_stage[0][client_type]: Applicant client_stage[1][c_client]: 31483 client_stage[1][c_office]: 28466 client_stage[1][client_type]: Instructor client_stage[2][c_client]: 23585 client_stage[2][c_office]: 67593 client_stage[2][client_type]: Debtor client_stage[3][c_contact]: 97031 client_stage[3][client_type]: Inventor ipo_branch: 1 matter_category: 1 matter_sub_category: 1 matter_standing_instruction: ddd -
Filter queryset against current user in Django Rest Framework where User sits in seperate model
I am trying to limit a set of list objects made a available to those created by specific users in Django Rest Framework. I have been following the DRF documentation to filter against current user, the main difference I have is that User is defined in a seperate model to the the objects I am working with. I'm trying to use a dunder to fix this but the data isn't filtering correctly. All list objects are available to any user rather than only some objects being available based on the creator who is logged in. I'm wondering if anyone could propose a way forward? Here are the models: class UserList(models.Model): list_name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) class UserVenue(models.Model): venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT) list = models.ForeignKey(UserList, on_delete=models.PROTECT) And here are the views.py #this is where a user can assign cafe objects to their list object (but currently can see all lists) class UserVenueViewSet(viewsets.ModelViewSet): serializer_class = UserVenueSerializer queryset = UserVenue.objects.all() def get_queryset(self): user = self.request.user return UserVenue.objects.get_queryset().filter(list__user=user) #this shows all lists for a user class UserList(viewsets.ModelViewSet): serializer_class = UserListSerializer queryset = UserList.objects.all() def get_queryset(self): return super().get_queryset().filter(user=self.request.user) -
Insufficient number of arguments or no entry found.| Web Pack build failed Djago React
Please help me out , I am learning raect with django tutorial here, and here I installed babel using yarn but now "npm run dev" is failed. Please also refer me a suitable community for instant solutions.enter this is package.jsone this is terminal screen shot -
The Compose file '.\docker-compose.yml' is invalid because: Invalid top-level property "db"
My docker-compose.yml file contains version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: Dockerfile contains # Pull base image FROM python:3.8.6 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ Using that command to build image and run the containers with one command $ docker-compose up -d --build And gitbash terminal throwing that error $ docker-compose up -d --build The Compose file '.\docker-compose.yml' is invalid because: Invalid top-level property "db". Valid top-level sections for this Compose file are: version, services, networks, volumes, secrets, configs, and extensions starting with "x-". You might be seeing this error because you're using the wrong Compose file version. Either specify a supported version (e.g "2.2" or "3.3") and place your service definitions under the `services` key, or omit the `version` key and place your service definitions at the root of the file to use version 1. For more on the Compose file format versions, see https://docs.docker.com/compose/compose-file/ According to … -
How to run two separate django instances on same server/domain?
To elaborate, we have one server we have setup to run django. Issue is that we need to establish "public" test server that our end-users can test, before we push the changes to the production. Now, normally we would have production.domain.com and testing.domain.com and run them separately. However, due to conditions outside our control we only have access to one domain. We will call it program.domain.com for now. Is there a way to setup two entirely separete django intances (AKA we do not want admin of production version to be able to access demo data, and vice versa) in such a way we have program.domain.com/production and program.domain.com/development enviroments? I tried to look over Djangos "sites"-framework but as far as I can see, all it can do is separate the domains, not paths, and it has both "sites" able to access same data. However, as I stated, we want to keep our testing data and our production data separate. Yet, we want to give our end-user testers access to version they can tinker around, keeping separation of production, public test and local development(runserver command) versions. -
Django Vue Js Authentication
I am working on a project using Django and Vue Js. Currently, i have authenticated my users and they can now log in and logout and tokens are also saved in stores too. But I have added permission to my Django views and in my models, I also included a user field as a foreignkey. The problem now is to know the user making a post from the vue js point so my user field is not null just like other fields like content field is populated by form data. Thanks. AddPost.vue data() { return { posts: { user: "", name: "", version: "", }, submitted: false, } }, methods: { post: function() { axios.post('http://127.0.0.1:8000/posts/list/', this.posts, { headers: { Authorization: `Bearer ${this.$store.state.accessToken}` } }) .then(function(data) { console.log(data); this.submitted = true; }); } } -
Disable django-summernote widget
How can I disable the summernote widget used by django-summernote? I have read many similar posts in Stackoverflow, but none has solved my problem. I tried solving it with jQuery, but nothing is returned when I use $('#summernote') or $('.summernote') from the browsers object inspector, that even if I already loaded the summernote script in the head of my html models.py class Note(models.Model): contents = models.TextField() forms.py class UpdateNoteModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['contents'].disabled = True class Meta: model = Note fields = ('contents') widgets['contents'] = SummernoteWidget() html head <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.js"></script> html body <script type="text/javascript"> $(document).ready(function(){ $('#summernote').summernote('disable'); }); </script > -
UNIQUE constraint failed: groups_groupmember.group_id, groups_groupmember.user_id
I am working on small django project and for that i have created one functionality that allows user to create and then join the group. Now , here is the problem : whenever i leave the group and try to rejoin it , it shows error that i mentioned in the the question "UNIQUE constraint failed: groups_groupmember.group_id, groups_groupmember.user_id" here is my join class : class JoinGroup(LoginRequiredMixin, generic.RedirectView): def get_redirect_url(self, *args, **kwargs): return reverse('groups:single', kwargs={'slug': self.kwargs.get('slug')}) def get(self, request, *args, **kwargs): group = get_object_or_404(Group, slug=self.kwargs.get('slug')) from sqlite3 import IntegrityError try: # GroupMember.objects.create(group=group) GroupMember.objects.create(user=self.request.user, group=group) except IntegrityError: messages.warning(self.request, 'already a member!') else: messages.success(self.request, 'You are now a member!') return super().get(request, *args, **kwargs) Can you please help me to solve this problem ? Thank you ! :) -
Django Practice to organize views that have same permission
The login_required, user_passes_test and permission_required decorator only apply to specific functions, similar for the mixin. But is it a good practice to put @permission_required('polls.add_choice') to each and every view that require such permission? I think it is quite common that multiple views have the same permission. For example, you have an employer and job seeker, only the employer can add company name/ address, post a job and check job application. It is also common that the website requires login for most of its pages. So my question is what is the idioms/practice assigning the same permission to multiple views? The only recipe I can find is Beginning Django - Listing 10-8. Permission checks in urls. Pay for include () definitions. Another approach is to swap the view function inside a class (as static method) and do some trick the add permission to all methods. Is there any better sulotion? Or any reason not to do that? -
How to run WebSocket (django-channels) in production Pythonanywhere?
I created a simple chat app using WebSockets after following the official Django-channels tutorial. However, I can't get it to work in production. I have done a few google searching to find out a forum in Pythonanywhere saying that they don't support WebSocket, I contacted the team and they told me the same thing. I have done even more google searching and found things related to Daphne server, Nginx, and a few other things I never heard about before. As I'm new to Django-channels I'm currently very confused! Is there something I can do to make my WebSocket website run normally in Pythonanywhere on production (for free of course) Or I have to delete all of the WebSocket code and replace it with repetitive Http called to check of new messages (With AJAX)? And if there is no other solution but to move to repetitive Http calls, is there any other web hosting service that offers free play which includes free SSL certification, the domain name (such as mydomain.servicename.com) instead of random characters, and WebSocket support? Thanks the code i use I don't know if it was relevant, also it's working perfect in development so i don't think there is … -
Bug Display whith chrome
i am currently on a python / django project, i am also using bootsrap. I have a display bug only with google chrome. When I load my page everything is fine then when I scroll, the bug occurs: When I reload the page everything is back to normal: This bug is not present on the project locally, only from production on a server (ubuntu with gunicorn and nginx). When i hover the mouse over this white block, the text displays randomly. This is not the only place where it happens. I don't know if this problem is known but I have absolutely no idea what it might be. here is the part of the code that we see in picture : <!-- Description content --> <div class="container-fluid main-color-dark-bg pb-4"> <div lass="row"> <div class="col-lg-8 col-md-10 col-12 mx-auto mb-3"> <a href="{% url 'watch' 'theoretical' level video_previous %}" class="text-left subpart-link">< Précèdent</a> <a href="{% url 'watch' 'theoretical' level video_next %}" class="subpart-link float-right">Suivant ></a> </div> </div> <!-- Description --> <div class="row col-lg-8 col-md-10 col-12 mx-auto"> <div class=""> <p class="theoretical-watch-p ext-md-left text-center"> {{ video.description }} </p> </div> </div> <!-- Sous parties et Ressources --> <div class="row mx-auto col-lg-8 col-md-10 col-12"> <!-- Sous parties--> <div class="col-lg-7 col-12 … -
Trying to display image in web page generated by django view
My goal is to have a simple form that allows a user to input a function to graph, along with a display window, and once the user hits the submit button, I would like numpy and matplotlib to take the form data and generate a figure, then display that figure in the new web page. So far, I followed this where it says "Create the Contact Form View" to get the form to generate and make the data usable. I found this which allows me to display the image. However, the image takes up the whole browser window like so. I would instead like that image to display in my web page. I'm very new to Django, so sorry if this doesn't make sense or isn't enough info. I'd love to give clarification or additional info if needed. Here is my app's views.py: from django.shortcuts import render from django.http import HttpResponse from matplotlib.backends.backend_agg import FigureCanvasAgg from .forms import GraphingInput from .graphing_tool import graph import io # Create your views here. def grapher_tool_input(request): submitted = False if request.method == 'POST': form = GraphingInput(request.POST) if form.is_valid(): cd = form.cleaned_data fig = graph(cd['left_end'], cd['right_end'], cd['top'], cd['bottom'], cd['function']) response = HttpResponse(content_type='image/jpg') canvas = FigureCanvasAgg(fig) … -
Django icalendar dtstart datetime issue
I have a form in Django-python for an event program. I'm trying to create an ics file for the events with icalendar, for this, I want to get the values 'dtstart' and 'dtend' from the variables 'starttime' and 'endtime' in the form, but I'm getting the code: Wrong datetime format. Anyone with any advice to solve this issue? ERROR elif not ical[15:]: return datetime(*timetuple) elif ical[15:16] == 'Z': return pytz.utc.localize(datetime(*timetuple)) else: raise ValueError(ical) except: raise ValueError('Wrong datetime format: %s' % ical) … class vDuration(object): """Subclass of timedelta that renders itself in the iCalendar DURATION format. """ CODE def event(request, id=None): instance = Event_cal() if id: instance = get_object_or_404(Event_cal, pk=id) else: instance = Event_cal() form = EventForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): form.save() startdate = request.POST.get('starttime') endate = request.POST.get('endtime') event = Event() event.add('summary', 'My Summary') event.add('dtstart', vDatetime.from_ical(startdate)) event.add('dtend', vDatetime.from_ical(endate)) Thanks in advance, I am learning python, so I don't have have much experience.