Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Api not serving media files to reactJS client-side
I am working on a React & Django project, I have built a Django API that stores video and also some text whenever I try to render the video by the client-side it does not render the video. The first problem that I came across is was the API was not giving me the correct full path it gave me this: video: "/media/lectures/mat105-Part2.mp4" So I then tried to resolve that by modifying the path to http://127.0.0.1:8000/api${content.video} Code to my API Models class LectureVideos(models.Model): lecturer = models.CharField(max_length=100, blank=False, null=False) module = models.CharField(max_length=100, blank=False, null=False) video = models.FileField(upload_to='lectures') date = models.CharField(max_length=100, blank=False, null=False) Code to my API VIEWS @api_view(['GET']) def getLectureVideos(request): videos = LectureVideos.objects.all() serializer = LectureVideoSerialzer(videos, many=True) return Response(serializer.data) Code to my client-side where I try to retrieve the data class Video extends Component { constructor(props) { super(props); this.state = { lectureVideos: [], }; this.getVideos = this.getVideos.bind(this); } componentDidMount() { this.getVideos(); } getVideos() { const url = "http://127.0.0.1:8000/api/videos-list/"; axios .get(url) .then((response) => { this.setState({ lectureVideos: response.data, }); }) .then((res) => { console.log("Fetch Successful"); }) .then((res) => { console.log(this.state.lectureVideos); }) .catch((error) => { console.log(error); }); } render() { return ( <div className="Video__container"> <VideoList listvideos={this.state.lectureVideos} /> </div> ); } } export default Video; … -
Creating an Inline Formset - Foreign Key Issue
I have the following 2 models that I want to use in a form set. I'm not sure what I've got wrong models.py class AppTradingPartnerTrp(models.Model): id_trp = models.AutoField(primary_key=True) tpid_trp = models.CharField(max_length=50, blank=True, null=True) name_trp = models.CharField(max_length=50) description_trp = models.CharField(max_length=100, blank=True, null=True) idtrn_trp = models.ForeignKey('AppTransmissionTrn', models.DO_NOTHING, db_column='idtrn_trp', blank=True, null=True) class AppCustomerTpRel(models.Model): id_rel = models.AutoField(primary_key=True) idcst_rel = models.ForeignKey(AppCustomerCst, models.DO_NOTHING, db_column='idcst_rel') idtrp_rel = models.ForeignKey(AppTradingPartnerTrp, models.DO_NOTHING, db_column='id_trp') cust_vendor_rel = models.CharField(max_length=50, blank=True, null=True) sender_id_rel = models.CharField(max_length=50, blank=True, null=True) old_vendor_rel = models.CharField(max_length=50, blank=True, null=True) vendor_name_rel = models.CharField(max_length=50, blank=True, null=True) category_rel = models.CharField(max_length=50, blank=True, null=True) And here is where I'm trying to create the formset: forms.py CstVendorNoFormSet = inlineformset_factory(AppCustomerTpRel, AppTradingPartnerTrp, exclude=()) However when I do runserver I'm getting: ValueError: 'AppTradingPartnerTrp' has no ForeignKey to 'AppCustomerTpRel'. -
Switch language on Django app keep languagecode/current_path_app
I have integrated switch button to change language on my django site. I have some apps. I don't want to redirect to home, instead of keep languagecode/current path this is my view.py in home app #function switch language def change_language(request): response = HttpResponseRedirect('/') if request.method == 'POST': language = request.POST.get('language') if language: if language != settings.LANGUAGE_CODE and [lang for lang in settings.LANGUAGES if lang[0] == language]: redirect_path = f'/{language}/' elif language == settings.LANGUAGE_CODE: redirect_path = '/' else: return response from django.utils import translation translation.activate(language) response = HttpResponseRedirect(redirect_path) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language) return response -
Get the last inserted time for more then one modal class in DRF
I am trying to get the response inserted time of more then one modal class and send in the response in DRF. For example, my modal class is: class FeedVehicle(models.Model): sensor = models.ForeignKey( 'SensorDevice', on_delete = models.CASCADE ) feed = models.TextField() created_at = models.DateTimeField(auto_now_add=True) class FeedElsys(models.Model): sensor = models.ForeignKey( 'SensorDevice', on_delete= models.CASCADE ) feed = models.TextField(null=True) created_at = models.DateTimeField(auto_now_add=True) I was writing the view as such but not able to succed class LastFeedAPIView(generics.ListAPIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAdminUser, permissions.IsAuthenticated,) serializer_class = serializers.DashboardSerializer def get(self, request, format=None): weather_r712 = models.FeedVehicle.objects.all().order_by('-id')[:1] weather_r712_searlializer = serializers.SignalFeedSerializer(weather_r712, read_only=True) weather_r718 = models.FeedElsys.objects.all().order_by('-id')[:1] weather_r718_serializer = serializers.WeatherR718FeedSerializer(weather_r718, read_only=True) response = {"r712":weather_r712_searlializer.data, "r718":weather_r718_serializer} return Response(response) I want to get the response of both modal last inserted time. I have created the serializer class But not sure how I will connect and get the response. Any Suggestions. -
How to check if data exists or not in Django rest framework
I have a CartModel, CartItem model. I trying to do when I create a cart and when the cart is get created and again I add the same data as I enter in pervious it create another cart. I trying to do that if the cart exists in the CartItem table it has to show the response "Cart already exists". But it is creating another cart. I search a lot and use the code but it will not run. If somebody is capable of giving an answer the please help me. views.py* class CartTestViewSet(viewsets.ModelViewSet): serializer_class = CartItemSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user if user.is_authenticated: if user is not None: if user.is_active and user.is_superuser or user.is_Customer: return CartItem.objects.all() raise PermissionDenied() raise PermissionDenied() raise PermissionDenied() def post(self, request): cart = Cart.objects.filter(user=request.user, cart=request.data, service=request.data, defects=request.data) if cart.exists(): print('cart already exists') else: print('cart is created') serializers.py from rest_framework import serializers from .models import CartItem, CartModel from rest_framework.response import Response class CartItemSerializer(serializers.ModelSerializer): def get_total(self, obj): return obj.get_total get_total = serializers.IntegerField(read_only=True, required=False) # id = serializers.IntegerField(read_only=False) class Meta: model = CartItem fields = "__all__" extra_fields = ['get_total'] read_only = ['get_total'] class CartModelSerializer(serializers.ModelSerializer): class Meta: model = CartModel fields = "__all__" models.py from django.db … -
How can i use asgi completely in django?
I'm new to django. After searching here and their i found asgi enable performance boost over django wsgi based view. So that i want to completely switch to asgi view but i din't found any guides regarding to it so that i can i implement it in views(function and class) and django orm. And also I'm pretty much unsure about how it works. If this question make no any sense, then sorry for that and help me regarding to asgi which is new features in django3. How it is different from django channel. -
Logger in django not printing on console or saving in file when applied inside api
I am trying to implement logging into my application. I have written the logging config in settings.py as LOGGING = { 'version': 1, # Version of logging 'disable_existing_loggers': False, # disable logging # Handlers ############################################################# 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'logs/log.log', }, ######################################################################## 'console': { 'class': 'logging.StreamHandler', }, }, # Loggers #################################################################### 'loggers': { 'django': { 'handlers': ['file', 'console'], 'level': 'INFO', 'propagate': True, }, }, } Now I used the logger in my API as: import logging . . . log = logging.getLogger(__name__) class GetDataStores(generics.RetrieveAPIView): def retrieve(self, request, *args, **kwargs): . . log.info('sample log message') . . This is neither printing anything on the console nor writing in the file -
How to deploy a Django app on a private cloud?
I am working on one django app and would like to find a way to deploy it on the cloud for testing purposes. As the app is for my own purposes, and not totally secure, I don`t want it to make it available on the internet. Apart buying a PC server and install it at home, what are the options to deploy the app and keep pushing some modifications to it? Many Thanks, -
vim recover a deleted swap file
I deleted the swap file and lost the modifications. The *.bash file returned to it original version. Is it possible to undo delete of the swap file (i.e., recover or restore the deleted *.bash.swp file)? -
Django urlpatterns issue
I am working from the Python Crash Course from no starch by Eric Matthes. I am having an issue with include(). The error I am receiving in command prompt is: django.core.exceptions.ImproperlyConfigured: passing a 3-tuple to include() is not supported. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead. Here is my code: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', include('learning_logs.urls', namespace='learning_logs')), ] -
Is it possible to put a model's admin page in the "Authentication and Authorization" section?
At the moment this model's admin page shows up in the "App" section of the admin site (in admin.py): from app.models import Role class RoleAdmin(admin.ModelAdmin): class Meta: model = Role filter_horizontal = ('group',) admin.site.register(Role, RoleAdmin) Is it possible to add this to the "Authentication and Authorization" section instead? -
Save strings (separated by virgola) directly into a django field
I have a html file as follow: <form method="POST" action="" id="dropdownform" enctype="multipart/form-data"> <fieldset class="form-group"> {% csrf_token %} <div class="content-section"> <div class="card-body"> {{ form.categories }} </div> </div> <div class="content-section"> <p class="text-muted" id="showtags"> // Tags will appear here </p> </div> </fieldset> <div class="form-group mt-7"> <button class="btn btn-primary" type="submit">Submit</button> </div> </form> <script> // here there is a JS code which returns the selected categories as tags into <p> </script> This is my model: class Post(models.Model): categories = models.ForeignKey(Categories, blank=True, null=True, on_delete=models.CASCADE) tags = models.TextField(blank=True, null=True) class Meta: db_table = "posts" def get_tags(self): if self.tags: return self.tags.split(",") else: None There is a dropbbox form that when user changes categories, a function in scripts returns tags and they will be appeared as a long string which separated by virgola. I need to save these values in tags field as separated strings. I don't know exactly how to tell django field should take that field after submitting the form! -
Trigger Django Action in Wagtail Equivalent
I'm trying to figure out how to trigger a custom Django action in Wagtail. Essentially trying to run a custom function in some way from the UI in Wagtail. I looked into the ButtonHelper / PageButtonHelper helpers, but it looks like that just allows you to navigate to a url. I'm looking for something very similar to Django Actions in Wagtail. Does anyone know if this is possible, or there's some equivalent in Wagtail? Thanks. -
What is the correct way of setting the Action attribute in a Django form
I have an html form in a Django system and I cannot find the correct way to implement the Action attribute in the form html <form action="stages" method="post"> urls.py urlpatterns = [ path('<str:partner_pk>/stages/', views.Stages.as_view(), name="stages"), ] views.py class Stages(View): """CBV for setting stages.""" url = 'duo/stages.html' def get(self, request, partner_pk): app.context['partner_pk'] = partner_pk return render(request, self.url, app.context) def post(self, request, partner_pk): """Render the POST request.""" stages_selected = app.update_stages(request) if app.context['use_stages'] and not stages_selected: messages.error(request, 'You have not selected any stages.') return render(request, f'{partner_pk}', app.context) else: return HttpResponseRedirect(reverse(f'duo/{partner_pk}/')) The error I get on clicking submit is: RuntimeError at /duo/2/stages/stages You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set... I have tried various other urls in action but the all give an error message -
Django creating super user error: AttributeError: 'ProfileManager' object has no attribute 'create_superuser'
Hi I am trying to create a superuser, however, after I added my own ProfileManager I get the error: AttributeError: 'ProfileManager' object has no attribute 'create_superuser' But my issue is should BaseUserManager already have this method? I cannot find a why to inherit the create_superuser method. My manager is: class ProfileManager(BaseUserManager): pass And my model is: class Profile(AbstractUser): objects = ProfileManager() Thanks for all the help in advance! -
The project doesn't load on Django with Ubuntu VPS, after gunicorn, supervisor and nginx settings [closed]
Hello everyone I ran into a problem, made all settings on the server, checked gunicorn, started the project directly with the command gunicorn Superman.wsgi: application --bind 0.0.0.0:8001, the site started, but without static files. Next, I installed supervisor, also made a separate configuration for it and configured nginx, when checking supervisor sudo supervisorctl status Superman the server replied that it works, when checking nginx sudo nginx-t the server also responds positively successful, but when I score the IP of my site in the browser search bar, the site does not load, the error is Site 91.228.152.32 does not allow you to establish a connection, the nginx logs are empty. What might be the problem, maybe I'm setting proxy_pass incorrectly? I attach the settings below, ASK for HELP in SOLVING the PROBLEM, I'm looking for a solution for a day and nothing(( Setup Gunicorn NAME="Superman-test" DJANGODIR=/webapps/Superman-test/Superman SOCKFILE=/webapps/Superman-test/run/gunicorn.sock GROUP=www-data NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=Superman.settings DJANGO_WSGI_MODULE=Superman.wsgi echo "Starting $NAME as `whoami`" cd $DJANGODIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- Setup Supervisor [program:Superman] command = sh /webapps/Superman-test/bin/gunicorn_start user = root … -
Django admin: How to get path of uploaded file
I have created model field for User Pic and User_pic_url, what i'm trying to do is when i upload image it's path should get populated in user_pic_url. Note that i'm uploading image from django admin itself. any idea. snapshot for ref: Snapshot Model.py: class Main(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=100) about = models.TextField() contact = models.CharField(default='0', max_length=12) email = models.CharField(default='-', max_length=50) linkedin = models.CharField(default='-', max_length=50) github = models.CharField(default='-', max_length=50) site_name = models.CharField(default='-', max_length=50) resume = models.FileField() cover_letter = models.FileField() user_pic = models.ImageField() user_pic_url = models.TextField(default="-") -
How to upload my django website to godaddy
I bought a hosting and already have the domain, however, the website is not showing up, the people over at godaddy told me that it is a code issue so I dont know what I have to change in setting.py or something, everything there is like the default -
Django error logging only working in debug mode
When getting a django.request error my logging only writes into the log file when running with DEBUG=True. With DEBUG=False nothing gets written. Here is my LOGGING definition: def skip_static_requests(record): if record.args[0].startswith('GET /static/'): # filter whatever you want return False return True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, 'skip_static_requests': { '()': 'django.utils.log.CallbackFilter', 'callback': skip_static_requests, }, }, 'formatters': { 'verbose': { 'format': "%(asctime)s [%(schema_name)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/var/log/mylog.log', 'filters': ['skip_static_requests'], 'formatter': 'verbose' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'filters': ['require_debug_false'], }, 'null': { 'class': 'logging.NullHandler', }, }, 'loggers': { 'django.security.DisallowedHost': { 'handlers': ['null'], 'propagate': False, }, 'django': { 'handlers': ['file', 'mail_admins'], 'propagate': True, 'level': config('LOG_LEVEL', default='INFO'), }, 'django.request': { 'handlers': ['file', 'mail_admins'], 'propagate': True, 'level': 'ERROR', } } } Anyone who has a clue what could be wrong? My feeling is that it has nothing to do with the LOGGING definition. -
The domain IIS is overwriting the Subdirectory
I have an site in IIS, lets say www.example.com (Laravel application) , and i have my subdirectory www.example.com/subdirectory (Django application), when i access the /subdirectory, the domain overwrite my subdirectory and I get 404 page of Laravel, I tried to make an rule in web.config of domain but i didn't get results, and I don't know what to So, this is my configs in main.settings( Django) USE_X_FORWARDED_HOST = True FORCE_SCRIPT_NAME = '/subdirectory/' SESSION_COOKIE_PATH = '/subdirectory/' LOGIN_REDIRECT_URL='/subdirectory/' LOGOUT_REDIRECT_URL='/subdirectory/' VIRTUAL_DIRECTORY = "subdirectory/" ALLOWED_HOSTS = ['example.com', 'localhost', 'wwww.example.com'] and my urlpatterns in main.urls urlpatterns = [ path(f'{settings.VIRTUAL_DIRECTORY}admin/', admin.site.urls), # path('password_change/', views.password_change, name='password_change'), path(f'{settings.VIRTUAL_DIRECTORY}', include('django.contrib.auth.urls')), path(f'{settings.VIRTUAL_DIRECTORY}', views.index, name='index'), path(f'{settings.VIRTUAL_DIRECTORY}aluno/', include('aluno.urls')), path(f'{settings.VIRTUAL_DIRECTORY}empresa/', include('empresa.urls')), ] -
How to solve this djando OneToOneField model error?
I'm trying to make a model that needs a relationship of one to one with a feedstock that is used by a plenty of formulas. This is my code: from django.db import models from dashboard.models import Formulas, Feedstock class FeedstockFormulas(models.Model): ratio = models.FloatField() feedstock = models.OneToOneField(Feedstock, on_delete=models.CASCADE, default="0") formulas = models.ForeignKey(Formulas, on_delete=models.CASCADE) This is the error I'm getting: Traceback (most recent call last): File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 798, in __init__ to._meta.model_name AttributeError: module 'dashboard.models.Feedstock' has no attribute '_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/mnt/c/Users/isaac/Documents/Github/uniaoracoes/dashboard/models/__init__.py", line 1, in <module> from .Formulas import Formulas File "/mnt/c/Users/isaac/Documents/Github/uniaoracoes/dashboard/models/Formulas.py", line … -
Django Regex Validator Not Working - Error 500 Deployment Server
Take the following example: class ProjectForm(forms.Form): client = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Client Name (lowercase)'}),validators=[RegexValidator(r'^[a-z]+$', 'Enter a valid client name (only lowercase letters)')]) stage = forms.ChoiceField(choices=TYPES) folder = forms.ChoiceField(choices=FOLDERS, required=False, label='') purpose = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Project Purpose (lowercase; digit optional)'}),validators=[RegexValidator(r'^[a-z-]+[1-9]?$', 'Enter a valid purpose (only lowercase letters, with a single optional digit)')]) computeapi = forms.BooleanField(required=True, initial=True, label='Compute Engine') deploymentmanapi = forms.BooleanField(required=False, label='Deployment Manager') storagecompapi = forms.BooleanField(required=False, label='Storage Components') monitorapi = forms.BooleanField(required=False, label='Monitoring') loggingapi = forms.BooleanField(required=False, label='Logging') def clean(self): form_data = self.cleaned_data projectname = form_data['client'] + "-" + form_data['stage'] + "-" + form_data['purpose'] client = form_data['client'] purpose = form_data['purpose'] for projectdict in projectdicts: if projectname == projectdict['name']: raise ValidationError(projectname + " already exists! Please try another name.") if not re.match("^[a-z-]+[1-9]?$", purpose): raise ValidationError(purpose + " does not comply with the Regex parameters.") if not re.match("^[a-z]+$", client): raise ValidationError(client + " does not comply with the Regex parameters.") return form_data The ValidationError for projectname works perfectly fine as expected. However, it's not working for Regex, and instead keeps throwing a 500 error. Is there something we need to do specifically to get the RegexValidator to work as expected within the class variables? I don't believe my additional code in the clean is needed (and if it … -
AttributeError at /add/4/ 'Item' object has no attribute 'filter'
I'm getting error AttributeError at /add/4/ 'Item' object has no attribute 'filter' at if order.item.filter(item__id = item.id).exists(): I'm trying add Items based on the ids in to cart. The item is being added in the cart table but showing above error. my views.py @login_required(login_url='/login/') def add_to_cart1(request, id): item = get_object_or_404(Item, id=id) order_item, created = CartItem.objects.get_or_create( item=item, user=request.user, ) order_qs = CartItem.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.item: if order.item.filter(item__id = item.id).exists(): order_item.quantity += 1 order_item.save() messages.success(request, "Item qty was updated.") return redirect("ItemAddedToCart") else: order.item.add(order_item) messages.success(request, "Item was added to your cart.") return redirect("ItemAddedToCart") else: order = CartItem.objects.create( user=request.user, ) order.item.add(order_item) messages.success(request, "Item was added to your cart.") return redirect("ItemAddedToCart") my models.py class CartItem(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) item = models.ForeignKey(Item, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True ,null=True) updated_at = models.DateTimeField(auto_now=True ,null=True) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) -
Update django form maintaining expiration time
this is my first post on this life-saving community. I recently started studying django, using 3.1 right now. My main problem is about maintaining a field from a form after the update. Using: form = TodoForm(request.POST, instance=todo) I can see all the fields, except from the expire one in wich i see dd/mm/yyyy (the default from the date picker) At the moment, to take expire field, I use bootstrap_datepicker_plus. Do you need more code to see what I'm doing wrong? Any idea? -
Python calling a function that creates directory does not work as expected
I am calling a function inside my Django view. The code works but not when calling the function inside the view. I have simplified the code. import os def MakeDir(path): try: os.mkdir(path) #... some more logic... except OSError as e: print(e) def MydjView(request): MakeDir('/tmp/year') #function call but directory is not created return HttpResponse('okay')