Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting trouble in django-admin setup
PS C:\Users\laveen\pycharmprojects\DjangoCourse> django-admin django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 django-admin + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
Recieve and use JWT token/Token in Web Socket using django-channels
What I need to know? I want to receive JWT Token while connecting in web socket. I want to use JWT token. What I am using? django for project. django-channels for implementing Web Socket. -
How to delete a Django model object automatically after 24 hrs
I am new to django. I want to delete a model object automatically after the specific time. This is my model i want to delete class CustomerOrder(models.Model): order_types = ( ('dinein','Dinein'), ('delivery','Delivery'), ('pickup','Pickup') ) restaurant = models.ForeignKey(RestaurantDetail,on_delete=models.CASCADE,null=True) customer_name = models.CharField(max_length=30,null=True) table_no = models.IntegerField(null=True) total_price = models.FloatField(null=True,blank=True) success = models.BooleanField(default=False,blank=True,null=True) status = models.CharField(max_length=15,default='pending',null=True) ordered_menu = models.ManyToManyField(OrderedMenu) timestamp = models.DateTimeField(default=datetime.datetime.now()) order_type = models.CharField(max_length=15,default='dinein',choices=order_types) the timestamp is the saved time of the current object. is any idea about how to delete a model object automatically after the specific time? (example after 24 hrs). -
Please help me to figure out where is the actual bugs, I did correctly but didn't get to work as expected
{% extends 'main.html' %} {% load static %} {% block content %} {% if page == "register" %} <h1>Hello This is register Page!!!</h1> <form method="POST" action="{% url 'register' %}"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Register" /> </form> <p>Aready have an account <a href="{% url 'login' %}"> Login </a></p> {% else %} <div class="auth"> <div class="card"> <div class="auth__header text-center"> <a href="/"> <img src="{% static 'images/icon.svg' %}" alt="icon" /> </a> <h3>Account Login</h3> <p>Hello Developer, Welcome Back!</p> </div> <form action="{% url 'login' %}" method="POST" class="form auth__form"> {% csrf_token %} <!-- Input:Email --> <div class="form__field"> <label for="formInput#text">Username: </label> <input class="input input--text" id="formInput#text" type="text" name="username" placeholder="Enter your username..." /> </div> <!-- Input:Password --> <div class="form__field"> <label for="formInput#password">Password: </label> <input class="input input--password" id="formInput#passowrd" type="password" name="password" placeholder="••••••••" /> </div> <div class="auth__actions"> <input class="btn btn--sub btn--lg" type="submit" value="Log In" /> <a href="forgetpassword.html">Forget Password?</a> </div> </form> <div class="auth__alternative"> <p>Don’t have an Account?</p> <a href="{% url 'register' %}">Sign Up</a> </div> </div> </div> {% endif %} {% endblock content %} and here is the error I have been taking Udemy course "Learn to build awesome websites with Python & Django!" by Dennis Ivy and I have reached almost middle of the course but when I reached here I was badly … -
get more than two foreign keys from another django table and perform calculations on them
In the Django app, I have created two tables. Product Invoice I have one table called Product which contains product name and product price columns are given. Then, I have a second table named Invoice which contains a product name(foreign key), product price(foreign key), discount, and total. My concern is how can I import both the values from the Product table i.e. product name and product price and perform calculations on them. The structure is given below: myapp -> PRODUCT: *Product Name *Product Id *Product Price INVOICE: *Product Name (foreign key) *Product Id (foreign key) *Product Price (foreign key) *Discount *Total = Product Price - Discount how can I import values and perform further calculations? -
Changing the opacity of the colour on the Polar Area chart
I am using Chart.js to create a set of polar area charts, I want to change teh opacity of the colour used to display the data so it is slightly transparent. Below you will find the code: var totals = {{ class_submission_totals|safe }} {% for t in type_qs %} var labels_{{ t.pk }} = [] var backgroundColors_{{ t.pk }} = [] {% for b in behaviour_qs %} {% if b.type.pk == t.pk and not b.previous %} labels_{{ t.pk }}.push("{{ b.title }}") backgroundColors_{{ t.pk }}.push("{{ b.primarycolour }}") {% endif %} {% endfor %} {% endfor %} new Chart("chart_{{ i.pk }}_{{ t.pk }}", { type: "polarArea", data: { labels: labels_{{ t.pk }}, datasets: [{ fillOpacity: 0.3, pointRadius: 1, backgroundColor: backgroundColors_{{ t.pk }}, data: totals_{{ i.pk }}_{{ t.pk }}_arr, }] }, options: { responsive: false, maintainAspectRatio: true, plugins: { legend: { display: true, }, title: { display: false, text: 'Chart.js Polar Area Chart' } } } }); {% endfor %} {% endfor %} -
django html: copy form input data and display in another page
I am trying to develop a delivery service web where users can input pickup and delivery address in the form and get the price online. if the price is fine, the user can click "place order" button which will navigate into another new page for user to fill in additional information, and importantly the previously input piackup and delivery addresses and the price will need to automatically shown somewhere in the new page. I am new to django and html, and I have tried to created a simpler page serving the same purpose. Now I could do the first part of form filling, and the backend calculate based on the user input and return the calculation result (e.g. price). Now, I am wondering how to do the "navigation to another new page which will display the two input values and calculation result" Main html: <html> <body> <form method="POST" hx-post="{% url 'blog:post_list' %}" hx-target="#num_1" hx-target="#num_2" hx-target="#result"> {% csrf_token %} <div> <label>num_1:</label> <input type="text" name="num_1" value="" placeholder="Enter value" /> </div> <div> <label>num_2:</label> <input type="text" name="num_2" value="" placeholder="Enter value" /> </div> <br /> <div id="num_1">{{ num_1 }}</div> <br /> <div id="num_2">{{ num_2 }}</div> <br /> <div id="result">{{ result }}</div> <br> <button type="submit">Submit</button> </form> … -
there is a problem in the login part of my project [closed]
my form is not working for some reason. that is, it does not give the expected result my views.py def TeacherLogin(request): if request.method == 'POST': form = TeacherLogin(data = request.POST) if form.is_valid(): user = authenticate(username=username, password=password).first() # user = User.objects.filter(username=username).first() if user is not None: return redirect('home') else: form = TeacherLogin() my forms.py class TeacherLoginForm(ModelForm): class Meta: model = User fields = ('username', 'password') my urls.py #in apps from django.urls import path, include from .views import * app_name = 'teachers' urlpatterns = [ path('teacherlogin/', TeacherLogin, name='teacherlogin'), ] -
How to programmatically make a user to assign permissions on template?
As you all know django admin has a function to give "Permissions" for user on their admin panel ! How to do that programmatically ? For example lets say i have a super user and the user can create staff users under them as multiple roles. And how to allow him to assign or add roles when the super user creates a profile on custom build admin panel ( am not asking for djago admin, am asking for custom own built admin panels) -
How I get the time zone of logged user by using Django?
I want to manage(such as Change the default language) the country region details of in my Django website. Does anyone have a best way to do that? -
Prefetch_related with filter for m2m
I'm trying to build a queryset to find candidates who has apply for a job_type, knows some languages and he wants to work in some zones. I'm able to select candidates based on job_type_ an d languages but my query doesn't filter by zones. : { "jobtype_id": 15, "languages": [21,83], "zones": [1,2,4] } This is my queryset: candidates = Candidate.objects.all().prefetch_related('job_types', 'languages').filter( job_types__id=job_type_id, languages__id__in=filter_languages).prefetch_related( Prefetch('job_types__candidate_job_type_zone', queryset=CandidateJobTypeZone.objects.all().filter(zone_id__in=filter_zones)), ) This is the SQL generated (i want an inner join to candidate_job_type_zone table and filter by zone id): SELECT `candidates`.`name`, `candidates`.`firstname`, `candidates`.`lastname`, `candidates`.`phone_number`, `candidates`.`secondary_phone_number`, `candidates`.`profession`, `candidates`.`own_car`, `candidates`.`driver_licence`, `candidates`.`location`, `candidates`.`document_type`, `candidates`.`document_id`, `candidates`.`work_permit`, `candidates`.`prefer_language`, `candidates`.`is_promoted`, `candidates`.`last_promoted_payment_date`, `candidates`.`is_active_job_search`, `candidates`.`last_active_job_search_date`, `candidates`.`created_at`, `candidates`.`updated_at`, `candidates`.`extra_data`, `candidates`.`user_id`, `candidates`.`nationality_id` FROM `candidates` INNER JOIN `candidates_jobs_types` ON (`candidates`.`user_id` = `candidates_jobs_types`.`candidate_id`) INNER JOIN `candidates_languages` ON (`candidates`.`user_id` = `candidates_languages`.`candidate_id`) WHERE (`candidates_jobs_types`.`job_type_id` = 15 AND `candidates_languages`.`language_id` IN (21, 83)) These are may models: class Candidate(models.Model): ... # relations user = models.OneToOneField( User, on_delete=models.CASCADE, null=False, verbose_name="Usuario relacionado", primary_key=True) job_types = models.ManyToManyField('JobType', through="CandidateJobType") languages = models.ManyToManyField(Language, through="CandidateLanguage") class CandidateJobType(models.Model): candidate = models.ForeignKey( Candidate, verbose_name="Candidato", on_delete=models.CASCADE) job_type = models.ForeignKey( JobType, verbose_name="Puesto de trabajo", on_delete=models.CASCADE, related_name='job_types') extra_data = models.JSONField(verbose_name="Datos extras", null=True) zones = models.ManyToManyField(Zones, through="CandidateJobTypeZone") is_active = models.BooleanField(verbose_name="Is active", null=True, default=True) class Meta: db_table = "candidates_jobs_types" unique_together = ('candidate', 'job_type') class … -
Multiple FeaturedPost on HomePage Using Wagtail
I haven't seen any question like this on the site. So hopefully this question will be useful for others in the future. I have a PostPage, EditorialPage, and DocumentPage. Within the models of the three, I added a 'featured' Boolean, so that if toggled in the settings, either Post is featured onto the HomePage. However, in the HomePage/Models, I only was able to get it to work with PostPage. I'm not too keen with query/querysets, but I feel it has something to do with that. I've read the Docs multiple times, but I do not understand how to make this work. Blog/Models.py class PostPage(Page): header_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) featured = models.BooleanField(default=False) highlight = models.BooleanField(default=False) description = models.CharField(max_length=255, blank=True,) body = StreamField(BodyBlock(), blank=True) tags = ClusterTaggableManager(through="blog.PostPageTag", blank=True) post_date = models.DateTimeField( verbose_name="Post date", default=datetime.datetime.today ) content_panels = Page.content_panels + [ ImageChooserPanel("header_image"), FieldPanel("description", classname="full"), InlinePanel("blog_authors", label="author", min_num=1, max_num=4), MultiFieldPanel([ InlinePanel("categories", label="category",), FieldPanel("tags"), ], heading="Meta"), StreamFieldPanel("body"), ] settings_panels = Page.settings_panels + [ FieldPanel("post_date"), MultiFieldPanel([ FieldPanel("featured"), FieldPanel("highlight"), ], heading="Showcase") ] Home/Models.py (Method 1) class HomePage(RoutablePageMixin, Page): def get_context(self, request): featured_post = PostPage.objects.live().public().filter(featured=True) featured_editorial = EditorialPage.objects.live().public().filter(featured=True) feature_document = DocumentPage.objects.live().public().filter(featured=True) featured_select = sorted( chain(featured_post, featured_editorial, feature_document), key=lambda page: page.first_published_at, reverse=True)[0] return featured_select … -
I am trying to get data from database using python Django but got an error
Hello everyone I am trying to get data from database but it give me error in case when I am trying to get single data from db as shown below wahid = Webapp.objects.get(title="Ecommerce Website") Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 418, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q child_clause, needed_inner = self.build_filter( File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1258, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1084, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1481, in names_to_path raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'title' into field. Choices are: created, demo_link, description, id, review, source_link, tags, tiltle, vote_ratio, vote_total It will work only on getting all data from db as shown in image -
How to run python-socketio with django?
I am using python socket io in django rest framework. When i try to connect to socket through postman socketio I get following error. Can anyone help me. Not Found: /socket.io/ server.py import os import socketio sio = socketio.Server(async_mode="eventlet") @sio.event def connect(sid, environ): print(sid, "connected") wsgi.py import os import socketio application = get_wsgi_application() from .socketio_config.server import sio socket_application = socketio.WSGIApp(sio, wsgi_app=application) -
Unable to set form choices from view Django
I learned how to do this from Django Form ChoiceField set choices in View in Form initial However it doesn't seem to work correctly, choices are given view: form_class = AskMCQuestionForm() mc_choices = [] if question.One: mc_choices.append(tuple((1, question.One))) if question.Two: mc_choices.append(tuple((2, question.Two))) if question.Three: mc_choices.append(tuple((3, question.Three))) if question.Four: mc_choices.append(tuple((4, question.Four))) if question.Five: mc_choices.append(tuple((5, question.Five))) mc_choices = tuple(mc_choices) print(mc_choices) form_class.fields['user_answer'].choices = mc_choices form_class.fields['assignment'].initial = assignment form_class.fields['exam'].initial = question.exam form_class.fields['correct_answer'].initial = question.correct_answer form_class.fields['text'].initial = question.text print("About to render page for MC question") return render(request, 'Exam/ask_question.html', {'question': question, 'form': form_class}) form: class AskMCQuestionForm(forms.ModelForm): class Meta: model = MC_Question fields = ('text', 'user_answer', 'assignment', 'correct_answer', 'exam',) widgets = { 'text': forms.TextInput(attrs={'class': 'form-control', 'readonly': True}), 'user_answer': forms.Select(attrs={'class': 'form-control'}), 'assignment': forms.Select(attrs={'class': 'form-control'}), 'correct_answer': forms.HiddenInput(), 'exam': forms.HiddenInput(), } model: class MC_Question(models.Model): One = models.CharField(max_length=200) Two = models.CharField(max_length=200) Three = models.CharField(max_length=200, blank=True, null=True) Four = models.CharField(max_length=200, blank=True, null=True) Five = models.CharField(max_length=200, blank=True, null=True) class Answers(models.IntegerChoices): one = 1 two = 2 three = 3 four = 4 five = 5 text = models.CharField(max_length=200) correct_answer = models.IntegerField(choices=Answers.choices, blank=True, null=True) user_answer = models.CharField(max_length=200) exam = models.ForeignKey(Test, on_delete=models.CASCADE) assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, blank=True, null=True) question is an object of MC_Question, the same as what the form is creating. Apologies if I … -
Deploying Django App to Heroku Fail to Push
I am trying to deploy my app to heroku and am running into errors. I'm directly following the walkthrough on Heroku's site, with no luck. error: error: src refspec master does not match any error: failed to push some refs to cmd line: https://imgur.com/a/RVDNUzx Any thoughts? -
How bad is it if I do not use Django_tenants in a SAAS app with multiple users?
So I wish I would of known about Django_tenants earlier. I have written a SAAS (Software as a service) app in Django and the user data is separate by foreign key on the DB. See example. class Company(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) . . class Product(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) . . How bad is this? Am I going to have major problems in the future? Is the data going to get contaminated in any way? Is sqlite3 the appropriate DB? Django_tenants uses Postgresql I have reasearched Django_tenants framework, and it is absolutely the safeguard I would need. But since my app is already written, I realize that to implement Django_tenants, it will basically be a complete rewrite, which I don't really want to do. So, I would really appreciate an opinion from someone with experience in the matter. Thank you. -
Why is Annotate Count function is not populating result?
I hope someone can help me out here - I have to models in Django one called 'Likes' and one called 'Foods', each record in Like contains a FK from Foods. I have the following function in python: def matches(request, eventId): matches = Food.objects.annotate(Count('like__event')) return JsonResponse([match.serialize() for match in matches], safe=False) The above returns a json response, however, I do not see the count of likes in it - I would expect to see at least "like__count": 0 but not even that, it's almost as if the annotate piece is being completely ignored. I think this is because my module is serialized that I don't see it in the JsonResponse. But then what would be the workaround? Thank you in advance! -
Heroku server error 500 after hosting Django app
I have this project, where details are fetched from API LINK COWIN It works completely fine when I run it in localhost, but after hosting it in Heroku, it is showing Server Error 500 settings.py: ALLOWED_HOSTS = ['*'] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static/css', ] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' if os.getcwd() == '/app': DEBUG = False django_heroku.settings(locals()) I am trying to host it from Github. github repo link: Github link for project -
User Specific Page in TODO List
I am making a simple todolist application but while I am trying to create user specific pages, I am unable to add a new task probably beacause database is not getting all required datas(i.e. owner of the task). models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class value(models.Model): task=models.CharField(max_length=200) complete=models.BooleanField(default=False) created=models.DateTimeField(auto_now_add=True) owner=models.ForeignKey(User,on_delete=models.PROTECT) def __str__(self): return self.task views.py from http.client import HTTPResponse from urllib import response from django.shortcuts import render,redirect from todo.models import value from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User # Create your views here. from .forms import TitleForm from django.urls import reverse from django.contrib.auth.models import User def home(request): values=value.objects.all() form=TitleForm() if request.method=='POST': form=TitleForm(request.POST) if form.is_valid(): new_data=form.save(commit=False) new_data.owner=request.user() new_data.save() return HttpResponseRedirect('/') context={'form':form,'values':values} return render(request,'home.html',context) #update def update(request,id): ggwp=value.objects.get(id=id) form=TitleForm(instance=ggwp) if request.method == 'POST': form=TitleForm(request.POST,instance=ggwp) if form.is_valid: form.save() return redirect('home') context={'form':form,} return render(request,'update.html',context) #delete def delete_data(request, id ): if request.method=="POST": ggwp=value.objects.get(id=id) ggwp.delete() return HttpResponseRedirect(reverse('deldata', kwargs={'id':id})) return redirect("/") forms.py from django import forms from django.forms import ModelForm from .models import value from django import forms class TitleForm(forms.ModelForm): class Meta: model= value fields='__all__' urls.py(app) from django.conf.urls import url from django.urls import path from . import views urlpatterns=[ path('',views.home,name='home'), path('delete/<str:id>', views.delete_data,name='deldata'), path('update/<str:id>',views.update,name='update') ] … -
How to pass one of the form field's data to another page using class based views in Python/Django?
I am working on a project where I present a form to the user asking about their sports interests to help them find local players to play with. Then I want to return other users who play the same sport. I am using a CreateView when presenting this form and have one model called UserCharacteristics asking these questions. I want to pass the sport the user chose to the ShowMatched view so I can filter the result based on the matching/same sport. In views.py, for the first class based view I am doing: class EnterInfo(LoginRequiredMixin, CreateView): template_name = 'myapp/enterinfo.html' fields = ['name', 'age', 'cityfrom', 'gender', 'sport'] model = UserCharacteristics def form_valid(self, form): form.instance.user = self.request.user return super(EnterInfo, self).form_valid(form) def get_success_url(self): return reverse('showmatched', kwargs={'sport': self.kwargs['sport'] }) For the second class based view in views.py I am doing: class ShowMatched(TemplateView): template_name = 'myapp/showmatched.html' model = UserCharacteristics context_object_name = 'allentries' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['allentries'] = UserCharacteristics.objects.filter(kwargs = {'sport' : self.sport}) return context In urls.py I am doing: path('enterinfo/', EnterInfo.as_view(), name='enterinfo'), path('showmatched/<str:sport>/', ShowMatched.as_view(), name ='showmatched'), In enterinfo.html file I am doing: <p>You are logged in as: {{request.user}}</p> <form action="{% url 'showmatched' sport.id %}" method="post"></form> {% csrf_token %} {{ form.as_p }} <input … -
Fastapi starlette Image Crop
i just wanna image crop in image called UploadFile in starlette. @app.post("/analyze/{type}") def analyze(type: str, image: UploadFile = File(...)): # type value validate if type not in AVAILABLE_TYPES: return {"status": "error", "data": {"error": f"type `{type}` is not supported."}} # req id gen req_id = uuid.uuid4() # save file input_dir = f"{DATA_BASE_DIR}/input/{type}" os.makedirs(input_dir, exist_ok=True) image_path = f"{input_dir}/{req_id}.jpg" with open(image_path, "wb") as buffer: shutil.copyfileobj(image.file, buffer) # send message to rabbitmq send_message(req_id, type, image_path) # return req id return {"status": "done", "data": {"request_id": req_id}} my code is here, i was used bytesIO and pillow library. but it doesn't worked. what should i do? -
nginx and django deployment issues
I seem to be having issues with my django and nginx deployment. Everything was running as normal, i'd navigate cd into /srv/www/repo do the usual git pull origin mybranch activate my venv and run python manage.py collectstatic This was my process, it has worked fine..until now. It seems that the database has shat the bed and I have no idea why. The issue first started when I did python manage.py migrate it was complaining django.db.utils.OperationalError: attempt to write a readonly database. I thought this was odd, but ultimately thought nothing of it. Then another issue popped up that files were missing when running python manage.py collectstatic Anyway, when I tried to take a look at the deployed changes it seems like the database has been completely wiped. I'm not even able to create user to start populating the db again as I'm getting django.db.utils.OperationalError: attempt to write a readonly database I'm not sure what to do? Really hoping someone can point me in the right direction -
Reorder Not Working with Filtered Data Ajax
I implemented a filtered view into my app and now my reordering ajax is not working. My app is a simple view of a data table that is filtered to a user and week (e.g. Rob makes a pick selection for the same group every week). I am using my reorder to allow the user to click and drag their selections into the order that they want. The data is already loaded for all weeks/users, and the user is not creating/deleting options, only ranking them. This was working on non-filtered data, but now it's not responding. ajax: class AjaxReorderView(View): def post(self, *args, **kwargs): if self.request.is_ajax(): data = dict() try: list = json.loads(self.request.body) model = string_to_model(self.kwargs['model']) objects = model.objects.filter(pk__in=list) # list = {k:i+1 for i,k in enumerate(list)} for object in objects: object.rank = list.index(str(object.pk)) + 1 model.objects.bulk_update(objects, ['rank']) # for key, value in enumerate(list): # model.objects.filter(pk=value).update(order=key + 1) message = 'Successful reorder list.' data['is_valid'] = True # except KeyError: # HttpResponseServerError("Malformed data!") except: message = 'Internal error!' data['is_valid'] = False finally: data['message'] = message return JsonResponse(data) else: return JsonResponse({"is_valid": False}, status=400) pick_list: {% extends 'base.html' %} {% load cms_tags %} {% block title %} {{ title }} · {{ block.super }} … -
Render multiple objects from Django model using request function
Working on adding some job listings to the front page of my django site. There are currently 20 jobs listed for testing purposes. I have a fairly simple django model which contains attributes of the such as job status (active, inactive, archived) and the time at which the job listing was created, so that I can order these chronologically. I want to be able to display only the 4 most recent jobs at the tope of the page, whilst displaying the remaining 16 jobs in a list below this. Here's what I've got so far... Models.py from django.db import models class Job(models.Model): ACTIVE = 'active' INACTIVE = 'inactive' ARCHIVED = 'archived' CHOICES_STATUS = ( (ACTIVE, 'Active'), (INACTIVE, 'Inactive'), (ARCHIVED, 'Archived') ) status = models.CharField(max_length=20, choices=CHOICES_STATUS, default=ACTIVE) created_at = models.DateTimeField(auto_now_add=True) In order to then render the jobs on the frontpage of the site I then refer to the job model in a view like below. Views.py from django.shortcuts import render, redirect from apps.job.models import Job def frontpage(request): jobs=Job.objects.filter(status=Job.ACTIVE).order_by('-created_at')[0:4] all_jobs=Job.objects.filter(status=Job.ACTIVE).order_by('-created_at') return render(request, 'core/frontpage.html', {'jobs': jobs, 'jobs':all_jobs}) This does make jobs appear on the frontpage however it seems that the configuration is dictated by the last request, i.e. all_jobs=Job.objects.filter(status=Job.ACTIVE).order_by('-created_at'). I know this because …