Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To Get The Local TIme In Models.DateTimeField() In Django?
I was trying to get the local time in the models section of my models.py file in Django. But this function returns the server time which is about 5 hours less than my local time, so, how do I get this correct? date = models.DateTimeField(default=timezone.now) Thanks In Advance! -
How can i update another model fields when i save another form
Hi i have 2 models Game and Match models.py class Game(models.Model): title = models.CharField(max_length=255) team1score = models.IntegerField(null=True, blank=True,default=0) ... team2score = models.IntegerField(null=True, blank=True,default=0) ... class Match(models.Model): title = models.CharField(max_length=255) game=models.ForeignKey(Game,on_delete=models.CASCADE) team1score = models.IntegerField(null=True, blank=True,default=0) ... team2score = models.IntegerField(null=True, blank=True,default=0) ... forms.py class MatchForm(forms.ModelForm): team1score = forms.IntegerField(widget=forms.TextInput,required=False) team2score = forms.IntegerField(widget=forms.TextInput,required=False) class Meta: model=Match fields=['team1score', 'team2score', ... ] I'm creating a match object with the code below. views.py def creatematch(request,...): form = MatchForm(request.POST or None) if form.is_valid(): match = form.save(commit=False) ... match.save() ... Now, my question is how can i update game.team1score and game.team2score when i create match objects -
Give object same field value as a field of its Foreign Key
I am trying to create a job board website. The user enters a zip code and jobs in a specified radius should be returned. Here is my models.py: class Business(models.Model): name = models.CharField(max_length = 150) address = models.CharField(max_length = 150) city = models.CharField(max_length = 150) zip_code = models.CharField(max_length = 10) state = models.CharField(max_length = 30) phone_number = models.CharField(max_length = 10) def __str__(self): return self.name +", " + self.address + ", " + self.state class Job(models.Model): business = models.ForeignKey(Business, on_delete = "models.CASCADE") title = models.CharField(max_length = 100) description = models.CharField(max_length = 500) zip_code = business.zip_code def __str__(self): return self.title + " - " + self.business.name Upon attempting to filter Job objects by zip code: jobs_in_zip = Job.objects.all().filter(zip_code = zip_code) I realized the Job model did not have a zip_code field. I tried updating the model as such: class Job(models.Model): business = models.ForeignKey(Business, on_delete = "models.CASCADE") zip_code = business.zip_code but this returned AttributeError: 'ForeignKey' object has no attribute 'zip_code' How should I go about this? Thanks in advance. PS: If you have a better title in my mind feel free to change it, I don't think I clearly defined the problem that well. -
Gallery in Django
I have a "Category" model. I want to have it so every time I create a category it creates a directory in my media folder. From there I want to be able to upload images to the relevant folders and have a gallery in my category view that loops through every image in said categories directory. category.html <div class="container"> <div class="row"> {% for image in images %} <div class="col-md-4"> <a href="/media/{{ image }}"> <img src="/media/{{ image }}" class="img-responsive img-thumbnail" width="304" height="236"/> </a> </div> {% endfor %} </div> </div> views.py def category_view(request): images = os.listdir(settings.MEDIA_ROOT) context = { "images": images, } return render(request, "main/category.html", context) This code seems to work but only for the MEDIA_ROOT. I want to loop through a specific category. -
Django: Does not raise error if CharField and TextField are not provided when blank=True
class Test(models.Model): name = models.CharField(blank=True) Now i try to save Test without supplying name Test.objects.create(pk=1) Now i am expecting it should raise an exception saying that name is required. Whereas for other fields it will raise an exception that we have to provide the value So is it some default behaviour for CharField and TextField that blank=True will allow to store empty string -
Auto-increment conflicting slugs on save
I need blog post slugs to be unique on a per user basis. When a user saves a new post in my Django project, I'd like it to check if the slug exists, and if it does, add a -1 to the end of it. What's the best way to do this? I've added my code below, which is always adding the -1, and I'm sure there's a better way to do this class Post(models.Model): ... def save(self, *args, **kwargs): posts = Post.objects.filter(user=self.user, slug=self.slug) if self not in posts: self.slug = self.slug + '-1' super(Post, self).save(*args, **kwargs) -
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>'
When I tried to add database with inspectdb command then this error is appearing mysql is conencted in settings.py I just created small patient table in phpmyadmin models.py class Patient(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() mobile = models.BigIntegerField() sex = models.CharField(max_length=6) address = models.CharField(max_length=255) occupation = models.CharField(max_length=20) class Meta: managed = False db_table = 'patient' and the remaining is auto generated by django itself there is id column there bt it was not autogenerated and length of age is also not getting fetched so this might causing problem becuz before ruinning inspectdb command server was running normally -
Not sure how to use Tastypie to process in GET and POST with non-standard OMR
I want to know what's best way to handle GET/POST in Tastypie. I am not saving/storing data in database in backend. 2 ajax calls, ajax_get(“GET”), ajax_save(“POST”, big_data>5mb) ajax_save() to save large amount of data. If using GET, nginx, gunicorn has limitation, you have to configure it. I don’t want that, that’s why to use POST. Following could work. But, is there better way? class HelloResource(Resource): file_result = fields.CharField(attribute='file_result', null=True) class Meta: resource_name = ‘hello’ allowed_methods = ('get', 'post') # Make no difference with/without for my case. always_return_data = True max_limit = None limit = 0 def dehydrate(self, bundle): """ Handle ajax POST. """ # When ajax_save() is called, it comes here. # But, the problem is when ajax_get() is called, it also comes to here. # Have to distinguished unrelated call. call_type = bundle.data['type'] # Figure out JS client action. def get_object_list(self, request): """ Handle ajax GET. """ try: # ajax_get(). Works! But, if calling ajax_save(), it does NOT come here. # Therefore, I used dehytrate()!!! call_type = request.GET.get('type', None) # Figure out JS client action. -
Data integrity in JSON(B) when replacing EAV
I'm implementing a database for a new application and I'm considering using JSON fields instead of traditional EAV approach. Everything seems okay, but there is a one big problem that I don't know how to solve. For example; in a traditional EAV model, we would have three tabels; First table to hold the attributes Second table to hold the values Third table to tie those two together. The identifier in the third table would always be primary key of one of the other two and not the value itself. If I change the name of the attribute, it's primary key remains the same thus having no affect on the data integrity in the third table. Now enter JSON. As far as I understand, the whole point of replacing EAV with JSON is to store all the values in the fields itself. So our record could look like this. { "color": "Blue", "size": "Large" } instead of storing values by primary keys. So my question is, if I down the road, change the title of the color from let's say Blue to Purple, how do I deal with data integrity? Since in classic EAV model the primary keys wouldn't change. -
How to refactor two Django querysets that match
I have two models that no have relationship, I match with one of its fields in this case area_ref withresource_ref For example: Match is found: area_ref = 'L020202' with resource_ref = 'L020202' Models... class Area(models.Model): name = models.CharField() area_ref = models.CharField() def __str__(self): return self.name class Resource(models.Model): name = models.CharField() resource_ref = models.CharField() def __str__(self): return self.name I'm currently doing it with lists area = Area.objects.values('area_ref') area_list_ref = [] for _a in area: area_list_ref.append(_a.get('area_ref')) resource = Resource.objects.filter(resource_ref__in=area_list_ref) It works, but when it finds several matches it takes a long time Any better ideas? -
How to check if for loop is in the middle value
I have trouble getting the middle loop in a forloop in django template. I've tried using {% for value in key.dictionary %} {% if forloop.counter == widthratio value|length 2 1 %} but with no effect. Actually after the widthratio I get an error Expected %} Computing the division was taken from this post Is there a filter for divide for Django Template? -
How to get sql equivalent query from django query?
Currently I am developing website in Django & I need to convert some djnago query to sql equivalent query. Purchase_order.objects.filter(query).order_by(id)[start: (start+length)] I want to convert above django query into sql type of query. Is there any way availble to convert it into sql also. -
How to edit value of a record when Django admin page of the model gets opened
In my Django app, I have a model that has an IntegerField for holding the number of queries done today and another field that holds the date of last modification of that field. class logs(models.Model): today_queries = models.IntegerField("today's queries", default=0, help_text="Total number of today's queries.") update_date = models.DateField(default=datetime.date.today) My problem is that every time I open the Django admin page for the logs model, the value for today_queries gets retrieved and shown (the default behavior obviously) but that number would be incorrect if tomorrow and other days come (it should be 0). How can I edit the value of today_queries as soon as the Django admin page for the logs model gets opened (so that I compare update_date with now and if it is a new day, reset the value of today_queries) -
Django page navigation- home list not visible
I am super new to Dango; pardon me for a rookie question :) I am learning Django by creating a "Note taking app". This is how the application home page looks. When I click on any of the notes from the note list, it opens the details on the right-side page. But the problem is it wipes-out the left-hand side note list. To reload the list I need to click on the Home link again. The expected behavior is, it should retain the note-list on the left side as well as show the details on the right frame. urls.py from django.urls import path from .views import NoteListView, NoteDetailView, NoteCreateView, NoteUpdateView, NoteDeleteView from . import views urlpatterns = [ path('', NoteListView.as_view(), name='lekha-home'), path('note/<int:pk>/', NoteDetailView.as_view(), name='note-detail'), path('note/new/', NoteCreateView.as_view(), name='note-create'), path('note/<int:pk>/update', NoteUpdateView.as_view(), name='note-update'), path('note/<int:pk>/delete', NoteDeleteView.as_view(), name='note-delete'), path('about/', views.about, name='lekha-about'), ] enter code here views.py class NoteListView(ListView): model = Note template_name = 'lekha/home.html' context_object_name = 'notes' ordering = ['-date_created'] class NoteDetailView(DetailView): model = Note # success_url = 'lekha/note_detail.html' class NoteCreateView(LoginRequiredMixin, CreateView): model = Note fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) home.html {% extends "lekha/base.html" %} {% block content %} {% for note in notes %} <div class="list-group"> <a … -
Is it necessary to create new app for homepage models in Django?
I want to add a slider to my homepage. What is best way to do it? Should I create a new app for slider? Or can I create a class for slider in home(app)/models.py? I tried to create Slider class in home/models.py. But I couldn't list on homepage. home/views.py def slider_index(request): slides = Slider.objects.all() return render(request, 'home.html', {'slides': slides}) def slider_detail(request, id): slide = get_object_or_404(Slider, id=id) context = { 'slide': slide, } return render(request, 'home.html', context) home/models.py class Slider(models.Model): title = models.CharField(max_length=120, verbose_name='Başlık') content = models.TextField(verbose_name='Açıklama') publishing_date = models.DateTimeField(verbose_name='Yayınlanma Tarihi', auto_now_add=True) image = models.ImageField(null=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('slide:detail', kwargs={'id': self.id}) # return "/slider/{}".format(self.id) class Meta: ordering = ['-publishing_date', '-id'] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', home_view), path('slider/', slider_index, name='index'), path('slider/<int:id>/', slider_detail, name='detail'), path('post/', include('post.urls')), ] and home.html: {% for slide in slides %} <!-- Slide #1 image --> {% if slide.image %} <img src="{{ slide.image.url }}" alt="{{ slide.content }}" title="{{ slide.title }}" /> {% endif %} {% endfor %} Nothing appears about slider. I'm newbie in django. I want to learn how to list slides in homepage. Thanks in advance. -
Django interaction with Gitlab API
How to use Gitlab API in Django app e.g for Ruby on Rails there is Gitlab API wrapper gem and for Django there is no such equivalent. I want to see repositories for given user/organization. -
Best practice to schedule a long running django batch job on Heroku
I have developed a Django web application that runs in Heroku. Everything has been working fine using 1 web dyno. Now I need to run a web scrapping batch job (also in Django) that takes approximately 12 hours to complete. I plan to execute it twice a week. Which would be the best way to accomplish this? Heroku documentation recommends using worker dynos and a scheduler to initiate the request. As far as I know, If I implement it this way I will have to pay for an entire worker dyno even if it is used only 24 hours a week. The other option is to execute the batch job within the scheduler but Heroku does not recommend executing long lasting processes that way. Any suggestions? Thanks. -
Object not being saved in Celery task
I am using celery=4.3 Django package and Django 2.2.6. I noticed that object is not saved when I try to update it from celery task function @app.task def update_object(object_id, points): object = MyObject.objects.get(pk=object_id) object.update_points(points) My object looks like this: class MyObject(models.Model): .... def update_points(self, points): self.points += points self.save() I am calling celery task with: update_object.delay(object_id, points) And this doesn't work :/ Does anyone have some suggestion why? -
Django Unit Test - ID's of created objects
Sample models.py models.py class Food(models.Model): name = models.CharField(max_length=50, verbose_name='Food') def __str__(self): return self.name Suppose that I have written unit test/s: from django.test import TestCase from myapp.models import Food class TestWhateverFunctions(TestCase): """ This class contains tests for whatever functions. """ def setUp(self): """ This method runs before the execution of each test case. """ Food.objects.create(name='Pizza') # Will the created object have id of 1? Food.objects.create(name='Pasta') # Will the created object have id of 2? def test_if_food_is_pizza(self): """ Test if the given food is pizza. """ food = Food.objects.get(id=1) self.assertEqual(food.name, 'Pizza') def test_if_food_is_pasta(self): """ Test if the given food is pasta. """ food = Food.objects.get(id=2) self.assertEqual(food.name, 'Pasta') I was wondering if it's safe to assume that the id's of the created objects in setUp() method will always start at id 1 and so on and so forth? If not, is there a specific reason why if the test database is always destroyed after running all tests? -
Can`t deploy Django app in Heroku via Github
First of all, I tried to deploy my app with heroku website. My action algorithm: 1) Choose app name and region. 2) Select Deploy tab to deploy app by Github. 3) Choose my repo and press Deploy Branch button, with master branch selected. Here is were I'm got firt error: ! No default language could be detected for this app. HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. See https://devcenter.heroku.com/articles/buildpacks ! Push failed 4) Select Settings tab and add heroku/python buildpack Second error is: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed First what I found about this error, is: this. But, I already got requirments.txt', andProcfile, and, I tried to put my.git` folder inside of project directory, and whole app generally. I also tried to uninstall and install this python buildpack myself through heroku CLI , but, still, nothing works. You can view my github repo here. Also, I will update this post if will find an answer. -
Dynamically change the buttons in Navbar FE: Bootstrap, BE: Django
How to change Log-in to Logged-in in the dropdown menu once the user has logged in. FE: Bootstrap BE: Django login.html: {% extends 'base.html' %} {% load staticfiles %} {% load crispy_forms_tags %} {%block login%} <body> <link rel='stylesheet' href='{%static "css/main1.css" %}'/> <div class='row'> <div class='col-md-5 col-md-offset-1'> <h1> {{ title }}</h1> <form method="Post" action="">{%csrf_token%} {{form|crispy}} <input type='submit' value='submit form' class=btn 'btn-default' /> </form> </div> </div> </body> {%endblock%} Navbar.html: <li {%if request.path == login%} class="active"{%endif%}><a href="{%url 'login'%}">Login</a></li> <li {%if request.path == register%} class="active"{%endif%}><a href="{%url 'register'%}">Register</a></li -
Django inlineformset_factory how to properlu override the __init__ function
everyone! I'm trying to pass a value to the init function and fill one of my field with data from another model. I hardcoded the value to get the right data in my field. I want to know, how to pass initial values into init function? I found a lot of solutions but they doesn't work for me. I've tried to pass primary key into initial func: forms.py class ObservationPartsForm(forms.ModelForm): def __init__(self, pk=None, *args, **kwargs): super(ObservationPartsForm, self).__init__(*args, **kwargs) primary = kwargs.get('pk') print('Get pk',primary) #Get pk None instance = kwargs.get("instance") meteostation = MeteoStation.objects.get(id=pk) if instance == None: meteoparam = forms.ModelChoiceField( queryset=meteostation.meteo_parametrs.select_related().filter(is_active=True), label='Метеопараметр', ) self.fields['meteoparam'] = meteoparam else: value_selected = forms.ChoiceField(label='Значение для выбора') self.fields['value_selected'] = value_selected #print(instance) class Meta(): model = ObservationParts fields = ('meteoparam', 'value_digit', 'value_selected', 'author_parts', 'who_updated') ObservationEntireFormset = inlineformset_factory(ObservationEntire, ObservationParts, form=ObservationPartsForm, extra=1, ) views.py class ObservePartsCreateView(CreateView): template_name = 'dairy/test.html' model = ObservationParts #form_class = ObservationPartsForm success_message = 'Метеопараметры добавлены к наблюдению.' formset = None def get_form(self, form_class=None, **kwargs): pk_ = self.kwargs.get("pk") print(pk_) form = ObservationPartsForm(pk=pk_) return form def get_initial(self, **kwargs): initial = super(ObservePartsCreateView, self).get_initial() initial['value_selected'] = ObserveDate.objects.all() return initial def get(self, request, *args, **kwargs): pk_ = kwargs.get("pk") observe_entire = ObservationEntire.objects.get(pk=pk_) self.formset = ObservationEntireFormset(instance=observe_entire) return super(ObservePartsCreateView, self).get(request, *args, **kwargs) def … -
how to test django get_absolute_url with unittest
I am trying to test get_absolute_url with unittest but i keep failing to pass the test. Any thought on how to test it properly? models.py class Address(models.Model): venue = models.CharField(max_length=1000) longitude = models.CharField(max_length=1000) latitude = models.CharField(max_length=1000) postal_code = models.IntegerField() person = models.ForeignKey(User, on_delete=models.CASCADE, related_name='person_addresses') def __str__(self): return self.venue def get_absolute_url(self): return reverse('core:address_detail', kwargs={'pk': self.pk }) urls.py from django.contrib import admin from django.urls import path, include from . import views app_name = 'core' urlpatterns = [ path('', views.address_list, name='address_list'), path('<int:id>/', views.address_detail, name='address_detail'), ] test_models.py from django.test import TestCase from core.models import Address from django.contrib.auth import get_user_model from django.urls import reverse User = get_user_model() class AddressModelTest(TestCase): def setUp(self): self.user = User.objects.create(username='amanda', password='amanda') self.address = Address.objects.create( venue="901 S Miami Ave, Miami, FL", person=self.user, longitude="-80.193039", latitude="25.765051", postal_code="33130", ) def test_address_get_absolute_url(self): # I tried 'self.client.post' and 'self.client.get' below, both are not working. response = self.client.post(reverse('core:address_detail', kwargs={'pk':self.address.pk})) self.assertEqual(response, self.address.pk) error from console django.urls.exceptions.NoReverseMatch: Reverse for 'address_detail' with keyword arguments '{'pk': 4}' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/$'] Any help would be much appreciate. -
Object of type 'AttributeError' is not JSON serializable
I have just started learning Django and was trying to create an API. It is a simple API which fetches a definition from the table and returns it as a response. But whenever I am trying to send a keyword in the request, I am getting the error, Object of type 'AttributeError' is not JSON serializable. What am I doing wrong in here? @api_view(['POST']) def getdetails(request): try: connection = sqlite3.connect('{}.db'.format('insure')) cursor = connection.cursor() plan = json.loads(request.body.decode('utf-8')) cursor.execute( """SELECT INSURANCE_TYPE_DESC FROM tblInsurancePlans WHERE INSURANCE_TYPE LIKE '%{}%'""".format(plan) ) rows = cursor.fetchall() for row in rows: return JsonResponse(str(row), safe=False) except Exception as e: return Response(e) However, when I try to hard-code the keyword (plan), it works and I get the response. -
DJANGO_SETTINGS_MODULE (error generated in code for Python Crash Course)
All good with Django setup, virtual env, etc. until I simply run the models.py to define models. Writing and running the code in VS Code for Windows. Run it in terminal session. I've tried editing the settings file in learning_log directory but did not solve the problem. For example, I added the last line to settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'learning_log', ] Also tried adding this line to settings: DJANGO_SETTINGS_MODULE=learning_log.settings Here is the offending code: from django.db import models class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) --snip-- Here is the error message from the terminal: c:/Users/Jeff/py_projects/learning_log/models.py Traceback (most recent call last): File "c:/Users/Jeff/py_projects/learning_log/models.py", line 3, in <module> class Topic(models.Model): File "C:\Users\Jeff\py_projects\env\lib\site- packages\django\db\models\base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\Jeff\py_projects\env\lib\site- packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "C:\Users\Jeff\py_projects\env\lib\site- packages\django\apps\registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "C:\Users\Jeff\py_projects\env\lib\site- packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\Jeff\py_projects\env\lib\site- packages\django\conf\__init__.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.