Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to activate an existing virtualenv projects? [Windows, Django, Python]
I'm a beginner to Django and Python, and I've never used virtualenv before. However, I do know the exact commands to activate and deactivate virtual environments (online search). However, this learning course takes time and sometimes I need to split the work over 2 days. When I create a virtualenv today and do some work, I'm unable to access the same virtualenv tomorrow. Even when I navigate to that folder and type in .\venv\Scripts\activate, it says "system cannot find specific path". How can I open already existing virtual environments and the projects within them? Could it be that I need to end my previous session in a certain way for me to access it the next time? -
Choice field for multiple items in a field
If i have 5 diffent sport in Sports then in Intrest model i want to put level to each of those 5 sports seprately,and want to print.How to do it. exampl:cricket=Advance basketball=beginer class Sports(models.Model): Sport=models.CharField(max_length=30) class User(models.Model): user=models.CharField(max_length=30) class Intrest(models.Model): user_name=models.Foreignkey(User,on_delete=models.CASCADE) sport=models.Foreignkey(Sports,on_delete=models.CASCADE) LEVEL=( ('1','Beginer'), ('2','Intermediate'), ('3','Advance'), ('4','Nevel Played'), ) Level=models.CharField(max_length=30,choices=LEVEL) -
Python dictionary to kwargs customization using comprehension
I use comprehension to build a dictionary to apply some filtering in Django dynamically. How can i modify the **filters in order to unpack the dictionary into custom arguments? filters = { key: value for key, value in [date1,date2,date3] } then print(**filters) Instead of date1=date1,date2=date2,date3=date I want: date1_gte=date1,date2_gte=date2,date3_gte=date3 -
Dynamic Django Bootstrap accordion inside for loop not loading
I've been working on an online portfolio and have been using the Django framework to do so. For a projects tab, I pass in an object (projects) containing the details of all my projects and try to show them through in an accordion through a for loop in a dynamic template. But the tabs do not collapse upon clicking them. I have no idea why. {% block content %} <h1>Projects</h1> <div class="accordion accordion-md" id="projectsAccordion" role="tablist" aria-multiselectable="true"> {% for project in projects %} <div class="card"> <div class="card-header" role="tab" id="{{ project.name }}heading"> <a data-toggle="collapse" data-parent="#projectsAccordion" href="#{{ project.id }}" aria-expanded="false" aria-controls="{{ project.name }}"> <h5 class="mb-0"> {{ project.name }} </h5> </a> </div> <!-- card header --> <div id="{{ project.id }}" class="collapse" role="tabpanel" aria-labelledby="{{ project.name }}heading" data-parent="#projectsAccordion"> <div class="card-block px-3 my-2"> <p>{{ project.description }}</p> <p>Timeframe: {{project.start_date}} - {{project.end_date}}</p> {% if project.motivation %} <p>Motivation: {{ project.motivation }}</p> {% endif %} <ul class="list-inline list-unstyled"> {% for tech in project.technologies.all %} <li class="list-inline-item"><p>{{ tech.name }}</p></li> {% endfor %} </ul> <button type="button" href="{{ project.link }}" target="_blank" class="btn btn-primary align-text-top project-link"> Code </button> </div> <!-- card body --> </div> <!-- collapse --> </div><!-- card --> {% endfor %} </div> <!-- accordion --> {% endblock %}``` -
im getting error in install Gdal library on heroku
devs, can anybody please tell me how to install gdal library on Heroku because I'm getting an error while I'm deploying my project on Heroku. I got two errors as follows: ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-_s4gq6_a/GDAL/setup.py'"'"'; file='"'"'/tmp/pip-install-_s4gq6_a/GDAL/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-_s4gq6_a/GDAL/pip-egg-info cwd: /tmp/pip-install-_s4gq6_a/GDAL/ Complete output (75 lines): WARNING: numpy not available! Array support will not be enabled /app/.heroku/python/lib/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running egg_info creating /tmp/pip-install-_s4gq6_a/GDAL/pip-egg-info/GDAL.egg-info writing /tmp/pip-install-_s4gq6_a/GDAL/pip-egg-info/GDAL.egg-info/PKG-INFO writing dependency_links to /tmp/pip-install-_s4gq6_a/GDAL/pip-egg-info/GDAL.egg-info/dependency_links.txt writing top-level names to /tmp/pip-install-_s4gq6_a/GDAL/pip-egg-info/GDAL.egg-info/top_level.txt writing manifest file '/tmp/pip-install-_s4gq6_a/GDAL/pip-egg-info/GDAL.egg-info/SOURCES.txt' Traceback (most recent call last): File "/tmp/pip-install-_s4gq6_a/GDAL/setup.py", line 151, in fetch_config p = subprocess.Popen([command, args], stdout=subprocess.PIPE) File "/app/.heroku/python/lib/python3.6/subprocess.py", line 729, in init restore_signals, start_new_session) File "/app/.heroku/python/lib/python3.6/subprocess.py", line 1364, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: '../../apps/gdal-config': '../../apps/gdal-config' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/tmp/pip-install-_s4gq6_a/GDAL/setup.py", line 249, in get_gdal_config return fetch_config(option, gdal_config=self.gdal_config) File "/tmp/pip-install-_s4gq6_a/GDAL/setup.py", line 154, in fetch_config raise gdal_config_error(e) __main__.gdal_config_error: [Errno 2] No such file or directory: '../../apps/gdal-config': '../../apps/gdal-config' During handling of the above exception, another exception occurred: Traceback (most recent call last): File … -
How to add HttpResponseRedirect instead of Response(serializer.data) in PUT request?
How can I override PUT request and instead of returning data add HttpResponseRedirect(reverse('home'))? class ItemAPIView(RetrieveUpdateAPIView): authentication_classes = (SessionAuthentication, ) permission_classes = (IsCompanyAdmin, ) serializer_class = ItemSerializer def get_object(self): get_object_or_404(...) -
authentication with simple user
good morning i have a problem with my login function when i submit it didn't login successufuly when i print(user.email) it give me the email of superuser not the email of simple user what is my errors def login(request): context = {} print("ok ok ok ok ok") user = request.user print(user.email) if user.is_authenticated: return render(request, "login.html") print("ok ici") form = LoginForm(request.POST or None) if request.POST: form = LoginForm(request.POST or None) if form.is_valid(): email = form.cleaned_data.POST['email'] password = form.cleaned_data.POST['password'] user = authenticate(request, email=email, password=password) print(email) if user: login(request, user) if user.user_type == '1': return render(request, "administrateur.html") elif user.user_type == '2': return render(request, "entrepreneur.html") else: print("errors") form = AuthenticationForm() context['login_form'] = form return render(request, "entrepreneur", context) -
Django Rest Framework: incorrect hyperlink on second viewset of same model
I'm trying to provide two distinct APIs using DRF but I'm unable to get the second app to stop creating hyperlinked references based on the first. It's essentially the same problem as Django Rest Framework with multiple Viewsets and Routers for the same object but I'm unable to get it working. app1/urls.py: router = SimpleRouter(trailing_slash=False) router.register(prefix=r'article', viewset=app1.ArticleViewSet, basename=r'article') urlpatterns = [path(f'', include(router.urls)] app2/urls.py: router = SimpleRouter(trailing_slash=False) router.register(prefix=r'published', viewset=app2.ArticleViewSet, basename=r'published') urlpatterns = [path(f'', include(router.urls)] site/urls.py: urlpatterns = [ path('app1/', include('app1.urls')), path('app2/', include('app2.urls')), ] While both viewsets are of the same model, the queryset & serializer for each is different. When I GET an item from /app2/published, it has an app1 URL: "url": "http://localhost:8000/app1/article/5461" What I'm wanting is for items retrieved via app2 to have: "url": "http://localhost:8000/app2/article/5461" From looking at the docs, it appears that providing basename should do what I want, but I'm not having any luck with getting it to work. -
How Do I Have Multiple ModelForms In Django in A SingleView?
I am trying to create A Project where I Have A model Form Which Takes A set of data as Input. However that is not an issue, How Do I Have Multiple Forms of that One single Model Form . I tried Using something like this from .forms import BookForm # Create your views here. def home_page(request): context = {} form = BookForm(request.POST or None) form1 = BookForm(request.POST or None) if form.is_valid(): form.save() if form1.is_valid(): form1.save() context['form']= form context['form1']= form1 return render(request, "home.html", context) But What Happens is the Data passed in the last form is passed in all of the forms. How Do I Implement this in Django Handling multiple forms in single view, which gets submitted on click of a button -
problem with deploying a dajngo project with gunuicorn and ngnix on centos
I followed all things in this digitalocean tutorial deploy with gunicorn,ngnix on centos But still my website is unavailable and I got unable to connect error but when I ping it It responds what is the problem? -
Is it possible to foreign key on bulk_create() Django?
I have the need to create many EVENT objects at once and subsequently create many ARCHIVED_EVENT objects that have a foreign key to their corresponding event. My code looks like something like this: events = [] archivedEvents = [] for _ in range(1000): event = Event(name="Test") archivedEvent = ArchivedEvent(event_id=event.id) archivedEvents.append(archivedEvent) events.append(event) Event.objects.bulk_create(events) ArchivedEvent.objects.bulk_create(archivedEvents) Unfortunately all Archived Events created here have a NULL foreign key to an EVENT. I understand that the primary key for an object is not generated until it is saved to the database. But I save the events before creating the archived events. Am I missing something? Should I refresh the cache before bulk creating the archived events? -
Django detail view
Models class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) box = models.CharField(max_length = 100, choices = box_choices) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ) status = models.CharField(max_length = 100, choices = status_choices) def __str__(self): return f"{self.user_id}-{self.pk}" class Date(models.Model): order_id = models.OneToOneField(Order, on_delete=models.CASCADE) date_added = models.DateField(max_length=100) scheduled_date = models.DateField(max_length=100) service_period = models.DateField(max_length=100) modified_date = models.DateField(max_length=100) finish_date = models.DateField(max_length=100) html template 'date_list.html' <!DOCTYPE html> <html> <head> <h1>Customer Record</h1> <form action="{% url 'accounts:logout-page' %} " method="post"> {% csrf_token %} <button type="submit" name="button">Logout</button> </form> </head> <body> <a class="button" href="{% url 'accounts:create-order' %}">Create</button>&nbsp;&nbsp;&nbsp;&nbsp;</a> {% for Order in order %} {{ Order.id }}&nbsp;&nbsp;&nbsp;&nbsp; {{ Order.user }}&nbsp;&nbsp;&nbsp;&nbsp; {{ Order.quote}}&nbsp;&nbsp;&nbsp;&nbsp; {{ Order.box }}&nbsp;&nbsp;&nbsp;&nbsp; {{ Order.pill_choice }}&nbsp;&nbsp;&nbsp;&nbsp; {{ Order.shipping_tracking}}&nbsp;&nbsp;&nbsp;&nbsp; {{ Order.memo}}&nbsp;&nbsp;&nbsp;&nbsp; {{ Order.status}}&nbsp;&nbsp;&nbsp;&nbsp; <a class="button" href="{% url 'accounts:date-list' %}">View</a>&nbsp;&nbsp;&nbsp;&nbsp; <a class="button" href="{% url 'accounts:update-order' Order.id %}">Update</a>&nbsp;&nbsp;&nbsp;&nbsp; <a class="button" href="{% url 'accounts:delete-order' Order.id %}">Delete</a>&nbsp;&nbsp;&nbsp;&nbsp; {% endfor %} </body> </html> Views. def date_list(request): date = Date.objects.all() context = { 'date': date } return render(request, "date_list.html", context) So I have two models 'Order' and 'Date', I'm actually trying … -
Can load balancing be done on our local website
I have a simple registration website made using django. Now i want to load balance requests on this website which is on localhost. Is this possible if so how? -
Sub-tenant for a tenant in django tenant schemas
I have managed to create a multi tenant system using django tenant schemas and it is working perfectly fine. Now, I want to develop another feature into it and I am not getting how to develop it. So let me explain it with a example. Suppose there's a tenant named ABC on our website (abc.localhost.com). ABC hires another company to handle sales, they have their own tenant setup on my website (salesXYZ.localhost.com). I want ABC and salesXYZ to be connected to each other so that salesXYZ must be able to access ABC's data. Is there anyway I can integrate this? -
Creating another model object alongside with generic CreateView
Here I am trying to register log if the new category has been created. But this is not working.I am using generic View to create the category model now I want to add LogEntry to this model so tried like this but it is throwing error. Exception Type: AttributeError Exception Value: 'CreateCategory' object has no attribute 'object' views class CreateCategroy(SuccessMessageMixin, generic.CreateView): model = Category fields = ['title'] template_name = 'add_category.html' success_url = reverse_lazy('list_category') success_message = 'Created Successfully.' def post(self, request, *args, **kwargs): LogEntry.objects.log_action(user_id=self.request.user.pk, content_type_id=ContentType.objects.get_for_model(self.object).pk, object_id=self.object.pk, object_repr=force_text(self.object), change_message='New Category has been created.', action_flag=1 ) -
Distinguishing The actions of updating and creation in django M2M signals
I wish to do the following. When a new project is created , i want to notify everybody that was assigned to the project that there's a new project available. Here is my simplified project model: class SalesProject(models.Model): sales_project_name = models.CharField(max_length=100) userProfile = models.ManyToManyField('UserProfile', blank=True) history = HistoricalRecords(excluded_fields=['version', 'project_status']) def __str__(self): return self.sales_project_name When a project is being created, i will send out the following signal : def CreateProjectNotification(sender, **kwargs): if kwargs['action'] == "post_add" and kwargs["model"] == UserProfile: for person in kwargs['instance'].userProfile.all(): #some check here to prevent me from creating a notification for the creator or the project Notifications.objects.create( target= person.user, extra = 'Sales Project', object_url = '/project/detail/' + str(kwargs['instance'].pk) + '/', title = 'New Sales Project created') The reason why im using the m2m_changed.connect instead of post_save is because i wish to access the M2M field , UserProfile to send out the notifications. Since the object would not be added to the through table at the point of creation , i can't use the post_save and instead i have to track the changes from the through table . problem With that said , this signal runs as long as the save() function is called and the model which changed … -
Django dynamic list comprehension filtering between dates
I am using comprehension to filter dynamically between multiple from-to date inputs. If one of the two has no value, the search should still work. How can I apply the below logic using django range operator? def mail_search(request): today_date = datetime.now() qs = MailAllocation.objects.filter(cmp_id=cmp_id) """comprehension: build a dictionary and use it for filtering queryset dynamically""" filters = { key: value for key, value in request.POST.items() if key in ['date_from1','date_to1','date_from2','date_to2','date_from3','date_to3'] and value } qs = qs.filter(**filters).order_by('-creation_date') context={ 'dfs_search_results':qs, } return render(request,'mail_search_results.html',context) -
Get value from form in createview
I use a CreateView to create new users, but I want to update an another model in the same time. (add the user to a club) My form : class SignUpFormInvitation(UserCreationForm): club = forms.CharField(label="Club") club_pk = forms.CharField(widget=forms.HiddenInput) username = forms.CharField(max_length=30, required=True, label="Pseudo") first_name = forms.CharField(max_length=30, required=True, label="Prénom") last_name = forms.CharField(max_length=30, required=True, label='Nom') email = forms.EmailField(max_length=254, label='E-mail') password1 = forms.CharField(widget=forms.PasswordInput, label="Mot de passe") password2 = forms.CharField(widget=forms.PasswordInput, label="Mot de passe confirmation") class Meta: model = User fields = [ 'club', 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', ] def __init__(self, *args, **kwargs): super(SignUpFormInvitation, self).__init__(*args, **kwargs) self.fields['club'].widget.attrs['readonly'] = True The field club and club_pk are correctly added to the form. My view : class SignUpViewInvitation(generic.CreateView): """ display the register form for a sportif """ form_class = SignUpFormInvitation success_url = reverse_lazy('user-connexion') template_name = 'utilisateurs/signup.html' def get_initial(self): club = get_object_or_404(Club, token=self.kwargs.get('token')) return { 'club':club, 'club_pk':club.pk, } def form_valid(self, form): club = Club.objects.get(pk=form.instance.club_pk) club.clubs_members.add(self.request.user) return super().form_valid(form) I try to use form_valid to update the club model but this error is returned : 'User' object has no attribute 'club_pk' for this line club = Club.objects.get(pk=form.instance.club_pk) -
How to setup fcm-django properly
I new to push notification, so I'm sorry for this stupid questions and also I'm unclear about some the terminology used in this package. Here I've some question. -Is the server key and fcm api key is same? -do i need to add some extrnal js script ko make this package work properly. if can you please share some guide or pdf or some link which help me to integrate this. -Do i need to add FCM Device manually? Please make me clear about fcm device. -After setup this project, i didn't get any notification to enable or disable push notifications. Here is my setup settings.py INSTALLED_APPS = [ ....... "fcm_django", ] FCM_DJANGO_SETTINGS = { "FCM_SERVER_KEY": "AAAA......:................................................MGC22WxjWHHcKOo" } Note: FCM_SERVER_KEY is server key instead of web api key If i need to add FCM Device how can i add FCM Devices properly, because i didn't know, from where and how to garb all the value for model FCM Device model fields. -
how can i get max latitude - min latitude - max longitude and min longitude point and radius in python django
I want to get max latitude - min latitude - max longitude and min longitude in my radius and them divide 4 parts and get 4 random points in 4 parts radius = 101 latitude = 54.3578545 longitude = 36.417484151 point = Point(float(latitude), float(longitude)) locations = Location.objects.filter(location__equals=(point, D(km=radius))) point.x + d or point.x + d.standard -
neo4j: "NO MODE SPECIFIED!"
I added neo4j to my docker-compose.yml file. It succesfully created, but while docker-compose up file it gives me this two error messages for neo4j: NO MODE SPECIFIED! env variables are populated(think that is not important) and excites with "neo4j exited with code 1" Also, I am adding MODE to environments, but how I see didn't help. that is how my docker-compose.yml looks like: neo4j: image: neo4j:4.0.5 hostname: neo4j container_name: neo4j ports: - "7474:7474" - "7687:7687" volumes: - ./data:/data environment: - NEO4J_dbms_mode=CORE -
Creating A Relationship Between Two User Models
Im building a website which will have teachers and students. Im using the default Django User models and originally ignored Teachers and treated all my Users as Students. Today I began trying to separate my users into Teachers and Students and am having a lot of difficulty. Im obviously missing some fundamental knowledge and have read a lot online but am going around in circles. A teacher can have many students and a student can have one teacher. First I thought Id need separate Student and Teacher models. So everyone now is a User, and I will attach either a Student or Teacher model to each (is this sloppy?). Now for the relationship. I tried creating a relationship between teachers and students within their own models, but it didnt work so I figured id need a separate TeacherStudentRelationship class to hold the relationships. This is my implementation so far: class Student(models.Model): student = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.student.username}' class Teacher(models.Model): teacher= models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.teacher.username}' class TeacherStudentRelationship(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) teacher = models.OneToOneField(User, on_delete=models.CASCADE) This doesnt throw any errors, though in Django Admin I can create multiple instances of TeacherStudentRelationship and assign a student to a … -
Is it possible to retrieve 'id' field of objects deleted in Django .delete()?
When executing the following query, is there a mechanism in place to return a list of the 'id's of the objects that have been deleted? >>> MyModel.objects.all().delete() >>> (430, {'myapp': 430}) -
SSL: CERTIFICATE_VERIFY_FAILED
Tried Option didn't work used in app.py os.environ['PYTHONHTTPSVERIFY'] = '0' ssl._create_default_https_context = ssl._create_unverified_context using flask data = report_downloader.DownloadReport( report, output, skip_report_header=False, skip_column_header=False, skip_report_summary=False, include_zero_impressions=True) and trying to get ACCOUNT_PERFORMANCE_REPORT working fine on local system when used tiangolo/uwsgi-nginx-flask:python3.6 as docker base image and deployed giving below error File "/google-analytics/helper_service/service.py", line 328, in sync_google_ads_word_data skip_report_summary=False, include_zero_impressions=True) File "/usr/local/lib/python3.6/site-packages/googleads/common.py", line 405, in Wrapper return utility_method(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/googleads/adwords.py", line 1268, in DownloadReport output, **kwargs) File "/usr/local/lib/python3.6/site-packages/googleads/adwords.py", line 1540, in _DownloadReport response = self._DownloadReportAsStream(post_body, **kwargs) File "/usr/local/lib/python3.6/site-packages/googleads/adwords.py", line 1614, in _DownloadReportAsStream response = self.url_opener.open(request) File "/usr/local/lib/python3.6/urllib/request.py", line 526, in open response = self._open(req, data) File "/usr/local/lib/python3.6/urllib/request.py", line 544, in _open '_open', req) File "/usr/local/lib/python3.6/urllib/request.py", line 504, in _call_chain result = func(*args) File "/usr/local/lib/python3.6/urllib/request.py", line 1361, in https_open context=self._context, check_hostname=self._check_hostname) File "/usr/local/lib/python3.6/urllib/request.py", line 1320, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)> -
Django admin log table not updating?
Django admin logs were showing fine before but once I deleted them all then it is not adding the logs in the table . The table is empty always . LogEntry.objects.all() it shows all the data before (worked). after I deleted them all with LogEntry.objects.all().delete() and removed this code. Now I tried changing database and performed some CRUD operation but LogEntry table is empty. What might gone wrong ?