Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django or Firebase for a small project
I am a beginner and looking forward to start freelancing with flutter. And I am wondering whether or not is Firebase better than Django for small projects that doesn't require alot of users concerning the price as firebase is alot easier than django -
Best way to connect Django Query results to Chart.js charts?
Can someone advise what is the cleanest/easyest way to connect my query to the Data/Label part of chart.js script? Thank you in advance. -
How to update a single item in a list from the template in Django?
I am looking for the best way to make an updateable list from model objects in Django. Let's say that I have a models.py: class Foo(models.Model): bar = models.CharField(max_length=10, blank=True) foo = models.CharField(max_length=30, blank=True) and I have a views.py that shows the objects from that model: def my_view(request): person_list = Person.objects.all() ctx= {'person_list': person_list} return render(request, 'my_app/my_view.html', ctx) Then I have a template, my_view.html: ... <table> <tr> <th>bar</th> <th>foo</th> <th></th> </tr> {% for item in person_list %} <tr> <td>{{item.bar}}</td> <td>{{item.foo}}</td> <td style="width: 5%;"><button type="submit" name="button">Change</button></td> </tr> {% endfor %} </table> ... So, I would like to add a form and make one of those fields changeable from within this template. I would like users to be able to change item.foo and then click the change button and it sends the update to the model. I tried making it a form, and using forms.py to create a form where users can put an input, and then submit the form, and that looked like this, my_view.html: ... ... <table> <tr> <th>bar</th> <th>foo</th> <th></th> </tr> {% for item in person_list %} <form method="post"> {% csrf_token %} <tr> <td>{{item.bar}}</td> <td>{{item.foo}}</td> <td>{{form.foo}}</td> <td style="width: 5%;"><button type="submit" name="button">Change</button></td> </tr> </form> {% endfor %} </table> ... ... … -
Filter foreign key objects in django template
I have the following model which is used to "archive" a post (i.e if it is created for a post by a user, that post is now hidden from that user) models.py class ArchivedFlag(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='archived_commits') post = models.ForeignKey(Commit, on_delete=models.CASCADE, related_name='archived_flag') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='archives') In a particular template, I want logic based on whether an ArchivedFlag exists for both the current user's group and the current post being examined. template.html {% for p in posts %} <form action="{% url 'archive_commit' c.oid %}" method="post"> {% csrf_token %} <input type="hidden" name="next" value="{{ request.get_full_path }}"> {% if <...an archived flag exists with post==post and group==user.group...> %} <...Do stuff for archived post...> <button type="submit", name="c_oid", value="{{ c.oid }}", class="btn btn-primary btn-sm">Restore</button> {% else %} <...do stuff for unarchived post...> <button type="submit", name="c_oid", value="{{ c.oid }}", class="btn btn-primary btn-sm">Archive</button> {% endif %} </form> {% endfor %} Is there any way to do this in a django template? I can't find any information on filtering in a template so perhaps this is not possible. -
include more than one image inside a TextField
How can I include more than one image inside a TextField in blog posts ? like that : main article_title : article_name 1 article_picture 1 article_desc 1 article_name 2 article_picture 2 article_desc 2 article_name 3 article_picture 3 article_desc 3 All in one article . this is my models: class Categorie (models.Model): class Meta : verbose_name_plural = 'Categorie' title = models.CharField(max_length=50) def __str__(self): return self.title class blog (models.Model): class Meta : verbose_name_plural = 'blog' ordering = ['article_created_at'] category = models.ForeignKey(Categorie,on_delete=models.CASCADE,null=True) article_slug = models.SlugField(blank=True,allow_unicode=True,editable=True) article_title = models.CharField(max_length=200 , null=True) article_name = models.CharField(max_length=200 , null=True ) article_picture = models.ImageField(upload_to='img_post' , null=True) article_desc = models.TextField(null=True) article_created_at = models.DateField(auto_now_add=True) article_updated_at = models.DateField(auto_now=True) article_auther = models.CharField(max_length=200 , null=True) def save(self , *args , **kwargs): if not self.article_slug: self.article_slug = slugify(self.article_name) super(blog , self).save( *args , **kwargs) def __str__(self): return self.article_title this is my views : from django.shortcuts import render from . import models from .models import blog , Categorie def blog_index(requset): posts = blog.objects.all().order_by('-article_updated_at') context = { 'posts':posts, } return render( requset , 'blog/blog.html' , context) -
How can I build a query that will return objects that hold more than one specific foreign key?
class People(models.Model); name = models.CharField() surname = models.CharField() class Votes(models.Model): value = models.CharField() people = models.ForeignKey(People) I would like to write a query that will return a queryset of people who have more than one vote(how many foreign keys of Votes has People) . how can I achieve this? -
How to store Persian character using Jesanfield in dajngo?
I tried to store Persian characters with Jesanfield, but I had the following problem when displaying characters in the database. "{'\u0628\u0631\u0646\u062f}" models: from django.contrib.postgres.fields import JSONField class example(models.Model): spec_json = JSONField(null=True, blank=True) enter image description here -
How to combine the Django WebSockets "websocket_urlpatterns" (path) of multiple apps in the Project URLRouter?
I have multiple apps and they all are using the "WebSockets (routing.py)", and I have routing.py in my project and apps. I can only add the "websocket_urlpatterns" of single app in my URLRouter, if I try to add the other "websocket_urlpatterns" in the URLRouter, it didn't worked and I get the error. Project routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import django_chatter.routing import app1.routing import os from time import sleep os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings") application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( app1.routing.websocket_urlpatterns # send request to chatter's urls ) ) }) App1 routing.py from django.urls import path from django_chatter import consumers import app1.consumers websocket_urlpatterns = [ path('ws/route1/' , app1.consumers.Consumer1.as_asgi()), path('ws/route2/' , app2.consumers.Consumer2.as_asgi()), path('ws/route3/' , app3.consumers.Consumer3.as_asgi()), ] App2 routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/chatter/chatrooms/<str:room_uuid>/', consumers.ChatConsumer.as_asgi()), path('ws/chatter/users/<str:username>/', consumers.AlertConsumer.as_asgi()) ] -
How to get an input field in javascript by rendering a form using django render to string?
Here is my issue and I have been trying for 2 days to understand what is my code doing? I have a django model form which is rendered to a modal an ajax call. Here is the model and the form. class CreateSagaForm(forms.ModelForm): class Meta: model = Saga fields = "__all__" widgets = { "end_date": forms.DateInput(attrs={"class": "datepicker"}), "start_date": forms.DateInput(attrs={"class": "datepicker"}), } def __init__(self, *args, disabled_field=True, **kwargs): super(CreateSagaForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = "CreateSagaForm" self.helper.layout = Layout( "epic_key", Row( Column("epic_status", css_class="form-group col-md-3 mb-0"), Column( "start_date", HTML("""<i class="fa fa-calendar" ></i>"""), css_class="form-group col-md-4 mb-0", ), Column( "end_date", HTML("""<i class="fa fa-calendar" ></i>"""), css_class="form-group col-md-4 mb-0 text-center", ), ), the models.py class Saga(models.Model): start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) the view that render the data of the modal through the ajax. def get_form(request, key_epic): instance = get_object_or_404(Saga, epic_key=key_epic) JsonInstance = serializers.serialize( "json", [ instance, ], use_natural_foreign_keys=True, use_natural_primary_keys=True, ) form = CreateSagaForm(request.POST or None, instance=instance) context = {"form": form} template = render_to_string("tracking/get-form.html", context, request=request) return JsonResponse( { "sagaForm": template, "instance": JsonInstance, } ) the ajax call epic_keys.forEach(epic => { epic.addEventListener('click', () => { var epicKey = epic.textContent; url = `/api-sagaForm/${epicKey}/` var formLocal = document.querySelector(".sagaFormLocal"); $.ajax({ url: … -
Is it possible to input data into another table using the create function within the classview(django crv)?
Is it possible to input data into another table using the create function within the classview? A unique failed error occurred when using the create function for this part class createSkilNoteForInsertMode(LoginRequiredMixin,CreateView): model = MyShortCut form_class = SkilNoteForm def get_template_names(self): return ['skilnote1/myshortcut_summernote_form.html'] def form_valid(self, form): type_list = Type.objects.all() if not type_list: Type.objects.create(type_name="summer_note") Type.objects.create(type_name="textarea") Type.objects.create(type_name="input") Type.objects.create(type_name="image") else: ty = type_list.get(type_name="summer_note") ms = form.save(commit=False) ms.author = self.request.user ms.type= ty ms.created = timezone.now() category_id = self.request.user.profile.selected_category_id ca = Category.objects.get(id=category_id) ms.category = ca profile = Profile.objects.filter(Q(user=self.request.user)).update(last_updated = datetime.now(), last_updated_category = ca.name) # In this part, how do I add data to the HistoryForUpdate model of the accounts2 app? # A unique failed error occurred when using the create function for this part return super().form_valid(form) -
Django search query in JSON data
If the searched query is in my JSON data, I want to show that product. views.py query = request.GET.get('search') if query: product_list = product_list.filter( Q(product_name__icontains=query) | Q(brand__brand_name__icontains=query) | Q(model__name__icontains=query) | Q(gtin_no__icontains=query) | Q(oem_no__icontains=query) | Q(tag__icontains=query) ) models.py product_name = models.CharField(max_length=300) slug = models.SlugField(unique=True, editable=False, max_length=300) category = models.ForeignKey('ProductCategory', null=False, on_delete=models.CASCADE, max_length=100) brand = models.ManyToManyField('Brand', null=True, max_length=100) model = JSONField(null=True, max_length=10000) product_code = models.CharField(blank=True, max_length=20) gtin_no = JSONField(blank=True, max_length=10000) oem_no = JSONField(blank=True, null=True, max_length=10000) tag = JSONField(blank=True, null=True, max_length=10000, default=None) Example model JSON data: { "data": "[['Car Parts', 'Ssangyong'], ['Industrial Parts', 'Lombardini'], ['Mercedes-Benz Sprinter', 'Sprinter OM 601, OM 602 DE LA']]" } Example GTIN JSON data: { "data": [ "4047755219970" ] } Example OEM JSON data: { "data": [ "624 320 0028", "625 320 0028" ] } Sometimes this JSON data can be empty. { "data": [ "None" ] } -
Django - How to get image field of ForeignKey query elements?
I have the following code at views.py to sort TvShows by there latest released episode (release_date) within 90 days: def tv_show_by_set_just_released(request): latest_episodes = TvShows.objects.filter(episode_show_relation__release_date__gte=now() - datetime.timedelta(days=90)) ... For each element found, I now also want to display a cover. But the cover is located at a different table and I don't really know how to pull it out probably in this query context. In the end I want to display the very first TvShowSeasons.cover for each element of my query from above. Is it somehow possible to marry these two elements, latest_episodes and TvShowSeasons.cover to display them properly at a template? Please also see models.py class TvShows(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.TextField(verbose_name=_("Title"), blank=False, null=True, editable=False, max_length=255) genre_relation = models.ManyToManyField(through='GenreTvShow', to='Genre') date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added")) class TvShowSeasons(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) show = models.ForeignKey(TvShows, on_delete=models.CASCADE, related_name='season_show_relation') season_number = models.IntegerField(verbose_name=_("Season Number"), blank=True, null=True, editable=False) cover = models.ImageField(verbose_name=_("Cover"), blank=True, null=True, upload_to=get_file_path_images) cover_tn = models.ImageField(verbose_name=_("Cover Thumbnail"), blank=True, null=True, upload_to=get_file_path_images) total_tracks = models.IntegerField(verbose_name=_("Total Tracks #"), blank=True, null=True) rating = models.CharField(verbose_name=_("Rating"), blank=True, null=True, editable=False, max_length=255) copyright = models.TextField(verbose_name=_("Copyright"), blank=True, null=True, editable=False, max_length=255) date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added")) Thanks in advance -
Problem with Django Tests and Trigram Similarity
I have a Django application that executes a full-text-search on a database. The view that executes this query is my search_view (I'm ommiting some parts for the sake of simplicity). It just retrieve the results of the search on my Post model and send to the template: def search_view(request): posts = m.Post.objects.all() query = request.GET.get('q') search_query = SearchQuery(query, config='english') qs = Post.objects.annotate( rank=SearchRank(F('vector_column'), search_query) + TrigramSimilarity('post_title', query) ).filter(rank__gte=0.15).order_by('-rank'), 15 ) context = { results = qs } return render(request, 'core/search.html', context) The application is working just fine. The problem is with a test I created. Here is my tests.py: class SearchViewTests(TestCase): def test_search_without_results(self): """ If the user's query did not retrieve anything show him a message informing that """ response = self.client.get(reverse('core:search') + '?q=eksjeispowjskdjies') self.assertEqual(response.status_code, 200) self.assertContains(response.content, "We didn\'t find anything on our database. We\'re sorry") This test raises an ProgrammingError exception: django.db.utils.ProgrammingError: function similarity(character varying, unknown) does not exist LINE 1: ...plainto_tsquery('english'::regconfig, 'eksjeispowjskdjies')) + SIMILARITY... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. I understand very well this exception, 'cause I got it sometimes. The SIMILARITY function in Postgres accepts two arguments, and both need to be of … -
How to generate dynamic rows in page based on the response of the js request? (Django Template / HTML)
Is this possible to append the rows with data in an HTML table as a response of the JavaScript request without doing a page postback? Django: 3.1.7 I want to write a seprate HTML file (Like a file we can use with include tag) for the code so I don't have to append the html of entire table in the HTML string. For now I am appending the HTML by converting to the string concatination. Note: Need a solution without page postback. function GetCollection(myId) { var Urlgetallcom = "/sc/GetCollection/" + myId ; // alert(Urlgetallcom); $.ajax({ url: Urlgetallcom, // the endpoint type: "GET", // http method data: { Id: myId }, // handle a successful response success: function (json1) { var Collection = json1; console.log(Collection); for (var i = 0; i < Collection.length; i++) { $('#Comments_Div').append( '<div class="mt-comments" style="border-bottom: 1px solid #eef1f5">' + '<div class="mt-comment">' + '<div class="mt-comment-info">' + '<div class="mt-list-item done mt-comment-info" onclick="ShowCommentInfoWindow(' + Collection[i].f.latitude + ',' + Collection[i].f.longitude + ',\'' + Collection[i].f.commentDetails + '\')">' + '<div id="' + Collection[i].pk + '" class="mt-comment-details" style="display:block">' + '<span>' + Collection[i].f.commentDetails + ' </span>' + '<div class="mt-comment-actions ">' + '</div>' + '<br />' + '</div>' + '<div class="mt-comment-body">' + '<div class="mt-comment-details">' + '<span … -
Django form how do I make 2 drop box search result depending on how first one is selected?
I am trying to make form consist of two dropbox using query from model. so first dropbox get all distinct store name from Menu table and that part, I got it working. However, how do I make second dropbox filter result depending on what I pick on first dropbox? For example, If I pick store A for first dropbox, it shows sa, sb, sc as menu name and if I pick store B for first dropbox, it shows ma, mb, mc as menu name and so on. Also, second dropbox can have 2 filter condition like storename + day. How can I accomplish this? forms.py class MenuForm(forms.ModelForm): store_name = forms.ModelChoiceField(queryset=Menu.objects.distinct('store_name')) menu_name = forms.ModelChoiceField(queryset=Menu.objects.filter(??)) class Meta: model = Menu fields = {'store_name', 'menu_name'} -
How to get the value being referenced in django?
Here I need to get the student_id in the values. I have defined s_id but if values() is called it does not show. FeeSection.objects.get(id=1).section.sectionstudent_set.annotate(s_id=F('student__id')).get(student__id=1).qouta.feeqouta_set.all().values() This query returns: <QuerySet [{'id': 1, 'qouta_id': 2, 'type_id': 1, 'amount': Decimal('200.00')}, {'id': 2, 'qouta_id': 2, 'type_id': 2, 'amount': Decimal('10.00')}]> what I need is: 's_id':1 <QuerySet [{'id': 1,'s_id':1, 'qouta_id': 2, 'type_id': 1, 'amount': Decimal('200.00')}, {'id': 2, 's_id':1,'qouta_id': 2, 'type_id': 2, 'amount': Decimal('10.00')}]> -
Final Test: Set up Django app for production
I finalized my first django app and uploaded it to the webhosting service and I'm having trouble with that. However, I am not sure that I did not make any mistake setting it up before the upload. So my question is: Can I run my virenv locally again and should my django app still work locally? I try to locate where my mistake is and want to make sure, that it is set up correctly. If I run my virenv I get this error "This site can’t provide a secure connection". Any help? That would be great! -
Django how to sort objects by there foregein key relation?
at my Django application I want to display some TV-Show entries. Currently I want to build a filter for TV-Shows sorted by there latest released episodes. But I'm not sure how the query has to look like. This is how I pull episodes for the last 90 days def tv_show_by_set_just_released(request): latest_episodes = TvShowEpisodes.objects.filter( release_date__lte=datetime.datetime.today(), release_date__gt=datetime.datetime.today()-datetime.timedelta(days=90)).order_by('-release_date') But how can I reference the actual TV-Show of the Episode now? I want to Sort the Tv-Shows by there latest added episode (release_date) please have a look a my modeling: class TvShows(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.TextField(verbose_name=_("Title"), blank=False, null=True, editable=False, max_length=255) genre_relation = models.ManyToManyField(through='GenreTvShow', to='Genre') date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added")) class TvShowEpisodes(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) duration = models.FloatField(verbose_name=_("Duration"), blank=True, null=True, editable=False, max_length=255) title = models.TextField(verbose_name=_("Title"), blank=False, null=True, editable=False, max_length=255) release_date = models.DateField(verbose_name=_("Release Date"), blank=True, null=True, editable=False) track = models.IntegerField(verbose_name=_("Track #"), blank=True, null=True) show = models.ForeignKey(TvShows, on_delete=models.CASCADE, related_name='episode_show_relation') season = models.ForeignKey(TvShowSeasons, on_delete=models.CASCADE, related_name='episode_season_relation') episode_id = models.CharField(verbose_name=_("Episode ID"), max_length=255, blank=True, null=True, editable=False) episode_sort = models.IntegerField(verbose_name=_("Episode Number"), blank=True, null=True, editable=False) synopsis = models.TextField(verbose_name=_("Synopsis"), blank=True, null=True, editable=False, max_length=255) date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added")) -
failed to build wheel for psycopg2?
Hi after i re write my source code and cloning my website from heroku i get this error LOGS : psycopg/psycopgmodule.c: In function ‘psyco_is_main_interp’: psycopg/psycopgmodule.c:689:18: error: dereferencing pointer to incomplete type ‘PyInterpreterState’ {aka ‘struct _is’} 689 | while (interp->next) | ^~ error: command '/usr/bin/gcc' failed with exit code 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-t_xxbtyy/psycopg2-binary/setup.py'"'"'; __file__='"'"'/tmp/pip-install-t_xxbtyy/psycopg2-binary/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-cevcg2_6/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.9/psycopg2-binary Check the logs for full command output. ! Push rejected, failed to compile Python app. ! Push failed Any fixes ?? Thanks -
ModuleNotFoundError when mocking while using pytest
I'm using pytest for writing unit tests in my django project. But when I want to mock a method in following code: @patch('smspanel.services.sms_panel_info_service.get_buinessman_sms_panel') def test_send_plain_sms_success(mocker, businessman_with_customer_tuple): mocker.return_value = SMSPanelInfo() customer_ids = list(map(lambda e: e.id, businessman_with_customer_tuple[1])) businessman = businessman_with_customer_tuple[0] message = 'message' result = services.send_plain_sms(user=businessman, customer_ids=customer_ids, message=message) smsq = SMSMessage.objects.filter( businessman=businessman, message_type=SMSMessage.TYPE_PLAIN, status=SMSMessage.STATUS_PENDING, message=message) assert smsq.exists() sms = smsq.first() receivers_count = SMSMessageReceivers.objects.filter(sms_message=sms, customer__id__in=customer_ids).count() assert receivers_count == len(customer_ids) I get following error: thing = <module 'smspanel.services' from 'C:\\Users\\Pouya\\Desktop\\programs\\python\\marketpine-backend\\smspanel\\services.py'> comp = 'sms_panel_info_service' import_path = 'smspanel.services.sms_panel_info_service' def _dot_lookup(thing, comp, import_path): try: return getattr(thing, comp) except AttributeError: > __import__(import_path) E ModuleNotFoundError: No module named 'smspanel.services.sms_panel_info_service'; 'smspanel.services' is not a package c:\users\pouya\anaconda3\lib\unittest\mock.py:1085: ModuleNotFoundError My test file is locate in smspanel/tests/test_services.py. -
Rendering database objects in Django
This is a basic question but I can't figure out what I'm doing wrong... I'm trying to render a detail view in my django site, but my calls to get the object are just failing or else not rendering. Here is what I have: views.py from django.template import loader from django.views.generic.base import TemplateView from django.http import HttpResponse from .models import user_profile def detail(request, content_id): template = loader.get_template('profiles/detail.html') profile = user_profile.objects.get(pk=content_id) context = {'profile': profile} return HttpResponse(template.render(context, request)) Within the template, I have simply been testing the calls using: <h1>{{ profile }}</h1> <h1>{{ profile.name }}</h1> This is my first time rendering this from scratch, I know I'm missing something dumb I just can't sort it. Thank you! edit This current setup receives a 500 error. Without the get(pk) statement it loads, but doesn't show the variables, just the rest of my HTML. -
postgresql psycopg2 django docker setup just cannot get it to connect to postgres at all
** Django==3.2.7 psycopg2==2.9.1 python=3.9.7(using this setup** for the hell of me i cannot get postgress to setup correctly iam very new to all this but so far this is the 4th hurdle ive hit but 2 i am having to seek help for i just cannot seem to setup postgres correctly ** my setup files ** ** docker compose ** version: "3.8" x-service-volumes: &service-volumes - ./:/app/:rw,cached x-database-variables: &database-variables POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_USER: postgres x-app-variables: &app-variables <<: *database-variables POSTGRES_HOST: postgres services: website: tty: true image: ashleytaylors_websites:latest command: python manage.py runserver 0.0.0.0:8000 volumes: *service-volumes environment: *app-variables depends_on: - db_migrate ports: - "8000:8000" db_migrate: image: ashleytaylors_websites:latest command: python manage.py migrate volumes: *service-volumes environment: *app-variables depends_on: - postgres postgres: image: postgres ports: - "5432" environment: - db-data:/var/lib/postgresql/data ** docker ** FROM python:3.9.7-slim-buster as production ENV PYTHONBUFFERED=1 WORKDIR /app/ RUN apt-get update && \ apt-get install -y \ bash \ build-essential \ gcc \ libffi-dev \ musl-dev \ openssl \ postgresql \ libpq-dev COPY requirements/prod.txt ./requirements/prod.txt RUN pip install --user -r ./requirements/prod.txt COPY manage.py .manage.py #COPY setup.cfg ./setup.cfg COPY ashleytaylors_website ./ashleytaylors_website EXPOSE 8000 FROM production as development COPY requirements/dev.txt ./requirements/dev.txt RUN pip install --user -r ./requirements/dev.txt COPY . . ** make file ** build: … -
Editing a Django package inside a docker container
In my Django docker file, I'm using the pip install -r requirements.txt file. Through this, I'm downloading a certain package but that package needs to be edited once installed. On my local computer, I can just go to the site-packages and edit it but I need to know where can I find it inside a container? Or is it even possible? I'm fairly new to docker so please help me out. -
Django import-export foregin key
I am trying to import data with a foreign key following the guide from the Django import-export library (foreign key widget). But I am getting the following error , I have tried to add an additional column with the header name id but I still get the same error. Errors Line number: 1 - 'id' None, 46, 19, LSD Traceback (most recent call last): File "/var/www/vfsc-env/lib/python3.6/site-packages/import_export/resources.py", line 635, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "/var/www/vfsc-env/lib/python3.6/site-packages/import_export/resources.py", line 330, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "/var/www/vfsc-env/lib/python3.6/site-packages/import_export/resources.py", line 318, in get_instance self.fields[f] for f in self.get_import_id_fields() File "/var/www/vfsc-env/lib/python3.6/site-packages/import_export/resources.py", line 318, in <listcomp> self.fields[f] for f in self.get_import_id_fields() KeyError: 'id' Here is what I did. class Clockin_Users(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. userid = models.IntegerField(db_column='UserID', unique=True) # Field name made lowercase. username = models.CharField(db_column='UserName', max_length=20, blank=True, facecount = models.IntegerField(db_column='FaceCount', blank=True, null=True) # Field name made lowercase. userid9 = models.CharField(db_column='UserID9', max_length=10, blank=True, null=True) # Field name made lowercase. depid = models.IntegerField(db_column='DepID', blank=True, null=True) # Field name made lowercase. empno = models.CharField(db_column='EMPNO', max_length=50, blank=True, null=True) # Field name made lowercase. def __str__(self): return self.name class Clockin_Department(models.Model): clockinusers = models.ForeignKey(Clockin_Users, on_delete=models.CASCADE) depid = models.AutoField(db_column='DepID', primary_key=True) # Field name made lowercase. … -
How to pass a javascript variable inside a url get in Django
I would like to send a radio_id to my view, Now I'm currently trying to get the ID of my radio by javascript, but I don't know how to pass it by get method inside my url and send to the view: html: <a href="{% url 'maintenance_issue_fix' %}?radio_id=checked"> <img src="{% static 'images/maintenance_list.jpg' %}"> </a> {% for list in issue_list %} <tr style="text-transform: capitalize;"> <td style="text-align:center;"> <input name="radio_id" type="radio" id="radio_id" value="{{list.id}}"> </td> <\tr> {% endfor %} javascript: <script> $(function(){ $('input[type="radio"]').click(function(){ if ($(this).is(':checked')) { var checked = $(this).val(); console.log(checked); } }); }); </script> views: def maintenance_issue_fix(request): if request.method == 'GET': issue_id = request.GET.get('radio_id') print(issue_id) When I try to get the javascript var to pass inside the url, occur the follow error: ValueError at /maintenance/maintenance_issue_fix/ invalid literal for int() with base 10: 'checked' How to do it?