Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'AnonymousUser' object has no attribute 'authenticated'?
I am using Django Version: 3.0.2. Student registration is working and user is saving to database successfully. The problem is after login it is showing 'AnonymousUser' object has no attribute 'authenticated'. Please any one solve my problem? views.py: from django.contrib.auth.models import User, Group, auth def studentregistration(request): if request.method == 'POST': form = StudentRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data['user_name'] password = form.cleaned_data['password'] confirmpassword = form.cleaned_data['confirm_password'] email = form.cleaned_data['email'] if password == confirmpassword: if User.objects.filter(username=username).exists(): messages.error(request,'user already exists please login') return render(request, 'login.html') elif User.objects.filter(email=email).exists(): messages.error(request, 'email already registered please login') return render(request, 'login.html') else: user=User.objects.create_user(username=username, password=password, email=email) user.save() messages.success(request, "Successfully registered, Please login") return render(request, 'login.html') else: messages.error(request, 'password and confirmation password do not match') return render(request, 'studentregistration.html') #return HttpResponseRedirect('studentregistration.html') else: form = StudentRegisterForm() return render(request, 'studentregistration.html', {'form': form}) def login(request): if request.method == 'POST': username = request.POST.get('user_name', '') password = request.POST.get('password', '') user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect('exam_pattern') else: messages.error(request,'invalid credentials') return render(request, 'login.html') else: return render(request,'login.html') Here, i am autheticated user, but i am getting 'AnonymousUser' object has no attribute 'authenticated' after login. def render_questions(request): if not request.user.authenticated: return render(request, 'login.html') else: global exam_session exam_session = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) questions = … -
Django Channels error with received messages
I have a simple chat app example from channels dockerized but im having a problem when i open 2 chats. If i open the first window and send a message, the consumers capture my message and reply to all channels in group (only me at the moment) Normal test Then if i open another window and send a message i receive two messages in the same window (same socket) and not other message in the first window-chat New window and two messages BUT i can send messages from the old window, im just going to see this messages in the new window. No messages from user2 But i send messages, i cant see it and user2 can see it My consumer # 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'] username = text_data_json['username'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username … -
How can i upload a image in database using django?
I have a python code for processing image. What i want now is- I want to upload an image from Webapp using django I want to process the uploaded image. I want to show the final output & store the result in server. can anyone help me with code & details? -
How to have a check that User must Select at least one of the two Foreign Keys in Django Rest Framework
I am trying to make a Django App. I am facing this issue that I need to bound the user to at least select one of the foreign keys. The logic being the user should have his own Idea or he needs to request one of the ideas posted by the teacher. My code looks like this. Models.py class RequestFYP(models.Model): requested_to = models.ForeignKey(Faculty, on_delete=models.CASCADE, related_name='Teacher') requested_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Student_Idea = models.ForeignKey(FYP, on_delete=models.CASCADE, null=True, blank=True) Related_Idea = models.ForeignKey(Idea, on_delete=models.CASCADE, null=True, blank=True) class Meta: verbose_name_plural = 'Requests' def __str__(self): return self.requested_by Serializers.py class RequestFYPSerializer(serializers.ModelSerializer): requested_by = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = RequestFYP fields = '__all__' API.py class RequestFYPView(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = RequestFYPSerializer def get_queryset(self): return RequestFYP.objects.filter(requested_by=self.request.user) def create(self, request, *args, **kwargs): serializer = RequestFYPSerializer(data=request.data) if serializer.is_valid(): serializer.save(requested_by=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Unable to save data into Foreign key fields in Django Rest Framework
I'm working on a project where I have to enroll students in a course. I have a model called Enrollment with two foreign key fields to Course, and Student. I'm trying to save course and student in Enrollment model when they submit. But after calling the save method also response returns a response as course and student are required. My models class Course(models.Model): course_name = models.CharField(max_length=300,default=None) author = models.ForeignKey(TeacherProfile,on_delete=models.CASCADE,null=True,default=None) course_description = models.TextField(null=True) course_cover = models.ImageField(null=True,blank=True,upload_to='course_covers/') def __str__(self): return self.course_name``` class Enrollment(models.Model): enroll_key = models.CharField(max_length=100,default="Text here",null=True) course = models.ForeignKey(Course,on_delete=models.CASCADE,null=True) student = models.ForeignKey(StudentProfile,on_delete=models.CASCADE,null=True) def __str__(self): return self.course.course_name class Meta: unique_together = [['course','student']] Serializer class CourseEnrollSerializer(serializers.ModelSerializer): class Meta: model = Enrollment fields = ['enroll_key','course','student'] My views @api_view(['POST']) @permission_classes([IsAuthenticated]) def EnrollCourse(request,pk): course = Course.objects.get(id=pk) print("course",course) student = StudentProfile.objects.get(user=request.user) print("student",student) serializer = CourseEnrollSerializer(data=request.data) print(serializer) print("loading the serializer...") if serializer.is_valid(): serializer.save(course=course,student=student) else: print("Serializer not valid",serializer.errors) return Response(serializer.errors) urls.py path('enrollcourse/<int:pk>/',views.EnrollCourse,name='enroll_course'), #pk is course primarykey What I get after printing serializer.errors {'course': [ErrorDetail(string='This field is required.', code='required')], 'student': [ErrorDetail(string='This field is required.', code='required')]} -
no module named 'social' when I'm trying to get a new facebook access_token in the postman using my new heroku domain name instead of localhost:8000
There Are The Steps I Followed To get an access_token after pushed my project into heroku I Changed My Site Url Of My App On Facebook from localhost:8000 to https://whispering-hamlet-67095.herokuapp.com/ changed my ALLOWED_HOSTS In Settings.py To ALLOWED_HOSTS = ["localhost","whispering-hamlet-67095.herokuapp.com"] This Step=> ### Testing On PostMan To Get facebook access_token As Usual Like I Used To Do When My Project is Only Running Locally But I Got This error When I Changed The Url From localhost:8000/ to https://whispering-hamlet-67095.herokuapp.com/ So What Should I Do To Use Facebook access_token with my new heroku domain and solve this error And There Are My settings.py code : import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ---------- SECRET_KEY = 'lr2g%2&4666(ghg%&dqhlzcm=f9$5&%q6l*z1+v7vh+khxackr' DEBUG = True ALLOWED_HOSTS = ["localhost","whispering-hamlet-67095.herokuapp.com"] ---------- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'egystoreapp', 'rest_framework_social_oauth2', 'social_django', 'oauth2_provider', 'bootstrap3', ] ---------- MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ---------- ROOT_URLCONF = 'egystores.urls' ---------- TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] ---------- WSGI_APPLICATION = 'egystores.wsgi.application' ---------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } ---------- AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, … -
ModuleNotFoundError: No module named 'mysite' (PythonAnywhere0
I'm trying to deploy my Django site using PythonAnywhere. The steps I followed were from https://help.pythonanywhere.com/pages/DeployExistingDjangoProject/ This is the code in my WSGI File This is what it says in my error log -
Using Django Rest Framework to initiate data processing on the backend
I have a fully functioning Django application and I am now adding an API using Django Rest Framework. I will creating a React front end which will use the API provided via DRF. I have worked out how to use DRF to create endpoints for my models using ModelViewSets and ModelSerializers. These work fine. I now need to create an endpoint that initiates some data processing. The endpoint will need to accept a date as input and then call some code to do the processing. My standard Django application currently does this by accepting a date via a Django form and then initiating a celery task. Here is the view: class GenerateRosterView(LoginRequiredMixin, FormView): """Generate Roster View.""" template_name = "generate_roster.html" form_class = GenerateRosterForm def get_form_kwargs(self): """Pass request to form.""" kwargs = super().get_form_kwargs() kwargs.update(request=self.request) return kwargs def get_success_url(self): """Get success URL.""" return reverse("roster_generation_status", args=(self.task_id,)) def form_valid(self, form): """Process generate roster form.""" start_date = form.cleaned_data["start_date"] self.request.session["start_date"] = start_date.date().strftime( "%d-%b-%Y" ) result = generate_roster.delay(start_date=start_date) self.task_id = result.task_id return super().form_valid(form) Here is the form: class GenerateRosterForm(forms.Form): """Generate Roster Form.""" def __init__(self, request, *args, **kwargs): """Get default start date from session.""" super().__init__(*args, **kwargs) if "start_date" in request.session: start_date = datetime.datetime.strptime( request.session["start_date"], "%d-%b-%Y" ) else: start_date = … -
Django - How can I set a Model's field using the existance of a ForeignKey as a condition?
I am trying to create a Django app where there are two main models - Team and Person. A Person can use the app as an User or can belong to a Team, and, in that case, the User will be the Team. class Team(models.Model): name = models.CharField(max_length=50) team_user = models.ForeignKey( User, on_delete = models.CASCADE, null = True, blank = True ) class Person(models.Model): person_user = models.ForeignKey(User, on_delete = models.CASCADE, null = True, blank = True) team = models.ForeignKey( Team, on_delete = models.CASCADE, null = True, blank = True ) I am trying to develop a File structure like this: /root /Team_01 /Person_01 (non-User) /files.csv /Person_02 (non-User) /files.csv /Person_03 (User) /files.csv I have read the documentation and I was trying to do something with the comment from Evgeni Shudzel in this post, but my problem is that I don't know how to set the file's path for the Person model so that if the Person is member of a Team, the path is "/team_id/person_id" and if not, the "/team_id" part is excluded. The pseudocode I have in mind: if Person.team exists: files = models.FileField(upload_to="TEAM_ID/PERSON_ID/") else: files = models.FileField(upload_to="PERSON_ID/") How can I implement this pseudocode? Thank you! -
django alternative to prevent header poison
Firstly I don't speak English very well, but anyway... i know I need to use allowed_hosts, but I need to use all "*" and a header attack can cause something like: <script src = "mysite.com/js/script.js"> <script> to <script src = "attacker.com/js/script.js"> <script> or mysite.com/new_password=blabla&token=blabla8b10918gd91d1b0i1 to attacker.com/new_password=blabla&token=blabla8b10918gd91d1b0i1 But all static files are load on a nodejs server "cdn.mysite.com" and all domains are in the database, so I always take the domain from the database to compare with the request header, and use the domain from the database of data to send anything to the client: views.py: def Index(request): url = request.META['HTTP_HOST'] cf = Config.objects.first() if cf.domain == url: form = regForm() return render(request, 'page/site/home.html', {'form': form}) elif cf.user_domain == url: ur = request.user.is_authenticated if ur: config = {'data' : request.user} lojas = 'json.loads(request.user.user_themes)' return render(request, 'app/home.html', {"config":config, "lojas":lojas}) else: forml = loginForm() return render(request, 'page/users/login/login.html', {'form':forml}) else: redirect("//" + cf.domain) Would that still be unsafe to use this way? -
Show product instance in Django UpdateView with Select Boxes
I need to show the product instance in the select boxes. I am very sure I followed the get_object and get_initial method pretty well but the form does not seem to initiate with the product I want to update. Any other way to do this? Model: class Order(models.Model): options = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) status = models.CharField(choices=options, null=True, max_length=200) def __str__(self): return self.status class Meta: ordering = ['-date_created'] My View: class OrderUpdateView(UpdateView): model = Order form_class = OrderUpdateForm template_name = 'crmapp/update-order.html' context_object_name = 'order' success_url = '/' def get_initial(self): initial = super(OrderUpdateView, self).get_initial() content = self.get_object() initial['customer'] = content.customer initial['product'] = content.product initial['status'] = content.status return initial def get_object(self, *args, **kwargs): product = get_object_or_404(Order, pk=self.kwargs['pk']) return product The Url: path('update-order/<str:pk>/', OrderUpdateView.as_view(), name='update-order') The HTML <div class="container"> <div class="row"> <div class="col-sm-6 offset-3"> <br><br><br><br> <form action="{% url 'update-order' order.pk %}" method="POST"> {% csrf_token %} {{ form.as_p}} <button class="btn btn-primary btn-block" type="submit">Save</button> </form> <br><br><br><br> </div> </div> -
How to get a users lat and long via button press in Django?
I'm in the process of trying to create an app that can grab a users lat and long when a button is press/clicked. I plan on storing the lat and long inside of a model field for each individual press/click. Only to be used later on inside of an interactive map, displaying every lat and long that has been stored. Looking into Leaflet or Google Maps API to implement a map. I've read the Django documentation on GeoIP2 and I think it may be my best option but I'm not sure if there are any better options? As far as implementing GeoIP2 goes, it's really as simple as what I have below, correct? from django.contrib.gis.geoip2 import GeoIP2 g = GeoIP2() lat,lng = g.lat_lon(user_ip) model_field_example_lat = lat model_field_example_lng = lng -
Django migrate rollback multiple migrations on failure
Django migrations has excellent behavior in terms of single migrations, where, assuming you leave atomic=True, a migration will be all-or-nothing: it will either run to completion or undo everything. Is there a way to get this all-or-nothing behavior for multiple migrations? That is to say, is there a way to either run multiple migrations inside an enclosing transaction (which admittedly could cause other problems) or to rollback all succeeded migrations on failure? For context, I'm looking for a single command or setting to do this so that I can include it in a deploy script. Currently, the only part of my deploy that isn't rolled back in the event of a failure are database changes. I know that this can be manually done by running python manage.py migrate APP_NAME MIGRATION_NUMBER in the event of a failure, but this requires knowledge of the last run migration on each app. -
I want to get an ID from the URL and query my data. Django Rest Framework
I am making a Marvel based API and I want to get the ID from the url and query the fields from that ID. my models.py: class Characther(models.Model): name = models.CharField(max_length=100) comics = models.TextField() events = models.TextField() series = models.TextField() stories = models.TextField() my views.py class CharList(generics.ListCreateAPIView): queryset = Characther.objects.all() serializer_class = CharSerializer def get(self, request, id): id = request.GET.get('id', '') return render(request, self, {'comics': get_object_or_404(comics, pk = id)}) class ComicList(generics.ListCreateAPIView): queryset = Characther.objects.filter().values('name', 'comics') serializer_class = ComicSerializer class EventsList(generics.ListCreateAPIView): queryset = Characther.objects.filter().values('name', 'events') serializer_class = EventsSerializer class SeriesList(generics.ListCreateAPIView): queryset = Characther.objects.filter().values('name', 'series') serializer_class = SeriesSerializer class StoryList(generics.ListCreateAPIView): queryset = Characther.objects.filter().values('name', 'stories') serializer_class = StorySerializer my url : urlpatterns = [ url(r'^v1/public/characters/(?P<id>[\w-]+)/', views.ComicList.as_view(), name = 'comics') ] -
how to make green color body using using is_grater_priority
`class Todolist(models.Model): title = models.CharField(max_length=255) detail = models.TextField(max_length=255, null=True, blank=True) created = models.CharField(max_length=255) is_grater_priority=models.BooleanField(default=False)` i have done this, but not working Now what should i do to make this workable ` {% if list %} {% for obj in list %} {% if obj == is_grater_priority %} <p class="text-success"><strong>Title:- </strong> {{obj.title}} </p> <p class="text-success"><strong>Details:- </strong> {{obj.detail}} </p> <p class="text-success"><strong>Sheduled:- </strong> {{obj.created}} </p> <a href="{% url 'todolist:edit_todolist' obj.id %}">Edit</a> <a href="{% url 'todolist:delete_todolist' obj.id %}">Delete</a> <hr> {% else %} <p><strong>Title:- </strong> {{obj.title}} </p> <p><strong>Details:- </strong> {{obj.detail}} </p> <p><strong>Sheduled:- </strong> {{obj.created}} </p> <a href="{% url 'todolist:edit_todolist' obj.id %}">Edit</a> <a href="{% url 'todolist:delete_todolist' obj.id %}">Delete</a> <hr> {% endif %} {% endfor %} {% else %} <h2>No list avilable</h2> {% endif %}` -
How to Append in Loop using Selenium
def show(request): driver = webdriver.Chrome('/Users/colegulledge/desktop/chromedriver') driver.get('https://www.horrycounty.org/bookings') sleep(random() + 2) date_form = driver.find_element_by_id('txtBookingDate') ##we are going to loop through the start date-end date in this input box def daterange(start_date, end_date): for n in range(int((end_date - start_date).days)): yield start_date + timedelta(n) start_date = date(2020, 1, 1) end_date = date(2020, 1, 3) def change_date_format(dt): return re.sub(r'(\d{4})/(\d{1,2})/(\d{1,2})', '\\2-\\3-\\1', dt) ##to change the format to month-day-year for single_date in daterange(start_date, end_date): days = (single_date.strftime(format("%Y/%m/%d"))) days = (change_date_format(days)) date_form.send_keys(days) sleep(2) ##Changing the date format and using send keys we put in in the inputbox for el in days: search = driver.find_element_by_css_selector("span.btn-primary") driver.execute_script("arguments[0].click();", search) sleep(2) inmate_info = driver.find_elements_by_class_name("cellLarge") rs = [] for p in range(len(inmate_info)): rs.append(inmate_info[p].text.strip()) date_form.clear() print(rs) ##the website keeps the previous date in the input box, so we must ##clear the input box and repeat the loop return HttpResponse(rs) So whenever I do this, rs is only returning the last day of records.. I believe my function is not appending to the list, instead it is replacing it. This may be obvious, but I am an inexperienced and working on my first major project. Any ideas/suggestions? Thanks -
Ajax data manipulation when transmitting to Django CBV
I'm using django-autocomplete-light with the select2 "select multiple" widget for a M2M form. I have it set up to enable "Create New" when the input is not found. However, my model has additional required fields beyond the initial input of the "select multiple" widget. I am trying to create a way to prompt the user for the additional fields when trying to create, and then sending that data through ajax to my django view. Right now, if I pre-supply the other required fields within my view, the user can create a new object with the name that they've entered (and clicked "Create New") for, and the other fields will be determined in my view. This shows me that the code is working, but ideally I'd like to prompt the user for the additional data. I have created a prompt, however I cannot the correct syntax for transmitting the data. As an example, pretend I have a model with required fields "Name" and "Location". On the Select2 widget, the user types a "Name" which doesn't exist as an object, and clicks "Create New". Now, I'd like the script to prompt them for the location, then transmit that in as a get_or_create … -
Django Stripe Payment Responds with Invalid Parameter after clicking Submit Payment button
I am working on an e-commerce project that requires stripe payment gateway. It is my first time to work on an application that requires stripe payment. I am a junior programmer. I am working on my localhost machine, I have tried to debug the code but i have failed to see where the problem is. @Hacker86 got the solution but has not shared it can anyone help me with the problem. This is the link of the same problem Stack I tried to solve the problem with the solution in the replies to above the question but all was in veil. So please can anyone help immediately reply me. Below is my relevant Code base.py import os from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__)))) SECRET_KEY = config('SECRET_KEY') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_framework', 'drf_yasg', 'crispy_forms', 'django_countries', 'core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'perfectfits.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = … -
django-tables2: Change column header link
I have created a table using django-tables2, and it displays correctly with verbose names displaying in the column headers. Each of the column headers is a link to sort the column, but as far as I can tell there is no way to change the link href: <th class="orderable"> <a href="?sort=column_name">Verbose Name</a> </th> I have found ways to edit the attributes of the <th> tag, but I can't find a way to edit the href parameter on the <a> tag wrapping the column header text. I have multiple tables I'd like to display, and I'd like to use different paths for updating each different table. Is there a way to update the Table or Column class to customize the URL used when clicking on the column header text? -
Redirect non ajax requests to DRF endpoint
I want to prohibit direct access to the endpoints. If I was using Django's CBV I'd simply add if not request.is_ajax(): return redirect... to the view. Now how would I achieve the same with DRF, specifically with viewsets and generic mixins? Should I overwrite get methods? If so, are there more elegant ways? -
After creating login and registration page HTML and CSS how to take user input and save to data base?
I'm currently making a website and have created both the HTML and CSS for both the registration and login Pages - I'm wanting to use Django to save the information, I'm just a bit confused on how to take the user input (using my html inputs) and then transferring them to the Django data base. I'm very new to web development as you can tell - I'm just trying to take it one step at a time. /* This is the style sheet for the Registration Page only */ body { background-color: rgba(255,0,0,0.65); } h2 { color: white; font-family: optima; font-size: 300%; font-weight: 500; font-variant: small-caps; line-height: 200px; height: 200px; z-index: 0; margin-top: -50px; } h3 { color: white; font-family: Helvetica; font-size: 250%; font-weight: 400; font-variant: small-caps; margin-top: 50px; } #rectangle{ top: 20px; display: inline-block; width:450px; height:550px; background:rgba(43, 43, 43, 1); transform: translate(-50%,-50%); border-radius: 15px; position: absolute; z-index:-5; top: 550px; } img { opacity: 0.8; display: block; margin-left: auto; margin-right: auto; background-repeat: no-repeat; } div { text-align: center; padding: 0; } label{ color:white; font-family:Helvetica ; display: block; text-align: center; padding-bottom: 10px; } select{ font-family:Helvetica ; background-color: lightgrey; text-align: center; margin: 0 auto; display: block; padding: 50; } span { color:white; … -
certbot and apache domain name trouble
I have deployed a django web application on a linux server using ubuntu 20.10 and apache2. My site was working well before I added certbot. However, after I ran the certbot commands for apache2 and ubuntu 20.04 (because 20.10 was not listed) my site only works for for first time users who put www.my_domain_name.com. When they just put my_domain_name.com in it serves them the default apache ubuntu page which is clearly not what I want. My idea was to use rewrite conditions and rules to send them to the www. version if they try to access it without that but everytime I do that an error occurs. The only rewrite rule I have is below and Server_Name is set to www.my_domain_name.com at the top of the .conf file. Can you help me write a rewrite rule to always send them to the https version and to the www. version or give me advice on how to get the non www. version to serve up the proper page with https? Also it is worth noting that when I try to open the non www. version in my browser it works fine, but when a first time user trys it it does … -
Can't load link postgreSQL to Django
I've created a new Django project in my virtual environment and installed psycopg2. I changed my settings.py file to the following: DB_NAME = "neighborhood" DB_USER = "django" DB_PASSWORD = "password" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, 'HOST': 'localhost', 'PORT': '5432', } } But when I run python manage.py migrate in my virtual enviorment, I get the following error: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: DLL load failed while importing _psycopg: The specified module could not be found. I'm using python v3.9 and postgreSQL v13. I checked other posts on Stack Overflow but none answered my problem. Thanks. -
django-filter according to the logged user
I am using the django_filters to filtering the information. However, it is showing the data of all regitered user of my system. I need show only the data of logged user. Follow the files: filters.py import django_filters from apps.requisitos.models import Requisito class RequisitoFilter(django_filters.FilterSet): class Meta: model = Requisito fields = ['nomeRequisito', 'projeto'] views.py class RequisitoList(ListView): paginate_by = 10 model = Requisito def get_queryset(self): usuarioLogado = self.request.user return Requisito.objects.filter(user=usuarioLogado) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = RequisitoFilter(self.request.GET, queryset=self.queryset) return context the loop for of html page {% for requisito in filter.qs %} thank you very much -
Saving database changes with django channels
I wish to make simple programme in django channels - I open Websocket and then listen for users clicking a button or pressing any key down. If such event occurs JS sends message to Channels where it gets access to db where there is a model of a counter, increment it depends it was click or key, and then send it back to group on layers. Unfortunately, error occurs. Why it calls contex error if I already used database_sync_to_async My consumers.py : from channels.generic.websocket import AsyncWebsocketConsumer import json from channels.db import database_sync_to_async from .models import Licznik class MyConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = 'main_room' self.counter = await database_sync_to_async(self.get_counter)() await (self.channel_layer.group_add)( self.room_group_name, self.channel_name ) await self.accept() def get_counter(self): return Licznik.objects.all()[0] async def receive(self, text_data): if text_data == "klik": self.counter.klik +=1 elif text_data == "klak": self.counter.key += 1 await database_sync_to_async(self.counter.save()) #error here klik = self.counter.klik klak = self.counter.key await (self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'klik': klik, 'klak': klak } ) async def chat_message(self, event): message_klik = event['klik'] message_klak = event['klak'] await self.send(text_data=json.dumps({ 'klik': message_klik, 'klak': message_klak })) async def disconnect(self, close_code): await (self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) await self.close() Error: Exception inside application: You cannot call this from an async context - use …