Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework in some prebuild methods , so how do I create my own method ? After creating my own method how to use it in code
I have created my own method using the Django rest framework Similar to some prebulid methods in the Django rest framework --->get, post, and another prebulid method. so how can I create my own method? I try to create my own method, but I don't know how to write it. -
How to use Valentina or DBeaver to load/import a .sql dump file (from the development version of a website) to the local version on my computer?
I have a .sql file which is a dump of the data coming from the development version of a website. I want to use that data in the local version of the website's Django backend running on my desktop I can see it at localhost:8000 but in the docker-compose.yml file the db is located at port 5432. What are the steps I need to do using Valentina or DBeaver to load in the data such that that data is what I see in Valentina or DBeaver ? I've already tried loading the dump through right-clicking the name of the database then choosing load dump from the options but I still don't see any data in the database tables. -
Django Table - Single Row if Item is unique
Is there a way to get all the amounts on a single row in HTML if "category name" is unique? According to my code, "category name" is no longer unique because it is being annotated by month. Thank you Data: HTML Output: I want them to be all in one row since they are "Car Payment" class CashFlow(LoginRequiredMixin, AccountContextMixin, TemplateView): model = Transaction template_name = 'transaction_app/cf.html' context_object_name = 'transaction' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.request.user #-------Dropdown Begins--------- #Get unique years for dropdown distinct_years = Transaction.objects.filter(user=user).dates('transaction_date', 'year') year_choices = [(date.year, date.year) for date in distinct_years] unique_years = list(set(year_choices)) unique_years.sort() context['unique_years'] = unique_years #-------Dropdown Ends----------- #---Get Data From Dropdown Begins--------- selected_year = self.request.GET.get('selected_year') selected_year = int(selected_year) if selected_year else datetime.now().year selected_status = self.request.GET.get('selected_status') #---Get Data From Dropdown Ends----------- #----Get Data for Table Begins------------ # Obtain distinct category names category_names = Transaction.objects.filter( user=user, transaction_date__year=selected_year, status=selected_status ).values_list('category__category_name', flat=True).distinct() # Aggregate data for each distinct category category_sums = [] for category_name in category_names: # Aggregate total amount for each month within the specified year for the current category category_sum_by_month = Transaction.objects.filter( user=user, transaction_date__year=selected_year, status=selected_status, category__category_name=category_name ).annotate( month=ExtractMonth('transaction_date') ).values('month').annotate( total_amount=Sum('amount') ) # Append category name and its monthly sums to category_sums list for … -
Will I need a consumers.py, asgi,py and routing.py using Tradier's websocket API?
So I'm trying to stream market data via the tradier API with websockets. Here are 2 links to the docs: https://documentation.tradier.com/brokerage-api/streaming/websocket-streaming https://documentation.tradier.com/brokerage-api/streaming/wss-market-websocket I'm not too familiar with websockets, so I'm wondering if I need to use django channels and add a consumers.py, asgi.py, and routing.py to stream this market data live to a front end? If the answer is yes, what would I need to add in each of these files? I've tried just having a consumers.py and having the streaming endpoint in urls.py consumers.py: import json import logging import websockets from channels.generic.websocket import WebsocketConsumer from .tradingAPI.tradier import tradierFunctions logger = logging.getLogger(__name__) class TradierStreamConsumer(WebsocketConsumer): async def connect(self): await self.accept() logger.info("WebSocket connection established") uri = "wss://ws.tradier.com/v1/markets/events" async with websockets.connect(uri, ssl=True, compression=None) as websocket: payload = { "symbols": ["SPY", "NVDA"], "sessionid": tradierFunctions.createStreamingSession(), "filter": ["quote"], "linebreak": "true" } await websocket.send(json.dumps(payload)) logger.info(f"Sent payload: {payload}") async for message in websocket: logger.info(f"Received message: {message}") await self.send(text_data=json.dumps({"message": message})) urls.py: urlpatterns = [ ... path('api/tradier/stream', TradierStreamConsumer.as_asgi()), ] I expected continuous JSON data being streamed to the web page, but in reality I get this: Also, this is my console output when I log the info: -
"<Model: ModelInstance>" needs to have a value for field "id" before this many-to-many relationship can be used
Currently getting this error between my UserProfile model and Song model when I try to get all user songs "song = user_prof.songs.all()" and error is the title "<UserProfile: ...>. This is my first time using a through model for two models (Song and Note) and am suspicious. The UserProfile, Song, Notes, and SongNotes instances are all saved and viewable in django admin, however the song_instance does not show any notes, in fact it doesnt even show its notes field im guessing due to the through. Song View class Songs(APIView): def post(self, request, format=None): try: data = self.request.data user_song = data['song'] name = data['name'] user = self.request.user user_prof = UserProfile.objects.get(user=user) song_instance = Song.objects.create(name=name) user_prof.songs.add(song_instance) user_prof.save() for index, pair in enumerate(user_song): note = Note.objects.create(note=pair[0], timestamp=pair[1]) song_note_through = SongNote.objects.create(song=song_instance, note=note, order=index) song_instance.save() return Response({ 'success': 'Song created' }) except Exception as e: print('Songs:post ', e, file=sys.stderr) return Response({ 'error': 'Unable to create song' }) def get(self, request, id='all', format=None): try: if id == 'all': user = self.request.user user_prof = UserProfile(user=user) song = user_prof.songs.all() else: song = Song.objects.get(id=id) serializer = SongSerializer(song) return Response({ 'song': serializer.data}) except Exception as e: print('Songs:get ', e, file=sys.stderr) return Response({ 'error': 'Unable to get song' }) models.py class UserProfile(models.Model): … -
WordPress blog in Subdirectory of Django site on cPanel
I've gone through several similar posts here on StackOverFlow but I can't get it to work. What I want to achieve is to load any url that contains /blog/ with WordPress. I have moved my WordPress instance into a folder called blog (inside public_html) and it loads fine when the Django instance is not active with this .htaccess file in public_html. I have no .htaccess file in the blog folder. <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{HTTP_HOST} ^(www.)?mysite.com$ RewriteCond %{REQUEST_URI} !^/blog/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /blog/$1 RewriteCond %{HTTP_HOST} ^(www.)?mysite.com$ RewriteRule ^(/)?$ blog/index.php [L] </IfModule> I also changed the WordPress URL and Site Address in the database to mysite.com/blog/ with https:// When I activate the Django instance, I change the .htaccess file to the below. <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_URI} ^/blog/ RewriteCond %{HTTP_HOST} ^(www.)?mysite.com/blog/$ RewriteRule . /blog/index.php [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . / [L] </IfModule> # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/usr/mysite.com" PassengerBaseURI "/" PassengerPython "/home/usr/virtualenv/mysite.com/3.11/bin/python" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END # DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION BEGIN <IfModule Litespeed> SetEnv DEBUG False etc... </IfModule> # DO NOT REMOVE OR MODIFY. … -
ConnectionRefusedError Errno 111 when Django uploaded to Godaddy Server
I dont have any problem in Local host when sending and reciving emails. But when I uploaded the files to the godaddy server, I am getting error when I am trying to send email. I spoke to godaddy support, but it was not helpful. Can someone please let me know the issue. #error ConnectionRefusedError at /support/python python [Errno 111] Connection refused # settings.py BASE_URL = 'https://www.example.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER = 'support@example.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'support@example.com' EMAIL_FROM_NAME = 'Support' # in views.py email = EmailMessage( subject, message, settings.EMAIL_HOST_USER, [recipient], reply_to=[request.user.email] # Set the reply-to address ) email.send() Thanks. -
How can one enable a mix of authenticated and unauthenticated websockets using Django Channels?
I'm running a Django application with DRF and Channels and I've configured a number of websockets, one of which I need to be open/insecure. However, all I can figure out is how to enable/disable security at the application level, not at the consumer specific level. Here is the asgi.py configuration: application = ProtocolTypeRouter( { "http": django_application, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_routing.websocket_urlpatterns)) ) } ) Alternatively, to disable the authentication, I can switch the websocket entry to URLRouter(websocket_routing.websocket_urlpatterns) With the DRF views, its easy enough to disable authentication: class WebhookCallEvents(APIView): authentication_classes = [] permission_classes = [] But these properties don't seem to work in a consumer class: class MyConsumer(AsyncWebsocketConsumer): authentication_classes = [] permission_classes = [] How would one enable authentication for some websockets but have it disabled for others within the same application? Looks like this is a duplicate of this question over here: Django Channels 2 websockets multiple AuthMiddlewareStacks However, none of the answers are accepted, so perhaps restating the question will yield some results. -
Django: Views and URLs Configured, but Pages Not Found (404 Error) - only /admin shows
I'm encountering an issue with my Django project. I've set up views and URLs for several pages like 'landing', 'chat', 'impressum', 'sales', 'team', and 'user'. However, when I try to access these pages in the browser, I receive a 404 error indicating that the pages cannot be found. Here's the relevant code I've implemented: from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.landing, name='landing'), path('chat/', views.chat, name='chat'), path('impressum/', views.impressum, name='impressum'), path('sales/', views.sales, name='sales'), path('team/', views.team, name='team'), path('user/', views.user, name='user'), ] # views.py from django.shortcuts import render def landing(request): return render(request, 'landing.html') def chat(request): return render(request, 'chat.html') def impressum(request): return render(request, 'impressum.html') def sales(request): return render(request, 'sales.html') def team(request): return render(request, 'team.html') def user(request): return render(request, 'user.html') # settings.py import os TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'teacherassistant/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', ], }, }, ] Despite correctly defining URLs and views, I'm unable to render the respective HTML templates for each page as intended. It seems like there's an issue with how Django is handling the routing.[enter image description here]enter image description here -
Django makemessages i got no such file directory error
(myenv) C:\Users\Boss\OneDrive\İş masası\Onlineshop>py manage.py makemessages -l ru CommandError: errors happened while running msguniq msguniq: error while opening "C:\Users\Boss\OneDrive\Is masasi\Onlineshop\myenv\Lib\site-packages\rosetta\locale\django.pot" for reading: No such file or directory In ubuntu server it works but in local i got this error -
Django reverts model value saved by form in POST (Ajax) when I call query by GET (Ajax)
I have a screen with a datatable with the data and I update the values using ajax and then reload it, but in some cases I save the value through a post request, and then when I make a new query to update the screen using get, the changed values are reverte without any error. View class ManualGetView(View): # get by which I query all values to show in the datatable def get(self, request): items = ConfiguracaoManual.objects.all().order_by('endereco') data = [item.to_dict_json(get_permissoes(RAIZ, request.user)) for item in items] response = {'data': data} return JsonResponse(response) class ManualAltView(View): def get(self, request, request_id): item = ConfiguracaoManual.objects.get(pk=request_id) data = item.get_data() response = {'status': 200, 'data': data} return JsonResponse(response) # post where I update the values def post(self, request, request_id): if request_id: model = ConfiguracaoManual.objects.get(pk=request_id) form = ManualForm(request.POST, instance=model) else: form = ManualForm(request.POST) if form.is_valid(): instance = form.save() # instance.save() if not request_id: Auditoria(usuario=request.user, modelo=RAIZ, mensagem=SUCESSO['incluir']).save() response = {'status': True, 'msg': SUCESSO['incluir']} else: Auditoria(usuario=request.user, modelo=RAIZ, mensagem=SUCESSO['incluir']).save() response = {'status': True, 'msg': SUCESSO['incluir']} else: if not request_id: Auditoria(usuario=request.user, modelo=RAIZ, mensagem=ERRO['alterar']).save() response = {'status': False, 'msg': ERRO['alterar'], 'erros': form.errors} else: Auditoria(usuario=request.user, modelo=RAIZ, mensagem=ERRO['alterar']).save() response = {'status': False, 'msg': ERRO['alterar'], 'erros': form.errors} return JsonResponse(response) JS Script //Function used to update by … -
Django - Create a model that holds aggregated Foreign Key values
I have a Django Model defined as a ServiceEvent, and another defined as Part. class ServiceEvent(Model): date = DateTimeField(null=False, blank=False, db_column='date', default=datetime.now()) vehicle = ForeignKey(Vehicle, on_delete=models.CASCADE) description = TextField(null=True, blank=False, db_column='description') # The contents of the notifications to create for this event. notification_contents = TextField(null=True, blank=False, db_column='notification_contents') # The mileage the event should occur. target_mileage = DecimalField(max_digits=10, decimal_places=2, null=True, blank=False, db_column='target_mileage') # The mileage at the time of the event. event_mileage = DecimalField(max_digits=10, decimal_places=2, null=True, blank=False, db_column='event_mileage') class Part(Model): part_number = CharField(max_length=100, null=False, blank=False, db_column='part_number') description = CharField(max_length=100, null=False, blank=False, db_column='description') price = DecimalField(max_digits=10, decimal_places=2, null=False, db_column='price') service_event = ForeignKey(ServiceEvent, on_delete=models.CASCADE) Since there can be multiple Parts per ServiceEvent, is there a way to store a column in the ServiceEvent table that contains the price of all of the parts added up that belong to a given event? I would like to do this for efficiency however I'm not sure if there is a better approach (like using a mapping table, which may still lead to the same question about the column). FYI: I'm using SQLite currently. Thanks! -
Heroku - Django - How to reduce cool down of keep alive
I have an API that creates a model object whenever an action is true. Slight problem, everytime the API sends some data it creates a connection and these connections dont seem to cool down very quickly. Connections seem to stay on for more than 60 minutes. This results in getting the following error: too many connections for role xxx As a result, I implemented the following code in my prod.py: from .base import * from decouple import config import django_on_heroku # Heroku Settings django_on_heroku.settings(locals(), staticfiles=False) # Adjust database settings import dj_database_url DATABASES['default'] = dj_database_url.config(conn_max_age=450, ssl_require=True) This was implemnted following Heroku's guidlines : https://devcenter.heroku.com/articles/python-concurrency-and-database-connections What I was hoping to achieve here was to have connections lasting a maximum of 45 seconds. (users dont need to spend more than 20 seconds on the site to get what they need). I seem to be missing something. Would you be able to shed some lights? Is there a better practice to ensure connections do not reach their limit? Edit: worth mentioning, I am on the Basic plan. Planning to move to Standard0 when ready for production. I am assuming the plan shouldnt affect the ability to define keep alives. -
Django How to Have an Internal Link on Custom Button Component
I am on DjangoCMS 3.11.3. I am not a Django developer, I primarily do .Net but was asked to help out with CSS and HTML. That went well, so now we are here... We currently have an imported Bootsrap4 Link/Button component that has far more options than the PM wants and than what the end users need. This imported plugin has 2 levels to the Internal Link and the 2nd level is hierarchical (indented) as show below: I seem to be able to have an internal link created in my custom Button component, but it only has a single dropdown of pages (each has a duplicate for some reason, the values of th duplicates are different if that means anything) and they are not indented (hierarchical) at all. I have been googling and such with no real success. I was able to dig into the repos and such to get some of the source code but it was getting insanely deep how far the spaghetti code was going. This is where you come in. I just want a simple component that lets the user pick a page within the CMS. I understand why all of the inheritence and such is … -
Django ORM: Case When not working when output is a Subquery producing a list of Ids?
I've been spending an incredible amount of time today on something I don't understand at all. Let me explain: I have a code similar to this one: puzzle_sequence__puzzles = <a subquery> puzzle_sequence__puzzles_3d = <another subquery> MyModel.objects.add_only_3d_puzzle_sequence().exclude(puzzle__in=Case( When(Q(only_3d_puzzle_sequence=True), then=Subquery(puzzle_sequence__puzzles_3d)), default=Subquery(puzzle_sequence__puzzles) )) which throws an error sqlite3.OperationalError: near "CASE": syntax error django.db.utils.OperationalError: near "CASE": syntax error or django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CASE WHEN CASE WHEN (`games_play`.`puzzle_sequence_id` IS NOT NULL AND CASE W...' at line 1") depending if I'm on sqlite3 or MariaDB server I've been toying with it for some while now, and it seems that's it's really the Case When statement which raised the issue as both the following statements work well: MyModel.objects.add_only_3d_puzzle_sequence().exclude(puzzle__in=Subquery(puzzle_sequence__puzzles_3d)) MyModel.objects.add_only_3d_puzzle_sequence().exclude(puzzle__in=Subquery(puzzle_sequence__puzzles)) I however don't understand at all why my Case When statement would fail Is there a specific issue if the output_field of a Case When statement should be a list of objects or list of object ids ? PS: as you can see, I'm not using Postgres, so I guess I cannot force output_field=ArrayAgg Thanks in advance -
QUALIFY on a non-window field
As stated here, from 4.2 Django supports fIltering against a window function. I've tried it and Django successfully creates a QUALIFY clause when using a window field in the filter clause. However, if using, let's say, a model field, the predicate is assigned to the WHERE clause. That arises the next problem: qs.annotate( position=Window( expression=RowNumber(), order_by=order_by ) ) obj = qs.get(id=obj.id) # obj.position will always be 1, as WHERE is run before QUALIFY -
This Customer doesn't have any saved payment details
def checkout_payment(request): if request.method == "POST": user = request.user cart_items = Cart.objects.filter(user=user, is_ordered=False) cart_total = sum(float(item.product.discounted_price()) * item.quantity for item in cart_items) # Convert cart_total to the smallest currency unit and then to integer total = int(cart_total * 100) stripe.api_key = settings.STRIPE_SECRET_KEY try: customer = stripe.Customer.create( email=request.user.email, name=request.user.first_name, description='Example charge', ) # payment_intent = stripe.PaymentIntent.create( # ) # creating charge charge = stripe.Charge.create( customer=customer, amount=total, currency="PKR", description='Payment has been charged successfully', source=request.POST.get('stripeToken') ) print(charge) messages.info(request, 'Payment has been successfully') return redirect('checkout_complete') except Exception as e: print(e) return render(request, 'checkout_payment.html') this is my code and why i am getting this error This Customer doesn't have any saved payment details. Attach a legacy Token, Card, Bank Account, or Source to this Customer and then try this request again, or use Payment Intents and Payment Methods instead. -
KeyError in django when i try to migrate
everytime i try to migrate i get KeyError: ('komaki', 'msg') Traceback (most recent call last): File "C:\Users\EXO\Downloads\Compressed\mathematics-main_2\mathematics-main\maths\manage.py", line 22, in <module> main() File "C:\Users\EXO\Downloads\Compressed\mathematics-main_2\mathematics-main\maths\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\commands\makemigrations.py", line 211, in handle loader.project_state(), ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\loader.py", line 361, in project_state return self.graph.make_state( ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\graph.py", line 329, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\migration.py", line 91, in mutate_state operation.state_forwards(self.app_label, new_state) File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\operations\models.py", line 384, in state_forwards state.remove_model(app_label, self.name_lower) File "C:\Users\EXO\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\state.py", line 128, in remove_model del self.models[model_key] ~~~~~~~~~~~^^^^^^^^^^^ KeyError: ('komaki', 'msg') why is thi happening -
Django annotate and filter
This is a follow up to a previous question but I will include all the detail here. I'm creating a game where one of the elements is that players vote for each other. Here are the models I've set up (relevant fields only) #models.py class Game(models.Model): gamecode = ShortUUIDField(length=4, max_length=4, unique=True) phasenumber = models.IntegerField(default=1) isActive = models.BooleanField(default=True) class Player(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) isPlaying = models.BooleanField(default=True) class PlayerVote(models.Model): byplayer = models.ForeignKey(Player, on_delete=models.CASCADE) forplayer = models.ForeignKey(Player, on_delete=models.CASCADE, related_name="voteforplayer") gamephasenumber = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) When a user joins a game, they get an entry in the "Player" model. When they cast a vote for another player, an entry is added to the "PlayerVote" model showing which player voted (byplayer), who they voted for (forplayer), and the phase that the game is in (gamephasenumber) (this is just an integer that increases each phase of the game) What I'd like to do is create a QuerySet which contains each player and how many votes they got in this phase of the game. I can do the below to get the votes they've received for all phases playerswithvotes = Player.objects.select_related('game').filter(game = activegame.game, game__phasenumber = activegame.game.phasenumber, isPlaying = True).annotate(votesreceived=Count('voteforplayer')).order_by('-votesreceived') But how … -
Converting to SQLAlchemy from Django ORM in Django Rest Framework
I have a DRF application. I have it written in Django Rest Framework. For database handling, I have used Django's Builtin ORM. Let me explain my project structure. I have a django project named TourReview. Inside TourReview I have an app named review. Here are my key files: review/models.py : from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator # Create your models here. class PlaceInfoModel(models.Model): TYPE_CHOICES = [ ('Beach', 'Beach'), ('Hill', 'Hill'), ('Fountain', 'Fountain'), ('Landmark', 'Landmark') ] owner = models.ForeignKey('auth.User', related_name='review', on_delete=models.CASCADE, default=1) name = models.CharField(max_length=60) address = models.CharField(max_length=300) rating = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(5)]) type = models.CharField(max_length=20, choices=TYPE_CHOICES) image = models.ImageField(upload_to='uploads/') review/serializers.py: from .models import PlaceInfoModel from rest_framework import serializers class PlaceInfoSerializer(serializers.ModelSerializer): class Meta: model = PlaceInfoModel fields = ['id', 'name', 'address', 'rating', 'type', 'image'] read_only_fields = ['owner'] reviews/views.py: from django.shortcuts import render from .serializers import * from .models import * from rest_framework.decorators import APIView from rest_framework import viewsets from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication from rest_framework.permissions import IsAuthenticatedOrReadOnly from .custom_permission import IsPermittedForAction from django.contrib.auth.views import LogoutView from .serializers import * from rest_framework.pagination import LimitOffsetPagination from rest_framework.filters import OrderingFilter class PlaceModelViewSet(viewsets.ModelViewSet): queryset = PlaceInfoModel.objects.all() serializer_class = PlaceInfoSerializer authentication_classes = [SessionAuthentication] permission_classes = [IsPermittedForAction,IsAuthenticatedOrReadOnly] pagination_class = LimitOffsetPagination filter_backends = … -
website not able to become responsive in django
body, html { height: 100vh; margin: 0; padding: 0; } .part1 { position: relative; width: 100%; height: 100%; background-color: black; display: flex; justify-content: space-between; } .tt { margin-top: 20px; margin-left: 20px; width: fit-content; height: fit-content; animation: slideInLeftTt 1s ease forwards; /* Animation for tt */ } @keyframes slideInLeftTt { 0% { transform: translateX(-100%); opacity: 0; } 100% { transform: translateX(0); opacity: 1; } } .txt2 { font-size: 35px; animation: slideInUpTxt2 1s ease forwards; /* Animation for txt2 */ } @keyframes slideInUpTxt2 { 0% { transform: translateY(100%); opacity: 0; } 100% { transform: translateY(0); opacity: 1; } } .txt { font-size: 64px; animation: slideInUpTxt 1s ease forwards; /* Animation for txt */ } @keyframes slideInUpTxt { 0% { transform: translateY(100%); opacity: 0; } 100% { transform: translateY(0); opacity: 1; } } .txt1 { font-size: 25px; animation: slideInUpTxt1 1s ease forwards; /* Animation for txt1 */ } @keyframes slideInUpTxt1 { 0% { transform: translateY(100%); opacity: 0; } 100% { transform: translateY(0); opacity: 1; } } .A1 { height: 100%; width: fit-content; color: white; display: flex; flex-direction: column; font-family: 'Baskerville Old Face', serif; } .pv { margin-top: 140px; margin-left: 200px; height: fit-content; width: fit-content; } .image { max-width: 100%; max-height: 100%; } .logo-container … -
Django Admin "Export selected" button not showing in Admin
I'm trying to enable the "Export selected" button in the Django admin for users to download data as an Excel sheet. I'm using django-import-export but the button isn't appearing. Here's what I've done: Installed django-import-export (pip install django-import-export). Trial 1: class UserAdmin(ImportExportModelAdmin): list_display = ('username', 'email'....) admin.site.unregister(User) admin.site.register(User, ImportExportModelAdmin) Trial 2: class UserAdmin(ExportMixin, admin.ModelAdmin): list_display = ('username', 'email'.....) admin.site.unregister(User) admin.site.register(User, UserAdmin) Restarted the development server. the django-import-export is in INSTALLED_APPS in settings.py Expected behavior: The "Export selected" button should appear in the Django admin user list view. Actual behavior: The button is not displayed. My Question: Why the button is not showing and how can I fix it. Any suggestions or insights into why the button might not be showing would be greatly appreciated. -
Django, Settings module not found on YouStable hostings
I have been deploying django websites on a shared hosting platform (YouStable). With my latest attempt I get a 500 server error page, because it can’t find the settings file. Background I did previously manage to deploy a site that worked. I deleted that when I had problems because I had chosen app names that conflict with reserved words and I also discovered I could pip install the Bootstrap web framework (although I need to sort this issue first). I have since had problems creating a new site. I reported a problem when the hosting server was trying to run code from a virtual environment connected to a previous site ( the site and venv have been deleted). The hosting support techies have fixed that. What I did. The procedure for deployment involves creating a Python ‘app’ in CPanel's ‘Setup Python app’ by; selecting a Python version (I chose 3.11), choosing a name (‘myapp’), selecting the domain name and saving the app. This creates a virtual environment (or venv) using my username (‘username’), the app name and the Python version. For me: /home/username/virtualenv/appname/3.11/ CPanel then displays the code to select and activate this venv for use in the terminal section … -
slider input ranges in html with min and max values inside a table and a for loop
I'm a newbie and battling my first issues with Django, html, js and so on.. I wonder if anyone can help me out here. I have a page where you must enter a series of ranges of attendances and prices for a movie center. If you purchase entrances to a movie if you go to the movies once you pay 8, if you plan to go from 2 to 5 times you pay 20 but if you plan to go 6 to 10 times you pay 30. what I'm getting is this The thing is that the list will grow every time you make a new range of prices. I can forsee someone adding another range from 11 to 20 times and paying 35$. ` #visit range <th scope="col">Precio</th> <th></th> </tr> </thead> <tbody> {% for cuota in cuotas %} <tr> <td><input name="range" id="range" min="0" max="100" value="0" type="range"></div> <td><a class="price">{{ cuota.price }}</a></td> <td style="text-align: right"> <button type="button" class="btn btn-secondary btn-xs text-align-right"><i class="fas fa-edit"></i></button> <button type="button" class="btn btn-secondary btn-xs"><i class="fas fa-trash-alt"></i></button> </td> </tr> {% endfor %} </tbody> </table> </div> </div>` The thing here is that the list will grow and I should have an unique ID for each slider and so on. … -
type object 'Project' has no attribute 'objects'
I use django version 5.0.3. And got this error : type object 'Project' has no attribute 'objects'. from django.db import models from account.models import User import uuid # # Create your models here. class Project(): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) description = models.TextField(blank=True,null=True)#not required created_by = models.ForeignKey(User,related_name = 'projects',on_delete=models.CASCADE)#pass in User object def __str__(self): return self.name from django.contrib.auth.decorators import login_required from django.shortcuts import render,redirect from .models import Project # Create your views here. @login_required def projects(request): projects = Project.objects.filter(created_by=request.user) return render(request,'project/projects.html',{ 'projects':projects }) when I "make migrations project" I got this message No changes detected in app 'project' and when I "python manage.py migrate" I got this message Operations to perform: Apply all migrations: account, admin, auth, contenttypes, sessions Running migrations: No migrations to apply. Not sure what happened here