Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
problems on loading templates & admin static_files with virtualenv Django?
I have a project i developed in my machine without using any virtual environments but when i added it to the production machine and made a virtualenv it started throwing errors when loading some pages(now it's only in the sign in page and the DetailView page) and loading the admin page is just like this : and the template error gives this : My virtualenv folder is located inside the project folder just for dealing with nginx and gunicorn. while eveything work fine on my own machine. I have a static_Root and staticfiles_dir so i can't really see where's the problem. -
OneToOneField does not exist on instances of the related object
I am trying to create a one-to-one relationship between two models in different apps. It is giving me the error "RelatedObjectDoesNotExist" when I try to assign a value to that attribute. When a Table is created, no attribute is set for party. When a SeatedUser is created I create the relationship. It is telling me that SeatedUser has no table #apps/restaurants/models.py class Table(models.Model): name = models.CharField(max_length = 50) size = models.IntegerField() restaurant = models.ForeignKey(Restaurant, related_name = "tables") party = models.OneToOneField(SeatedUser, related_name = "table", null = True, default = None) createdAt = models.DateTimeField(auto_now_add = True) updatedAt = models.DateTimeField(auto_now = True) objects = RestaurantManager() #apps/users/models.py class SeatedUser(models.Model): time = models.DateTimeField(auto_now_add = True) member = models.OneToOneField(User, related_name = "seatUser", null = True) objects = DataManager() #apps/restaurants/views.py seatedUser = SeatedUser( member = lineMember.member ) seatedUser.save() seatedUser.restaurant.add(Restaurant.objects.get(line = lineMember)) seatedUser.table.add(myTable) #ERROR SeatedUser has no table lineMember.delete() I need to assign a Table to a SeatedUser, therefore assigning a SeatedUser to that Table. I cannot figure out why it is telling me that this variable doesn't exist. -
How can I save all Scrapy HTML files to S3?
I would like to set up a system to save all HTML files Scrapy finds to s3. Then before pulling any page, I would like to check if that page has already been scraped and stores to S3. I have looked at scrapy's ITEM_PIPELINES, but that seems like it's only for the parse_item function? If I have multiple spiders, it seems silly to have to add a line like: def parse(self, response): self.push_and_save_to_s3(response.text) def parse_item(self, response): self.push_and_save_to_s3(response.text) Is there some middleware I can set up that will do this automatically every time scrapy finds HTML? That way I don't have to go add this code to each parse() function and parse_item() function in my codebase. Once I have that setup, is there a way I can check all previous URLs to tell scrapy to either pull from the live webpage or our S3 bucket? -
Django templates files
Django template works fine with a .html file for me, and I have no issues with it. I was just wondering if there were any upgrades to the templates that permits the use of other kinds of files like .php for rendering. -
How to update prefix id of a formset
I'm new at python, but no at programing. I'm using Django to create a webapp and in some part, I have to create products. A product has a name, brand and type, but this product can have many "inventories". For example: The product Iphone has a brand Apple, type Phone and since I have 3 in my stock, there is another table that saves 3 individual codes for them (and the price and state as well). For this solution I have used formsets, and it was working fine without the JS. What I mean is that the process is ok, but when I want to dinamically add a new row to add a new Inventory, is added visually but then when I tried to save it, it just saves the last row. I have looked into the debug console of chrome and it seems that the problem is that the name and ID, of the new row, remains the same as the original one (the prefix I believe), but I don't know how to change it. Here is my code: (In this picture you can see that the second row has a prefix of 0, it happens the same with … -
Minimal audio (wav or mp3) file in bytes for unit testing
I want to find a minimal audio file (like the testfile_gif below) for unit testing. I don't want to load it from the hard drive (like here). I want the second test to perform like the first one. import magic from django.core.files.uploadedfile import SimpleUploadedFile class TestFiles(TestCase): def test_working(self): # Test an Image File # testfile_gif = ( b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04' b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02' b'\x02\x4c\x01\x00\x3b') gif_file = SimpleUploadedFile(name='image.gif', content=testfile_gif, content_type='image/gif') mime = magic.from_buffer(gif_file.read(1024), mime=True) self.assertEqual('image/gif', mime) def test_not_working(self): # Test an Audio File # testfile_audio = b'What should be written in here?' audio_file = SimpleUploadedFile(name='music.mp3', content=testfile_audio, content_type='audio/mpeg') mime = magic.from_buffer(audio_file.read(1024), mime=True) self.assertEqual('audio/mpeg', mime) Preferably, I don't want to use any packages (like import mock). -
JavaScript Function Doesn't Work On Django
When the first page is loaded, I want the user to come across all the music, but if he selects a list from RadioButton, I only want the music in that list, but the javascript function doesn't work. Let me add that I don't normally know JavaScript, but I need to use it. <div style = "margin-top : 100px;"class = "container"> {% for table in tables %} <input type="radio" name="list1" onclick="mL('{{table}}')"> {{table}} {% endfor %} <div align="center"> <audio class="my_audio" controls="controls" autoplay="autoplay" style="width:500px;"></audio> <ul> {% for table in tables %} {% for music in musics %} <li style="list-style-type:None"> <a id="{{table}}" href="javascript:void(0);" onclick="playSong('{{music}}')">{{music}}</a> </li> {% endfor %} {% endfor %} {% for music in musics %} <li style="list-style-type:None"> <a id="default" href="javascript:void(0);" onclick="playSong('{{music}}')">{{music}}</a> </li> {% endfor %} </ul> </div> </div> <script> function mL(x) { {% for table in tables %} if (x=={{table}}) document.getElementById("{{table}}").style.display="block"; document.getElementById("default").style.display="none"; {% endfor %} else document.getElementById("{{table}}").style.display="none"; document.getElementById("default").style.display="block"; } </script> -
Django: I try to add new group in the admin site but it does't work, the group is added but the permissions with it are not
Do I need to implement some codes for that? To make the modification in admin site effect. -
Django Using Model.objects.all() as a blueprint for a secondary DB entry
I am having a bit of trouble with the logic of how this should work so I am hoping it is possible. Overall I am working on an Apartment Move-Out/Move-In Inspection Application in Django, and in both portions I have universal Locations that must be inspected for each report. I have allowed the InspectionLocations objects to be updated/submitted by clients, which is presenting an issue in how submitted reports should be stored in my Database. What I want is to use the InspectionLocations table as a blueprint to build an Inspection Report for Move-Ins where the form-fields are generated based on the InspectionLocations objects' location, status, and information attributes/fields. My issue is right at this point, how do I reference those values as a blueprint to build a report submission when the number of fields in the InspectionLocations can change? from django.db.models import Sum from django.db.models.signals import post_save from django.dispatch import receiver from apps.units.models import Unit class Inspections(models.Model): class Meta: abstract = True id = models.AutoField(primary_key=True) inspection_date = models.DateField() submitted_by = models.ForeignKey( 'users.CustomUser', default=None, null=True, on_delete=models.SET_NULL, db_column='submitted_by') last_update = models.DateTimeField(auto_now=True) date_added = models.DateTimeField(auto_now_add=True, editable=False) class MoveInInspections(Inspections): unit = models.ForeignKey(Unit, on_delete=models.CASCADE, db_column='unit_id') # should have reference to all InspectionLocation items as … -
How to receive and save data via ajax in django?
through ajax I am sending the data correctly, because the data I see through wireshak and they are correct. On the django server, he sends me the correct request "POST / solit / HTTP / 1.1" 200 52. But the value sent does not receive it, it does not reach the Mysql database and I do not understand why, if the traffic sends well the data. In wireshak I see the data of the post request, they are the correct ones, but they are not saved in the database, when I want them to be added as if I were to update the record of such database fields and it does not , I do not understand why this is my views.py def solit(request): if request.method == 'POST' and request.is_ajax(): form = addiForm(request.POST) if form.is_valid(): peticion = form.save() if peticion.usuario: peticion.usuario.d_pendientes = form.cleaned_data.POST.get['dias_adicionar', None] # Get the form value if has, otherwise assign it to None (change it if you want another default value) peticion.usuario.h_pendientes = form.cleaned_data.POST.get['horas_adicionar', None] # The same peticion.usuario.save() print (request.get) return JsonResponse({'status': 'true', 'msg': 'Procesado Correctamente'}) else: return JsonResponse({'status': 'false', 'msg': 'Los datos no son validos'}) form = addiForm() return render(request, 'plantillas/adicionar.html', {'form':form}) This is my … -
Django app changes in server after a while
I'm running a Django app on an AWS EC2 instance. When I upload the app it works fine for a while and all of a sudden some problems appear. First, it doesn't find the media folders that initially found and second, if I fix the paths to the media folders, it returns a problem with urlpatterns, which doesn't make sense since the app works for an hour or so until it doesn't. To fix the issue I have to reupload the app but after a couple of hours it happens again. Any solutions? -
How to Embed a Plotly Interactive Graph in Webpage
I have an interactive graph generated by Plotly in Python that I saved to an html file using plotly.offline.plot(fig, filename='/tmp/interactiveGraph.html') I am now trying to embed this interactive graph into some kind of webpage, using either Dash or Django. I'm leaning toward Django at the moment, given that I have an html version of the graph. Which would be better? My code for the webpage is in a separate file from the code where I am creating the graph. A lot of the tutorials I've found online just say to add a few lines to the template, but I don't know how to get those lines that they've described. tl;dr: I'm looking for guidance as how to integrate an html file-for a Plotly interactive graph-with a web python script using Django or Dash Reference: https://github.com/ricleal/DjangoPlotLy https://www.pythonsetup.com/how-implement-data-visualization-django-and-plotly/ -
Django filter objects based on property in ForeignKey set
I have models that look something like this: class Type(models.Model): name = models.CharField(max_length=50) notes = models.CharField(max_length=50) class Instance(models.Model): type = models.ForeignKey(Type, on_delete=models.CASCADE) color = models.CharField(max_length=50) quantity = models.PositiveIntegerField() I want to get a list of all Types that have at least one Instance whose quantity is greater than 0. How can I express that? In (pseudo) vanilla Python, this would be something like: [type for type in Type.objects.all() if type.instance_set.objects.filter(lambda instance: instance.quantity > 0)] I tried available_types = Type.objects.filter(Q(instance_set__contains=Q(quantity__gt=0)) but this doesn't work because Django is looking for quantity as an attribute of Type, and of course doesn't find it, because it's an attribute of Instance. -
How to make serializer which could return list in ApiView?
I tried to make API which will return me list of "listing" id for authenticated user, but I did it without any serializer. my view : class AuthUserFavoriteListingsView(APIView): """List of favorite user listings""" permission_classes = (IsAuthenticated, ) def get(self, request): listings = UserListingFavorite.objects.filter(user=request.user).values_list('listing_id', flat=True) return Response({"listings": listings}) it is my result: { "listings": [ 9, 11 ] } Is there any way to get the same result with the serializer? -
TypeError at /modelo/matricula save() missing 1 required positional argument: 'self'
Hola como estas soy nuevo en django bueno mi asunto es que quiero guardar en mi tabla matriculas las llaves de los estudiantes el grupo y el anyo pero me dice save() missing 1 required positional argument: 'self' entoces no se def matricula(request): if request.method=='POST': form=matriculaForm(request.POST) if form.is_valid(): matricula=matriculaForm.save() matricula.save() return redirect('correcto') else: form=matriculaForm() return render(request,'matricula.html',{'form':matriculaForm}) esa es la vista este el modelo class matricula(models.Model): codigo=models.ForeignKey(alumno,default=None,null=False,on_delete=models.CASCADE) grado=models.ForeignKey(grado,default=None,null=False,on_delete=models.CASCADE) anyo=models.ForeignKey(anyo,default=None,null=False,on_delete=models.CASCADE) -
How to get the date from the date picker in django
I am trying to get the date from the user using date picker in django. But I am just getting none despite user picking up a date . I followed this tutorial https://simpleisbetterthancomplex.com/tutorial/2019/01/03/how-to-use-date-picker-with-django.html I am trying to get the date using the cleaned.data. date = form.cleaned_data['date'] How do I get the date user selects. Also, I want the hour and minute field in date picker This is my date field in the form (I am using forms.form) class DateForm(forms.Form): date = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M'], widget=forms.DateTimeInput(attrs={ 'class': 'form-control datetimepicker-input', 'data-target': '#datetimepicker1' }) ) Here is the code in my HTML file <div class="input-group date" id="datetimepicker1" data-target-input="nearest"> <input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker1"/> <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> <script> $(function () { $("#datetimepicker1").datetimepicker(); }); </script> -
Change Django setting ALLOWED_HOSTS in settings.py only when running pytest
I've got a test that I'm trying to run where I login to my django application: class FirefoxTestCases(StaticLiveServerTestCase): def setUp(self): data_setup.basic_apps_setup(self) self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def test_log_in_with_no_apps_displays_firefox(self): # Opening the link we want to test self.browser.get(self.live_server_url) assert "log in" in self.browser.page_source time.sleep(2) self.browser.find_element_by_id("id_username").send_keys("userone") self.browser.find_element_by_id("id_password").send_keys("test") self.browser.find_element_by_id("log_in").click() time.sleep(2) # Check the returned result assert "Something appears to be missing" in self.browser.page_source In doing this - it doesn't actually allow the login because in my settings I have specific ALLOWED_HOSTS setup. Is there a way to access the ALLOWED_HOSTS settings when running this test so that it will allow login when testing? -
Reading Dictionary in Array with Django to HTML
I have the following dictionary: export = { 'target': target_name, 'chats': [ { 'name': 'name', 'time': 'time', }, { 'name': 'name', 'time': 'time', }, ], } What I want to do is to pass these values to a dynamically generated HTML file. {{ for chat in chats }} <h3>{{ chat.name }}</h3> {{ endfor }} If I try to do this it returns the following error: Could not parse the remainder: ' chat in chats' from 'for chat in chats' I am already returning the dictionary, so I can do <h3>{{ target }}</h3> -
Django runserver hangs at “System check identified no issues (0 silenced).” for a while
I am not able to start manage.py runserver 0.0.0.0:8000. I am using a MySQL database and I have imported all the required modules. I am trying to run quite basic application. I am running python 3.7.3 on windows 10. Here is the error I am getting: System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000000005A89E18> Traceback (most recent call last): File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\utils\aut oreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\core\mana gement\commands\runserver.py", line 120, in inner_run self.check_migrations() File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\core\mana gement\base.py", line 442, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\db\migrat ions\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\db\migrat ions\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\db\migrat ions\loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\db\migrat ions\recorder.py", line 62, in applied_migrations return {tuple(x) for x in self.migration_qs.values_list('app', 'name')} File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\db\models \query.py", line 268, in __iter__ self._fetch_all() File "C:\Users\flgferre\Desktop\webapp\venv\lib\site-packages\django\db\models \query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) MemoryError -
How Do I Stop Recursive GET For Python/Django/Javascript?
I've spent the last couple days trying to figure out the answer to this SO...ModelChoiceField invalid literal for int() with base 10: '' Leveraging this solution, How to prevent submitting the HTML form's input field value if it empty I'm really close. The problem is...I'm using a django DetailView and overriding GET to try and get the value that is being passed by Javascript, but it's essentially looping when I perform my GET. I'm new to Javascript, and it's entirely possible that my Javascript program is incorrect. Here is my code.... My Django DetailView... class AuthorDetailView(LoginRequiredMixin,DetailView): model = Author template_name = 'author_detail.html' def get_object(self, queryset=None): return get_object_or_404(Author, id=self.request.GET.get("dropdown")) def get(self, request, *args, **kwargs): dropdown=self.request.GET.get("dropdown") if dropdown: print(dropdown) try: if Author.objects.filter(Q(id=self.request.GET.get("dropdown"))).distinct(): self.object = self.get_object() return HttpResponseRedirect(reverse('Main:author_detail')) else: messages.add_message(self.request, messages.INFO, 'Please enter a valid choice.') print(dropdown) return HttpResponseRedirect(reverse('Main:author_detail')) My HTML.... My FORM.... class AssociateByNameForm(forms.Form): dropdown = forms.ModelChoiceField(queryset=User.objects.none(),required=False) def __init__(self, *args, **kwargs): dropdown = kwargs.pop('dropdown', None) super(AssociateByNameForm, self).__init__(*args, **kwargs) self.fields['dropdown'].widget.attrs['class'] = 'choices' self.fields['dropdown'].empty_label = '' self.fields['dropdown'].queryset = Author.objects.filter(is_active=True).order_by('last_name','first_name') self.fields['dropdown'].label_from_instance = lambda obj: "%s" % obj.get_full_name() My Javascript.... $(document).ready(function () { $('form').submit(function() { var dropdown = $('#id_dropdown').val(); if (dropdown === undefined || dropdown === "") { $('#id_dropdown').attr('name', '' ); } }); }); From what … -
How do I Force db commit of a single save in django-orm in a celery task
I am using django and celery. I have a long running celery task and I would like it to report progress. I am doing this: @shared_task def do_the_job(tracker_id, *args, **kwargs): while condition: #Do a long operation tracker = ProgressTracker.objects.get(pk=tracker_id) tracker.task_progress = F('task_progress') + 1 tracker.last_update = timezone.now() tracker.save(update_fields=['task_progress', 'last_update']) The problem is that the view that is supposed to show the progress to the user cannot see the updates until the task finishes. Is there a way to get the django orm to ignore transactions for just this one table? Or just this one write? -
How to create profil model with foreign key
I want to create a dashboard for users for showing their SEO score. I have on my projet 3 apps: -Account : with a login/registration form using the Usercreation form basic of django. it has fields(email,firstname,last_name) -Analysis : With a scrapper that's scanning all the website and saving on the database the seo score, the email, and the consent to contact or not What I want to do is to merge these 2 tables, maybe using foreinkeys or I don't know what. For what? I want to have a table while when i click on the user on django admin, there is his name,last name, email, seo score, and his website, and he can login with his mail. On this dashboard I will show him all the data related to his website so that's why i have to make a connection between the login platform and the website scrapper. part of Settings.py : import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'key' # SECURITY WARNING: don't run with debug … -
How to create postgresql object from a Django script?
I have this code: import random import string def random_username_and_password(stringLength): letters = string.ascii_letters return ''.join(random.choice(letters) for i in range(stringLength)) username = random_username_and_password(random.randint(8, 12)) password = username To create a user, it is enough to register the following line User.objects.create_user(username, password) But I want to do this through connecting to the postgres database from a script. import sys,os if __name__ == '__main__': # pragma nocover # Setup environ sys.path.append(os.getcwd()) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "starnavi.settings") import django django.setup() from django.db import connections db_conn = connections['default'] try: c = db_conn.cursor() except OperationalError: connected = False else: connected = True But what to do next, I do not understand. I'm use Django 2.2, Python 3.7, Postgresql 9.5 -
How to pass context from views to JS file Django
I am using Google charts to show data in my webapp. Right now these charts are in the script tag in my templates (HTML) like so. <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Date', 'Low', {role: 'annotation'}, 'Medium', {role: 'annotation'}, 'High', {role: 'annotation'}, 'Emergency',], ['{{three_sun}}', 124, 124, 163, 163, 87, 87, 0], ['{{two_sun}}', 120, 120, 160, 160, 80, 80, 0], ['{{last_sun}}', 127, 127, 159, 159, 89, 89, 0], ['{{this_sun}}', {{total_low}}, {{total_low}}, {{total_medium}}, {{total_medium}}, {{total_high}}, {{total_high}}, {{total_emergency}}] ]); var options = { title: 'All Bugs', vAxis: {title: 'Total Bugs'}, isStacked: true }; var chart = new google.visualization.SteppedAreaChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> I am trying to clean up this project and have all my scripts coming from static .js files. Now obviously it doesn't recognize {{three_sun}}. I need to know how i can be able to use this chart with the context variables, from a static.js like so. chart.js google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Date', 'Low', {role: 'annotation'}, 'Medium', {role: 'annotation'}, 'High', {role: 'annotation'}, 'Emergency',], ['{{three_sun}}', 124, 124, 163, 163, 87, 87, 0], ['{{two_sun}}', 120, 120, 160, 160, 80, 80, 0], ['{{last_sun}}', 127, 127, 159, 159, 89, 89, 0], … -
Problem with django-multiselectfield and forms
I want to do a multiple selection in the models django and how it would turn out (I used the library), and now I try to make sure that only selected items from my model field are shown in my form, but I am faced with a small problem : AttributeError: 'MSFList' object has no attribute 'get_choices_selected' 1) I know that in this library there is a function get_choices_selected that returns selected items 2) I tried to use just the output of the model, but it returns the string data type: (( my models.py CHOSE_SIZE = (('XS', 'XS'), ('S', 'S'), ('M', 'M'), ('L', 'L'), ('XL', 'XL'), ('XXL', 'XXL'), ('XXXL', 'XXXL')) ....... available_size = MultiSelectField(choices=CHOSE_SIZE, verbose_name='Available Sizes', default=None) my forms.py class item_add_form(forms.Form): quantity = forms.IntegerField(max_value=21, min_value=0) size = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOSE_SIZE) def __init__(self, *args, **kwargs): choices = kwargs.pop('choices', None) super(item_add_form, self).__init__(*args, **kwargs) self.fields['size'] = forms.ChoiceField(widget=forms.RadioSelect, choices=choices) my views.py class MainPage(views.View): products = Product.objects.get(ordered__gt=0) form = item_add_form(choices =products.available_size.get_choices_selected()) contex = {'products' : products, 'form_input': form } def get(self, request): return render(request, 'MainPage/Mainpage.html', context=self.contex) I will be glad to any help, and I ask your advice: 1) Is it possible to fix this somehow? 2) Or how to do it better?