Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channels not connecting client using Nginx
I'm trying to deploy a Django app that uses Django Channels. I deployed the app using Nginx and Gunicorn, since i want Daphne to handle only all the Websocket-related stuff. I created a systemtl service for daphne, here it is: [Unit] Description=Daphne service After=network.target [Service] PIDFile=/run/daphne/pid User=root Group=root WorkingDirectory=/django-vue-mpa ExecStart=/django-vue-mpa/venv/bin/daphne --bind 0.0.0.0 --port 9000 --verbosity 0 django_vue_mpa.asgi:application ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID Restart=on-abort PrivateTmp=true [Install] WantedBy=multi-user.target And here is my actual nginx conf: server { listen 80; server_name http://138.68.97.153/; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /django-vue-mpa/django_vue_mpa; } location / { include proxy_params; proxy_pass http://unix:/django-vue-mpa/django-vue-mpa.sock; } } The problem is that every time i try to connect to a websocket consumer i get a TIMED OUT error. What do i need to edit in my nginx config file in order to handle websocket requests to Django Channels? Any advice is appreciated! -
Is it possible to next lookup fields in Django RestFramework?
Suppose I have a model with a ManyToManyField and would like to add or remove entries using the drf. Is there a way to nest these so that the endpoint url looks like mainmodel/{mainmodel_id}/many_to_many_name/{entry_id}? I tried using 'lookup_fields' as class parameter, which didn't work and nesting Viewsets like this: class MainModelAPI(viewsets.GenericViewSet): model = MainModel serializer_class = MainModelSerializer queryset = MainModel.objects.all() lookup_field = 'mainmodel_id' class SubModel(viewsets.GenericViewSet): model = SubModel lookup_field = 'entry_id' ... But both obviously didn't work. I searched the API but didn't find any reference for "nesting viewsets" or "multiple lookup fields / ids". -
runtests.py after install and cloning django in linux terminal
I don't know if I've gone wrong somewhere. But ive cloned and activated django in the linux terminal on my chromebook. It says it can take a while for the runtests.py to complete but it's my second attempt and i'm getting endless periods and random 's' was being thrown in every so often. I'm not very good with the linux terminal and I have only the past hour started trying to understand django. But this is currently what my terminal looks like and it is never ending: ..............................................................................................................................................................................................................................................ssssssssssssssssssssssssssssssssssss...................................s..s........................................s............................s...........s.sss...s......................................................................................................................sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss.s................................sss..............................................................................................................................s.........s.......ss..................s......................................s...................s.........s.s...s...s.s.......s.s......s..s.....................................s.......................................................................................... Have I gone wrong somewhere? Everything else seemed to work fine (I am following a tutorial). Sorry if I sound like an idiot -
Get fields of foreign key in serializer django
I'm 2 weeks into django so this might be dumb! In my django project, I have 3 models, Teacher, Student and a CustomUser. CustomUser has 2 fields first_name and last_name. Student has 3 fields grade, field_of_study and user which is a foreign key to CustomUser. Now inside my StudentSerializer I want to serialize first_name, last_name, grade and field of study. But because the last 2 field are not direct fields of Student, I cannot do that. Anyone know how this should be handled? I also came across this Retrieving a Foreign Key value with django-rest-framework serializers but the answer didn't help really. -
Logging Errors not going to correct file
I`m currently working with Django and the errors are not going to error_log, but they are going to log. The settings are: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s', 'datefmt' : "%d/%b/%Y %H:%M:%S", }, 'simple': { 'format': '%(levelname)s %(asctime)s %(message)s', 'datefmt' : "%d/%b/%Y %H:%M:%S", }, }, 'handlers': { 'file': { 'level': 'INFO', #'class': 'logging.FileHandler', 'class':'logging.handlers.TimedRotatingFileHandler', 'when': 'D', 'filename': os.path.join(BASE_DIR, 'logs', 'log'), 'formatter': 'simple', }, 'error_file': { 'level': 'ERROR', #'class': 'logging.FileHandler', 'class':'logging.handlers.TimedRotatingFileHandler', 'when': 'D', 'filename': os.path.join(BASE_DIR, 'logs', 'error_log'), 'formatter': 'simple', }, 'console':{ 'level': 'INFO', 'class':'logging.StreamHandler', 'formatter': 'simple', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file'], 'level': 'INFO', 'propagate': True, }, 'error_file': { 'handlers': ['console', 'error_file'], 'level': 'ERROR', 'propagate': True, } }, } Can someone help me understand why is that? I was looking for it and did not find the error. Django documentation: "It isn’t enough to just put logging calls into your code. You also need to configure the loggers, handlers, filters, and formatters to ensure you can use the logging output. Python’s logging library provides several techniques to configure logging, ranging from a programmatic interface to configuration files. By default, Django uses the dictConfig format. In order … -
Braintree Payment store_in_vault: false not working
I'm using Python and Braintree with the Drop-In. I try to not store a credit card in the vault, but the option seems to get ignored. Here is my code: result = gateway.transaction.sale({ "amount": order.total_amount, "payment_method_nonce": request.data.get('nonce', 'none'), "options": { "submit_for_settlement": True, "store_in_vault_on_success": False }, }) Although the option is set to false after a successful payment (sandbox) and a page refresh the payment method is stored. -
django makemigrations command takes too long because of directory node_modules
I put the frontend code inside my django project. When I execute makemigrations command using manage.py , django simply stuck at '''Tracking file by folder pattern: migrations''' and takes much time to finish. I have to remove the node_modules directory in the front-end source code dir to make 'makemigrations' to function again. Is there a workaround so that I can make manage.py ignore the node_modules directory so it can run makemigrations? -
I'm getting a NoReverseMatch error but I think my files are valid
From my base.html: <div id="button_container"> <button class="button"><a href="{% url 'home' %}"> HOME </a></button> <button class="button"><a href="{% url 'rooms' %}"> ROOMS & SUITES </button> <button class="button"><a href="{% url 'roomBookingsList' %}"> ROOM BOOKINGS </button> </div> Urls.py: path('rooms/mybooking', views.roomBookingsList, name='roomBookingsList'), Views.py: def roomBookingsList(request): suiteBookingList = Suite_booking.objects.all() context = { 'suiteBookingList': suiteBookingList, } return render (request, 'roomBookingsList.html', context=context) roomBookingsList.html: {% for suiteBookingList in suiteBookingList %} <li> {{ suiteBookingList }}</li> {% endfor %} So when I run it and click the ROOM BOOKINGS from the base.html, it will show me whatever rooms I have booked. No problem here. I also want to add an edit button here so I can update the booking if I accidentally typo the name or something. So I added in the roomBookingsList.html: {% for suiteBookingList in suiteBookingList %} <li> {{ suiteBookingList }}</li> - <a href="{% url 'edit_suite' suite.id %}">Edit</a> {% endfor %} Added in urls.py: path('rooms/suite/edit/<int:suite_id>', views.edit_suite, name='edit_suite'), Added in views.py: def edit_suite(request, suite_id): if request.method == 'POST': suite = Suite_booking.objects.get(pk=suite_id) form = BookingForm(request.POST, instance=suite) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('roomBookingsList')) else: suite = Suite_booking.objects.get(pk=suite_id) fields = model_to_dict(suite) form = BookingForm(initial=fields, instance=suite) context = { 'form': form, 'type': 'edit', } return render(request, 'roomBookingsList.html', context=context) Then I tried to run it again, … -
how to write 3 dependant table join query in Django
I am new in django , I want to create join query in django, my model is as follow Model.py Class area_country(models.Model): country_id = models.AutoField(primary_key=True) country_name = models.CharField(max_length=100, null=True) short_name= models.CharField(max_length=20, null=True) flag_enable = models.SmallIntegerField() class Meta: db_table = "area_country" class area_state(models.Model): state_id = models.AutoField(primary_key=True) state_name = models.CharField(max_length=100, null=True) short_name = models.CharField(max_length=20, null=True) country_id = models.ForeignKey(area_country, on_delete=models.CASCADE) flag_enable = models.SmallIntegerField() class Meta: db_table = "area_state" class area_city(models.Model): city_id = models.AutoField(primary_key=True) city_name = models.CharField(max_length=100, null=True) short_name = models.CharField(max_length=20, null=True) state_id = models.ForeignKey(area_state, on_delete=models.CASCADE) flag_enable = models.SmallIntegerField() class Meta: db_table = "area_city" i need query like SELECT "area_country"."country_id", "area_country"."country_name", "area_state"."state_id", "area_state"."state_name", "area_city"."city_id", "area_city"."city_name" FROM "area_country" LEFT OUTER JOIN "area_state" ON ("area_country"."country_id" = "area_state"."country_id_id") LEFT OUTER JOIN "area_city" ON ("area_state"."state_id" = "area_city"."state_id_id") ** Try by me ** view.py result = area_country.objects.all().select_related('area_state').values('country_id', 'country_name', 'area_state__state_id', 'area_state__state_name') when i print it by using query = result.query SELECT "area_country"."country_id", "area_country"."country_name", "area_state"."state_id", "area_state"."state_name" FROM "area_country" LEFT OUTER JOIN "area_state" ON ("area_country"."country_id" = "area_state"."country_id_id") this is ok now i try result = area_country.objects.all().select_related('area_state').select_related('area_city').values('country_id', 'country_name', 'area_state__state_id', 'area_state__state_name','area_city__city_id','area_city__city_name') it show me error Cannot resolve keyword 'area_city' into field. Choices are: area_state, country_id, country_name, flag_enable, short_name please help me. -
Hyperlinks in Django for loop are linking to the same page
On a user's profile page right now it is displaying the number of people they are following and the usernames of the people they are following. When the user clicks on a username, I quite simply want it to take the user to that user's profile page but right now it is linking back to the same user's profile page, so essentially just reloading the page. I am guessing it is because I am passing in user.username as a keyword argument because when I follow this same format but instead using user.id I don't run into this problem. I would like to use user.username so that the username can be displayed in the url. profilePage.html {% block body %} <h3>{{ user.username }}</h3> <br> <br> <p>{{ profile.number_of_friends }}</p> <p>{% for friend in profile.get_friends %}</p> <a href="{% url 'profile' profile.user.username %}">{{ friend }}</a><br> {% endfor %} {% endblock %} views.py def profile_page(request, user_username): profile = get_object_or_404(Profile, user__username=user_username) return render(request, "network/profilePage.html", { "profile": profile }) urls.py path("profile/<str:user_username>", views.profile_page, name="profile"), models.py class User(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE, primary_key=True) friends = models.ManyToManyField("User", related_name='following', blank=True, symmetrical=False) -
Django Channels after sending message, current tab showing 2 messages(sender + receiver) but other tab does not show anything?
I am following this tutorial Channels Tutorial Link My Goal was to make a simple asgi chat server. But It is showing weird behaviour. The message sent from one tab..should print "HI" in current tab..and also "HI" in the tab connected in the same room. but its printing the both "HI" in the current tab, no message is shown in the other tab connected in the same room. my consumers.py is simeple, just from the tutorials file... import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) my settings file is configured to receive redis connection in 127.0.0.1. I am using docker redis image just s the tutorial said. ASGI_APPLICATION = 'mysite.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': … -
How to add a gitignore folder to github actions?
I have a Django Project and created a dev branch. In my .gitignore file I have the "media" folder. My project looks like this: - Django Project/ - app1/ - app2/ - media/ - profile_pics/ - default.jpg - .gitignore In my gitignore I added media. I've been trying to add github actions, so I created this ci.yml name: Testing on: push jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.6, 3.7, 3.8] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Tests run: | python manage.py test When I push the repo I received this message from Github Actions: FileNotFoundError: [Errno 2] No such file or directory: '****/media/default.jpg' What is the best way to deal with this? I could use git add media -f but I do not know if then this file would be in my repo and when I merge it with main and deploy it I would have that folder and overwrites the media in deployment. -
Getting filtered list of items in admin changelist_view()
I need to enrich the changelist_view page with some statistics for the items that are shown, id est after the filters have been applied. But I've found no straightforward way. I can get queryset and parse request URL for the filters, but it's ugly. I can first get super().changelist_view(request), and then I have context_data['cl'].queryset, but that's double work, since I'll need to make HTML again with my added data. Is there some better way? I think the closest question was Django admin change_list view get ChangeList queryset - better solution than my monkey patch, but there was no answer there… -
How to get notification on template using django signals?
I'm a beginner's level Django developer and I'm making a hospital system. In the hospital system, I want to add a notification system whenever any patient uploads a report against the doctor id I want to inform the doctor to the doctor notifications template that the report of patient(with name) has been submitted. I was trying it to work for 2 days and used signals to create a message but I'm unable to show it on the doctor's side. Please anyone can tell me how can I make it easier or Should I use something else instead of signals. The Previous Code that I tried. from django.shortcuts import render, HttpResponse,request from hospital.models import Patient ,Doctor,Report from django.db.models.signals import post_save,pre_save def save_report(sender,instance,**kwargs): instance = Patient.objects.get(id=1) dr_id= instance.assignedDoctorId patient=models.Patient.objects.get(user_id=request.user.id) doctor=models.Doctor.objects.get(id=dr_id) notifications=print("New report has been submitted") mydict={ 'doctor':doctor, 'patient':patient, 'notifications':notifications } return render(request,'temp/doctor_Notifications.html',context=mydict) post_save.connect(save_report,sender=Report) -
Vendor Permission in Django
How to set permissions in Django so that a Vendor can delete or update their own product, not others. This means if they log in from their account then they can only update or delete their own product, not others. -
Django ImportError at/ boards doesn't look like a module path
first of all, I'm a junior programmer and this is the first question in this communicate so, I have a problem when I configure the HTML file with Django this error comes on my face, please guys help me ImportError -
Tempus dominus form input not valid
Im using tempus dominus widget to pick a date and time in my django project. I realised that particular line made the form return False for form.is_valid(). The is_valid() function only returns false when I add that date field with the tempus dominus widget in my forms.py. views.py @require_http_methods(["POST"]) def saveBooking(request): form = BookingForm(request.POST, request.FILES) print(form.is_valid()) <--returns False forms.py from tempus_dominus.widgets import DateTimePicker class BookingForm(forms.ModelForm): # Next line gives error date = forms.DateTimeField(widget=DateTimePicker(options={ 'useCurrent': True, 'collapse': False, }, attrs={ 'append': 'fa fa-calendar', 'icon_toggle': True, } ), label="" ) models.py class Booking(models.Model): date = models.DateTimeField(default=timezone.now,null=False) -
Play the uploaded video(One video in one page) in detail page
After clicking watch Home page Code structure If any one can help me with this, It will be very kind of you, Stuck for weeks in this Source used in html file <source src='{{ MEDIA_URL }}{{ movie_file }}' type='video/mp4'> views.py def Movie_detail(request, pk): lastvideo = Postmovie.objects.last() movie_file = lastvideo.movie_file post = Postmovie.objects.filter(Published_date__lte=timezone.now()).order_by('-Published_date') #movie = Postmovie.objects.all() stuff_for_frontend = {'post': post, 'movie_file': movie_file} return render(request, 'Movie_Management_System/Movie_details.html', stuff_for_frontend) # render movie details Here last video is only shown knowingly because the video was not playing and i came up with this logic but i want to play those videos which are uploaded in form Post_list.html <div class="card" style="width: 18rem;"> {% if post.Thumbnail %} <img class="card-img-top" src="{{post.Thumbnail.url}}" alt="Card image cap"> {% endif %} <div class="card-body"> <h5 class="card-title">{{post.movie_title}}</h5> <p class="card-text">Released: {{post.release_date}}</p> <a href="{% url 'Movie_detail' pk=post.pk %}"class="btn btn-primary">Watch</a> </div> </div> above i wanted to show the source how On clicking watch site is directed to detail page [Home pageAfter clicking watch -
how do i pre fill a form field with a models object in django
i have two pages profile and add notes. i want to fill the patient field in the add notes form with the users first name whenever i click add notes on any users profile will i need to change the url path? if yes, how do i get the data from the url and fill it in the form. urls.py urlpatterns = [ path('', dashboard, name='dashboard'), path('profile/', profile, name='profile'), path('profile/<str:slug>/<int:pk>', profile, name='profilepk'), path('edit_profile/<int:id>/', edit_profile, name='editprofile'), path('addnotes/', addnotes, name='addnote'), ] views.py def addnotes(request): profile = Profile.objects.get(user_id=id) form = PatientNotesForm(request.POST or None) if form.is_valid(): form.save() return redirect(f'/dashboard/profile/{user.profile.slug}/{user.pk}') return render(request, 'core/addnotes.html', {'form': form}) def profile(request, slug, pk): profil = Profile.objects.get(slug=slug) profile = Profile.objects.get(pk=pk) context = {'profile': profile, 'profil': profil} return render(request, 'dashboard/profile.html', context) models.py class Note(models.Model): illness = models.CharField(max_length=1000, blank=True) patient = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='patientnote', null=True) Doctor = models.CharField(max_length=100, blank=True) Description = models.CharField(max_length=10000, blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.illness}" forms.py class PatientNotesForm(ModelForm): illness = forms.CharField(max_length=100, help_text='First Name') patient = forms.CharField(max_length=100, help_text='Last Name') doctor = forms.CharField(max_length=100, help_text='address') description = forms.CharField(max_length=100,widget=forms.Textarea) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['illness'].widget.attrs.update( {'placeholder': ('illness')}) self.fields['doctor'].widget.attrs.update( {'placeholder': ("Doctor's name")}) self.fields['patient'].widget.attrs.update( {'placeholder': ("Patient's name")}) self.fields['description'].widget.attrs.update( {'placeholder': ("Description")}) self.fields['illness'].widget.attrs.update({'class': 'log'}) self.fields['doctor'].widget.attrs.update({'class': 'log'}) self.fields['patient'].widget.attrs.update({'class': 'log'}) self.fields['description'].widget.attrs.update({'class': 'textarea'}) class Meta: model = … -
channel_layer.group_send not working properly
I'm going along with the channels tutorial and I have the exact same code as mentioned in the documentation's tutorial. It's a simple chat application which echos the message to other connection in the same room. here is my consumer class: # chat/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) the problem is the consumer is sending all messages only to the last connection of the same group. for example if i open 2 browser tabs with /chat/room1/, only the second tab will be able to see the messages. -
Using the user_username instead of user_id to access a user profile
How can I access a model object by their username instead of their id or how can I convert the username into an id that can then be used to access a model object? I have a view like below where the argument that is being passed in is the user_username: views.py def profile_page(request, user_username): form = FollowUserForm(request) profile = Profile.objects.get(user=user_username) return render(request, "network/profilePage.html", { "form": form, "profile": profile }) I know that we can't put the user equal to user_username so is there a way of converting the username somehow into an id which I can then use to access the relevant Profile object? I'm doing it like this because in my urls.py I want the url to show the user's username rather than just a number id. urls.py path("profile/<str:user_username>", views.profile_page, name="profile"), -
How to integrate Zoom services into a django website?
With a website project under construction, the need for 1-to-1 video calls arose. I have decided to use Zoom services for this purpose but I struggle to implement it. Although their docs are extensive, for me it is not clear how to implement it with this framework. I would appreciate any general step by step guidance on this implementation process as well as any links to articles/videos/ etc on this topic. Any guidance will be a great help. -
divide items that belongs to two query sets in django
I have created two querries in django . One that returns number of handled calls per agent and second returns the missed calls per agents. I would like to know how to combine the two queries in order to get a percentage of handled calls par agent, which means take the total from the query3 and divide it on the total of query2 grouped by agent , Of course i will render the result to the web page Here are the two queries Thanks # A query that returns total calls that has been handled queryset2 = CsqAgentReport.objects.values('agentname').filter(Q(originatordnhandeled__contains='1') | Q(missedcallshandeledy_n__contains='1')).exclude(agentname__contains='None').annotate(total=Count('nodeid_sessionid_sequenceno', distinct=True)).order_by('agentname') # A query that returns total calls that has been missed queryset3 = CsqAgentReport.objects.values('agentname').filter(originatordnnothandeled__contains='1').filter(ringtime__gt = '00:00:00').exclude(agentname__contains='None').annotate(total=Count('nodeid_sessionid_sequenceno', distinct=True)).order_by('agentname') -
upstream sent no valid HTTP/1.0 header
I have made a Django project in which I have created a Django-channels app. My chat app is working when I run manage.py run server 0.0.0.0:8000 on the server and works fine but on my IP address i.e. on the website it doesn't work while in Nginx error logs it says - *13 upstream sent no valid HTTP/1.0 header while reading response header from upstream, client: 132.154.xxx.xxx, server: www.website.com, request: "GET /ws/chat/room_id/ HTTP/1.1", upstream: "http://0.0.0.0:6379/ws/chat/room_id/", host: "www.website.com" this is my nginx conf. file- server { server_name www.website.com website.com; client_max_body_size 4G; keepalive_timeout 5; charset utf-8; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/saurabh/thinkgroupy; } location / { proxy_pass http://unix:/run/gunicorn.sock; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; } location /ws/ { proxy_pass http://0.0.0.0:6379; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/website.com/fullchain.pem; # manag> ssl_certificate_key /etc/letsencrypt/live/website.com/privkey.pem; # man> include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot } server { if ($host = www.website.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = website.com) { return 301 https://$host$request_uri; } # managed by … -
Cannot run unit tests in django project. ModuleNotFoundError: No module named 'xxxx'
I started developing some time ago in new project written in django. In tests directory there is Dockerfile, but it takes some time to build everything and run. I Would like to run my tests locally in pycharm, but when i do this then i get it: error description Line in code which raises error looks like that from project.settings import *, but pycharm is ok with it. Structure of the project I suppose that pycharm is ok because src directory is marked as root - thanks to that imports work, but when pytest runs tests it doesn't see src as root. pytest config Theoretically i could change all paths to start from src like from src.project.settings import *, but hundreds of them are in the project, so i think there is better way to resolve this problem