Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to generally reference a django url that has parameter
It's my urls.py app_name = "medicalrecord" urlpatterns = [ path("filesharing/<str:username>/", views.FileSharingView, name="FileSharingView"), ] in my css.html ... {% url 'medicalrecord:FileSharingView' "IDK" as medicalrecord_file_sharing %} ... {% if request.path == medicalrecord_file_sharing %} <link rel="stylesheet" type="text/css" href="{% static 'medicalrecord/css/filesharing.css' %}"> {% endif %} IDK what to put there, any username i put it only matches that one, how to set it dynamic ? -
How to populate auth.groups and auth.group_permissions tables with initial data in Django project
Context I am using PostgreSQL. I would like to immediately populate the auth.groups and auth.group_permissions tables, after the very first migration of my project. So, after I have set up these tables the way I want them, I dump them by running python manage.py dumpdata auth.groups auth.group_permissions > core/fixtures/initial_data.json The resulting file is this [ { "model": "auth.group", "pk": 1, "fields": { "name": "Admin", "permissions": [ 29, 31, 32, 33, 34, 35, 36 ] } }, { "model": "auth.group", "pk": 2, "fields": { "name": "Operators", "permissions": [ 42, 43, 44, 39, 40 ] } }, { "model": "auth.group_permissions", "pk": 12, "fields": { "group": 1, "permission": 32 } }, { "model": "auth.group_permissions", "pk": 13, "fields": { "group": 1, "permission": 33 } }, { "model": "auth.group_permissions", "pk": 14, "fields": { "group": 1, "permission": 34 } }, { "model": "auth.group_permissions", "pk": 15, "fields": { "group": 1, "permission": 35 } }, { "model": "auth.group_permissions", "pk": 16, "fields": { "group": 1, "permission": 36 } }, { "model": "auth.group_permissions", "pk": 17, "fields": { "group": 1, "permission": 29 } }, { "model": "auth.group_permissions", "pk": 18, "fields": { "group": 1, "permission": 31 } }, { "model": "auth.group_permissions", "pk": 19, "fields": { "group": 2, "permission": 39 } }, { … -
My bootstrap modal is not showing up after it said the process was successful
this html code for my modal - the page displays fine but when click the button to show the modal it doesn't show up but when i inspect my web page it says my says the process was successful but i cant see it and i also got errors- i am still new with JavaScript and html <td><a href="#" class ="btn btn-success show_notification" data-toggle="modal" data-target="#myModal">Send Notifications</a></td> </tr> {% endfor %} </tbody> </table> </div> <!-- /.card-body --> </div> <!-- /.card --> </div> </div> </div> </section> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Send Notification <span id="name"></span></h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <div class="form-group"> <input type="text" name="message" class="form-control" id="message"> <input type="hidden" name="admin_id" class="form-control" id="admin_id"> </div> </div> <div class="form-group"> <button class="btn btn-info btn-block" type="button"> Send Notification</button> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> {% endblock main_content %} {% block custom_js %} <script> $(".show_notification").click(function(){ var admin_id=$(this).parents("tr").children("td:eq(0)").text(); var admin_name=$(this).parents("tr").children("td:eq(3)").text(); console.log(admin_id); $("#admin_id").val(admin_id); $("#name_span").text(admin_name); }); </script> {% endblock custom_js %} this is the errors that came up in my web console > admin_send_notification_admin:410 GET > http://127.0.0.1:8000/static/plugins/bootstrap/js/bootstrap.bundle.min.js > net::ERR_ABORTED 404 (Not Found) jquery.vmap.min.js:10 Error: <svg> > attribute width: Expected length, "undefined". VectorCanvas.setSize … -
Runtime model generation in Django or other languages
I'm asking this question for hearing about advice and having an idea about the possibility of this type work. Not asking for any code help, just advice, and a little leading would be helpful, if it is still the wrong place to ask this question, sorry about that. I would like to build an application that lets users upload a CSV or excel file and generate a SQL table at the backend at that time and store data into the table. Then print the loaded data in UI. I did it before in a terrible and messy way by using the Create Table query and select query for printing data. I believe you will think of me how a programmer can be so ridiculous if you see these codes. That's the reason I want to learn if there is a better and standard way to do the same thing or shouldn't do something like that at all? And how other companies do this type of works? You can advise different programming languages if there are any. I read about documents Dynamic Models. I understand a little, but they don't advise to build in that way, so I don't know if … -
Linking two tables with ManyToManyField in Django
I have two db tables: Estados: estado_id, estado_nome Familia: familia_id, familia_nome One family can have multiple Estado, in my mysql db it uses a tertiary table, with composite keys, as we all know django don't supports it. I'm willing to do whatever it takes to make it work. Thank you very much for reading my question and i hope you have a good day. -
I can't install graphene-django in GitHub actions
I am building a Django project, and I am using GitHub actions to run python manage.py test whenever I push. The problem is that in the project, I am using the graphene-django package, which's available to install via pip install graphene-django. The problem is that, for some reason, this doesn't seem to work (it outputs an error). I have tried everything: pip install graphene-django pip install "graphene-django>=2.0" pip install --user graphene-django pip install --user "graphene-django>=2.0" pip3 install graphene-django pip3 install "graphene-django>=2.0" pip3 install --user graphene-django pip3 install --user "graphene-django>=2.0" Some of these commands display a different error, but the most common is this: Collecting promise>=2.1 (from graphene-django>=2.0) Downloading https://files.pythonhosted.org/packages/cf/9c/fb5d48abfe5d791cd496e4242ebcf87a4bb2e0c3dcd6e0ae68c11426a528/promise-2.3.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> ModuleNotFoundError: No module named 'setuptools' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-5vr1pems/promise/ Here is my YAML file for the Action (with the last intslling attempt): name: Testing on: push jobs: test_vote: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Run Django unit tests run: | pip3 install --user django pip3 install --user "graphene-django>=2.0" python3 manage.py test env: # Random key SECRET_KEY: '!nj1v)#-y)e21t^u@-6tk+%+#vyzn30dp+)xof4q*y8y&%=h9l' Any help would be really appreciated, … -
How to deal with an abandoned Django package ( that is not compatible anymore with new version of Django/python )?
In my case there is no update in Django-suit package, anyone know how to deal with it? -
having trouble configuring Django on the atom editor for a Mac computer
I am trying to set up Django the newest version with python 3 and I keep getting errors about the path way. this is what it is saying and the following is my configurations. Note: I have uninstalled and installed and even wrote it to the exact way their website directs with no luck. it just changes around the error. terminal: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/patrickjobe/Desktop/wordcount/wordcount/urls.py", line 20, in <module> path('index/', views.index), NameError: name 'path' is not defined urls.py page configs rom django.contrib import admin from . import views urlpatterns = [ path('index/', views.index), path('admin/', admin.site.urls), ] settings.py page TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] views.py page from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request, 'index.html') -
How overwrite django-friendship
I am using a third party application called "django-friendship" and I want to adapt it to my project. To adapt it to my project I need to overwrite several functions and urls that come by default, but I don't know how to overwrite them. The source code is here: https://github.com/revsys/django-friendship For example, I want to overwrite the following function in views.py: def all_users(request, template_name="friendship/user_actions.html"): users = user_model.objects.all() return render( request, template_name, {get_friendship_context_object_list_name(): users} ) and for example I want this function to do nothing, just print a text on the screen (not its purpose but to make the example simpler) in this way: def all_users(request, template_name="friendship/user_actions.html"): print("Hello World") I have used the following import: from friendship.views import all_users But it does not work, it still uses the function of the third party application and not mine. On the other hand, "django-friendship" uses the following urls: friendship/ ^users/$ [name='friendship_view_users'] friendship/ ^friends/(?P[\w-]+)/$ [name='friendship_view_friends'] friendship/ ^friend/add/(?P<to_username>[\w-]+)/$ [name='friendship_add_friend'] friendship/ ^friend/accept/(?P<friendship_request_id>\d+)/$ [name='friendship_accept'] friendship/ ^friend/reject/(?P<friendship_request_id>\d+)/$ [name='friendship_reject'] friendship/ ^friend/cancel/(?P<friendship_request_id>\d+)/$ [name='friendship_cancel'] friendship/ ^friend/requests/$ [name='friendship_request_list'] friendship/ ^friend/requests/rejected/$ [name='friendship_requests_rejected'] friendship/ ^friend/request/(?P<friendship_request_id>\d+)/$ [name='friendship_requests_detail'] friendship/ ^followers/(?P[\w-]+)/$ [name='friendship_followers'] friendship/ ^following/(?P[\w-]+)/$ [name='friendship_following'] friendship/ ^follower/add/(?P<followee_username>[\w-]+)/$ [name='follower_add'] friendship/ ^follower/remove/(?P<followee_username>[\w-]+)/$ [name='follower_remove'] friendship/ ^blockers/(?P[\w-]+)/$ [name='friendship_blockers'] friendship/ ^blocking/(?P[\w-]+)/$ [name='friendship_blocking'] friendship/ ^block/add/(?P<blocked_username>[\w-]+)/$ [name='block_add'] friendship/ ^block/remove/(?P<blocked_username>[\w-]+)/$ [name='block_remove'] How can I modify … -
Is including the user field in two related models a bad practice? (Django)
I’m fairly new to Django and programming in general. I’m building a tool for a friend in the construction industry. Basically the client bids for a tender and if they win they sign a contract. A contract can have multiple projects and a project can have multiple jobs. But the user should also be able to create a job for smaller projects that are not under a contract. Every job must be under a project. If the user has a contract I want the user journey to be as the following: Create a contract -> create a project -> create a job. I want to link the contract to the user and the job to the user as well but I’m not sure if it’s a good practice to include the user field twice in two related models. I’d like to know if my solution is wrong and a bad practice, and if there’s a better solution. Thanks! class Contract(TimeStampedModel): owner = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) title = models.CharField( max_length=100, blank=False, unique=False) starting_date = models.DateTimeField(default=timezone.now, blank=True) class Meta: verbose_name_plural = "Contracts" def __str__(self): return self.title class Project(TimeStampedModel): name = models.CharField( max_length=50, blank=False, unique=False) contract = models.ForeignKey( Contract, on_delete=models.RESTRICT, blank=False, related_name='contract', … -
Reverse for 'update_prices' not found. 'update_prices' is not a valid view function or pattern name
i am building an amazon web scraper where you can submit a link and track the price of your product. When i try to go to this site this error pops up and it also says that the error is at line 0 at base.html How do i get rid of this error models.py from django.db import models from .utils import get_link_data # Create your models here. class Link(models.Model): name = models.CharField(max_length=220, blank=True) url = models.URLField() current_price = models.FloatField(blank=True) old_price = models.FloatField(default=0) price_difference = models.FloatField(default=0) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.name) class Meta: ordering = ('price_difference', '-created') def save(self, *args, **kwargs): name, price = get_link_data(self.url) old_price = self.current_price if self.current_price: if price != old_price: diff = price - old_price self.price_difference = round(diff, 2) self.old_price = old_price else: self.old_price = 0 self.price_difference = 0 self.name = name self.current_price = price super().save(*args, **kwargs)``` **views.py** ```from django.shortcuts import render, redirect from django.urls import reverse_lazy from .models import Link from .forms import AddLinkForm from django.views.generic import DeleteView def home_view(request): no_discounted = 0 error = None form = AddLinkForm(request.POST or None) if request.method == 'POST': try: if form.is_valid(): form.save() except AttributeError: error = "Ups ... couldn't get the name or the … -
Django static file not working properly in production
This is the first time to deploy a project for development. Here are the steps that I have made to ensure that the static files are correctly reflected on the site. Added STATIC_ROOT to the setting.py STATIC_ROOT = '/home/ahesham/Project/static/' STATIC_URL = '/static/' python manage.py collectstatic Here is the outcome: You have requested to collect static files at the destination location as specified in your settings: /home/User/Project/static This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes 1545 static files copied to '/home/User/Project/static'. (venv) User@django-server:~/Project$ python manage.py runserver 0.0.0.0:8000 Now the problem is that when I opened the site, not all CSS files are not reflecting and in the console it is proving it: Failed to load resource: the server responded with a status of 404 (Not Found) login.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) style.min.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) meme.jpg:1 Failed to load resource: the server responded with a status of 404 (Not Found) loginutil.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) login.css:1 … -
Django postgres migration error foreign key constraint does not exist
I'm using a PostgreSQL database hosted with aws, everytime I try to migrate (python manage.py migrate) I run into this error: column "id" referenced in foreign key constraint does not exist. I have tried removing the two foreign keys that I'm using with no luck I still get the same error. I have also tried this solution with no luck. The rest migrates with no problem, Just this one error Model.py class Subprogram(models.Model): title = models.CharField(max_length=100) program = models.ForeignKey(Program, on_delete=models.CASCADE) budget = models.DecimalField(default=0, decimal_places=0, max_digits=11) class Project(models.Model): name = models.CharField(max_length=100) budget = models.DecimalField(decimal_places=0, max_digits=11) budget_year = models.PositiveIntegerField(default=current_year(), validators=[MinValueValidator(current_year)]) file = models.FileField(blank=True) subprogram = models.ForeignKey(Subprogram, on_delete=models.CASCADE, default=) -
ManyToManyField In HTML
Can someone please let me know the proper way to display values that have been entered in a ManyToMany data field? In my project, a contractor can have multiple trades or skills, this should be entered in the trade field. class SubTrade(models.Model): strade = models.CharField("Trade", max_length=255) def __str__(self): return self.strade def get_absolute_url(self): return reverse ("trade_full", kwargs={"pk": self.id}) class SubContractor(models.Model): nameF = models.CharField("First Name", max_length=255, blank = True, null = True) nameL = models.CharField("Last Name", max_length=255, blank = True, null = True) nameN = models.CharField("Nickname", max_length=255, blank = True, null = True) trade = models.ManyToManyField('SubTrade') phone = models.CharField("Phone", max_length=255, blank = True, null = True) email = models.EmailField("Email", max_length=254, blank = True, null = True) address = models.CharField("Address", max_length=255, blank = True, null = True) dateC = models.DateTimeField("Date Created", auto_now_add=True) dateU = models.DateTimeField("Last Updated", auto_now=True) note = models.TextField("Notes", blank = True, null = True) def __str__(self): return '%s %s' % (self.nameF, self.nameL) def get_absolute_url(self): return reverse ("contractor_full", kwargs={"pk": self.id}) These are my views. class SubContractorCreateView(CreateView): model = SubContractor template_name = "project/contractoradd.html" fields = ['nameF', 'nameL', 'nameN', 'trade', 'address', 'phone', 'email', 'note'] def form_valid(self, form): return super().form_valid(form) This is my HTML Code {% for contractor in contractor %} Last Name: {{contractor.nameL}} <br> … -
How to get an evironment variable value in YAML file?
I am working on a Django project, and I am using GitHub for source control purposes. I am using GitHub actions to run python3 manage.py test when pushing. I don't want to post my secret key to the repository. So I stored it on an environment variable and used os.environ.get('SECRET_KEY') to keep it secret. The problem is that by doing this, GitHub doesn't know what the SECRET_KEY is. There is a way to set custom environment variables in the YAML file in the workflow directory, but if I put the SECRET_KEY there, there is no point in covering it in settings.py. Does anybody know what I can do? -
AssertionError: `create()` did not return an object instance
I am getting the error below while sending a request to a UserRegisterView: File "/Users/MichaelAjanaku/Desktop/test/afrocode/lib/python3.6/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Users/MichaelAjanaku/Desktop/test/leave/views.py", line 22, in post serializer.save() File "/Users/MichaelAjanaku/Desktop/test/afrocode/lib/python3.6/site-packages/rest_framework/serializers.py", line 207, in save '`create()` did not return an object instance.' AssertionError: `create()` did not return an object instance. I don't know why such occurs. Here is my views.py: class UserRegistrationView(CreateAPIView): serializer_class = UserRegistrationSerializer permission_classes = (AllowAny,) def post(self, request): serializer = self.serializer_class(data= request.data) serializer.is_valid(raise_exception=True) serializer.save() status_code = status.HTTP_201_CREATED response = { 'success' : 'True', 'status code' : status_code, 'message' : 'User registered successfully' } and the serializers: class UserRegistrationSerializer(serializers.ModelSerializer): profile = UserSerializer(required=False) class Meta: model = User fields = ('email', 'password','profile' ) extra_kwargs = {'password': {'write_only' : True}} def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create_user(**validated_data) UserProfile.objects.create( user = user, first_name = profile_data['first_name'], last_name= profile_data['last_name'], ) Please what is causing the error? Thanks -
Add tag attribute and description to Django rest framework
Need help, there is serializers.py and it has the following class written in it: class menu(serializers.ModelSerializer): a = serializers.CharField(default='http://localhost/1') class Meta: model = Object fields = ['a'] At the output, I get this line: <a>http://localhost/1</a> How to write the 'menu' class correctly so that the following construction is output: <a href="http://localhost/1">Menu 1</a> Thank you! -
Is there anyway in django to create the form such that when users select on one choice it will show another set of choice that users can select on
I want to create the form such that when users select on one choice it will show another set of choices that users can select on (or show text field that user can write in). For example, if I have a form Use geographical feature Yes No When user select yes it will show another set of choices under "yes" Use geographical feature Yes randomize fixed input No Is there any possible way to implement in django and how to embed it in django html template? I am quite new to the web-dev and django. So, I am not quite sure what to look for and Googling hasn't yielded me the answer I am looking for. -
Suggestions for splitting up a Django model of 1000+ fields
I am looking for suggestions on how to deal with a database table that has 1000 or more columns and I am tying to translate it into one or many Django models. The data also needs to be filtered through API calls within the URL. Every field needs to be able to filter the rest of the data. I have come up with a few solutions and would like input or resources related to them: Just have a model with 1000+ fields - This seems like it would be a nightmare to maintain and would require a lot of brute force coding but would likely work fine if data was selectively returned. Use a JSON field to store all less frequently accessed data - The issue here would be difficulty in filtering the data using Django Filters. Split data into related models connected by One-to-One relationships, as I understand this cuts down on join operations. - This would seem to require more coding than the first option but would be more maintainable. Does anyone have any information or resources on dealing with database tables of this size? -
Django form saves and fetches <QuerySet object> instead of values
I have a simple Django 3.1.0 app I need to create in order to assign Tasks with Tags (or assign tags into tasks). Model class Task(models.Model): user = models.CharField(max_length=33) time = models.DateTimeField(auto_now_add=True) task = models.CharField(max_length=500) tags = models.CharField(max_length=100, default="None", null=True) class Tag(models.Model): tag = models.CharField(max_length=30, default="No Tag") members = models.ManyToManyField('Task', related_name="tag") class Meta: verbose_name = "tag" verbose_name_plural = "tags" view def main(request): model = Task.objects.values().all() tags = Tag.objects.values().all() form = TaskForm() con = {'context': list(model), 'form': form, 'tags': list(tags)} if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = TaskForm() return render(request, "tasks.html", con) form class TaskForm(ModelForm): class Meta: model = Task fields = ['user', 'task', 'tags'] template_name = 'tasks.html' tags = ModelMultipleChoiceField( queryset= Tag.objects.all(), widget=CheckboxSelectMultiple(), required=False, ) task_form <form method="post" class="form"> {% csrf_token %} {{form}} <input type="submit" value="Save"> </form> This returns in the tags list the items listed as: Tag object (1) Tag object (2) And when it saves when i press submit, it fetches in a table (in another template), the values saved in the text of <QuerySet [<Tag: Tag object (2)>]> That's how it stores them in the database. I have managed to extract the values as they are ('tag1','tag2') and send … -
Email activation link issue in Django 3.1.3
Well, I decided to implement an account authentication system by sending an activation link to the email of the user who just registered and here are the views and the message sent def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string( 'users/email_template.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), } ) to_email = form.cleaned_data.get('email') email = EmailMessage(mail_subject, message, to=[to_email]) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return HttpResponse('Thank you for your email confirmation. Now you can login account.') else: return HttpResponse('Activation link is invalid!') Token Generator class: from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( text_type(user.pk) + text_type(timestamp) + text_type(user.is_active) ) account_activation_token = TokenGenerator() The template with the message: {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm … -
is there a way to create superuser for django apps on heroku without using CLI?
I changed my db of my app on heroku to not use the sqlite db that is the default for django app, to use the heroku postgres database. however, I want to login to my admin portal on my heroku app, but i am not sure how to create a superuser. Also, is there a way to push my local db to my heroku db? I have been deploying through github (not using the heroku CLI, so I was wondering if there was a way without using the CLI). if there isn't a way without using the heroku CLI, could someone tell me how I would init the heroku git repository, considering the fact that I already have a GitHub repository that I have been using (I am not great with git). this is my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } import dj_database_url db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) -
How to handle a site wrapper and in Django templating?
I have a Wagtail site with the following structure: <html> <head> </head> <body> <div id="site-wrapper"> <div id="site-canvas"> <div id="site-navigation"> </div> <div id="site-mobile-navigation"> </div> <div id="content"> </div> </div> </div> </div> </body> </html> I would like to use the {% extends "base.html" %} command to utilize the above HTML structure within a site wide template, but I'm not sure how to handle extending exclusively within the the <div id="content"> element. The hope is that the navigation, header, body, etc., could all be placed in a template but that I could begin the Wagtail pages starting within the 'content' div. -
Django ManyToManyField upload multiple files getting error NoneType
I want to upload multiple file in Django. The code below is getting 'NoneType' object is not iterable. I don't understand How can i make files iterable and save in database. i have m2m field. i think i need to create FileModel before FileUploadModel. I would be grateful for any help. MODELS class FileModel(models.Model): filename = models.FileField(upload_to='files/') class FileUploadModel(models.Model): file = models.ManyToManyField(FileModel, blank=True) FORMS from .models import FileUploadModel class AForm(forms.ModelForm): file = forms.FileField(label='Select a file to upload', widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) def __init__(self, *args, **kwargs): super(AForm, self).__init__(*args, **kwargs) class Meta: model = FileUploadModel fields = '__all__' VIEWS def uploading_view(request): form = AForm(request.POST, request.FILES) if request.method == "POST": if form.is_valid(): a = form.save() # Here you have the a model already created files = request.FILES.getlist('file') # 'file' is the name of the form field. for f in files: a.file.create(filename=f) # Here you create a "b" model directly from "a" model context = { 'form': form } return render(request, 'uploading.html', context) -
My css changes are not getting reflected when i run my website
In my directory i have de following: -Proyecto -proyecto -static -css styles.css -images -tienda in my settings.py file i already added my STATICFILES_DIRS: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] And in my template called "tienda.html" i have the following: {%load static%} <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> <h3>TIENDA</h3> when i run my website with my localhost, no css changes are reflected. I already tried deleting de cache from the explorers but still i can´t see any changes.